Project

General

Profile

Download (7.16 KB) Statistics
| Branch: | Tag: | Revision:

haketilo / test / unit / test_popup.py @ 42fe4405

1
# SPDX-License-Identifier: CC0-1.0
2

    
3
"""
4
Haketilo unit tests - repository querying
5
"""
6

    
7
# This file is part of Haketilo
8
#
9
# Copyright (C) 2022 Wojtek Kosior <koszko@koszko.org>
10
#
11
# This program is free software: you can redistribute it and/or modify
12
# it under the terms of the CC0 1.0 Universal License as published by
13
# the Creative Commons Corporation.
14
#
15
# This program is distributed in the hope that it will be useful,
16
# but WITHOUT ANY WARRANTY; without even the implied warranty of
17
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
# CC0 1.0 Universal License for more details.
19

    
20
import pytest
21
import json
22
from selenium.webdriver.support.ui import WebDriverWait
23

    
24
from ..extension_crafting import ExtraHTML
25
from ..script_loader import load_script
26
from .utils import *
27

    
28
def reload_with_target(driver, target):
29
    current_url = driver.execute_script('return location.href')
30
    driver.execute_script(
31
        '''
32
        window.location.href = arguments[0];
33
        window.location.reload();
34
        ''',
35
        f'{current_url}#{target}')
36

    
37
unprivileged_page_info = {
38
    'url': 'https://example_a.com/something',
39
    'allow': False
40
}
41

    
42
mocked_page_infos = {
43
    'privileged': {
44
        'url': 'moz-extension://<some-id>/file.html',
45
        'privileged': True
46
    },
47
    'blocked_default': unprivileged_page_info,
48
    'allowed_default': {
49
        **unprivileged_page_info,
50
        'allow': True
51
    },
52
    'blocked_rule': {
53
        **unprivileged_page_info,
54
        'mapping': '~allow'
55
    },
56
    'allowed_rule': {
57
        **unprivileged_page_info,
58
        'allow': True,
59
        'mapping': '~allow'
60
    },
61
    'mapping': {
62
        **unprivileged_page_info,
63
        'mapping': 'm1',
64
        'payload': {'identifier': 'res1'}
65
    }
66
}
67

    
68
tab_mock_js = '''
69
;
70
const mocked_page_info = (%s)[/#mock_page_info-(.*)$/.exec(document.URL)[1]];
71
browser.tabs.sendMessage = async function(tab_id, msg) {
72
    const this_tab_id = (await browser.tabs.getCurrent()).id;
73
    if (tab_id !== this_tab_id)
74
        throw `not current tab id (${tab_id} instead of ${this_tab_id})`;
75

    
76
    if (msg[0] === "page_info") {
77
        return mocked_page_info;
78
    } else if (msg[0] === "repo_query") {
79
        const response = await fetch(msg[1]);
80
        if (!response)
81
            return {error: "Something happened :o"};
82

    
83
        const result = {ok: response.ok, status: response.status};
84
        try {
85
            result.json = await response.json();
86
        } catch(e) {
87
            result.error_json = "" + e;
88
        }
89
        return result;
90
    } else {
91
        throw `bad sendMessage message type: '${msg[0]}'`;
92
    }
93
}
94

    
95
const old_tabs_query = browser.tabs.query;
96
browser.tabs.query = async function(query) {
97
    const tabs = await old_tabs_query(query);
98
    tabs.forEach(t => t.url = mocked_page_info.url);
99
    return tabs;
100
}
101
''' % json.dumps(mocked_page_infos)
102

    
103
popup_ext_data = {
104
    'background_script': broker_js,
105
    'extra_html': ExtraHTML(
106
        'html/popup.html',
107
        {
108
            'common/browser.js':   tab_mock_js,
109
            'common/indexeddb.js': '; set_repo("https://hydril.la/");'
110
        },
111
        wrap_into_htmldoc=False
112
    ),
113
    'navigate_to': 'html/popup.html'
114
}
115

    
116
@pytest.mark.ext_data(popup_ext_data)
117
@pytest.mark.usefixtures('webextension')
118
@pytest.mark.parametrize('page_info_key', ['', *mocked_page_infos.keys()])
119
def test_popup_display(driver, execute_in_page, page_info_key):
120
    """
121
    Test popup viewing while on a page. Test parametrized with different
122
    possible values of page_info object passed in message from the content
123
    script.
124
    """
125
    reload_with_target(driver, f'mock_page_info-{page_info_key}')
126

    
127
    by_id = driver.execute_script('''
128
    const nodes = [...document.querySelectorAll("[id]")];
129
    return nodes.reduce((ob, node) => Object.assign(ob, {[node.id]: node}), {});
130
    ''');
131

    
132
    if page_info_key == '':
133
        error_msg = 'Page info not avaialable. Try reloading the page.'
134
        error_msg_shown = lambda d: by_id['loading_info'].text == error_msg
135
        WebDriverWait(driver, 10).until(error_msg_shown)
136
        return
137

    
138
    WebDriverWait(driver, 10).until(lambda d: by_id['info_form'].is_displayed())
139
    assert (page_info_key == 'privileged') == \
140
        by_id['privileged_page_info'].is_displayed()
141
    assert (page_info_key == 'privileged') ^ \
142
        by_id['unprivileged_page_info'].is_displayed()
143
    assert by_id['page_url'].text == mocked_page_infos[page_info_key]['url']
144
    assert not by_id['repo_query_container'].is_displayed()
145

    
146
    if 'blocked' in page_info_key or page_info_key == 'mapping':
147
        assert by_id['scripts_blocked'].text.lower() == 'yes'
148
    elif 'allowed' in page_info_key:
149
        assert by_id['scripts_blocked'].text.lower() == 'no'
150

    
151
    if page_info_key == 'mapping':
152
        assert by_id['injected_payload'].text == 'res1'
153
    elif page_info_key != 'privileged':
154
        assert by_id['injected_payload'].text == 'None'
155

    
156
    mapping_text = by_id['mapping_used'].text
157
    if page_info_key == 'mapping':
158
        assert mapping_text == 'm1'
159

    
160
    if 'allowed' in page_info_key:
161
        'None (scripts allowed by' in mapping_text
162
    elif 'blocked' in page_info_key:
163
        'None (scripts blocked by' in mapping_text
164

    
165
    if 'rule' in page_info_key:
166
        'by a rule)' in mapping_text
167
    elif 'default' in page_info_key:
168
        'by default_policy)' in mapping_text
169

    
170
@pytest.mark.ext_data(popup_ext_data)
171
@pytest.mark.usefixtures('webextension')
172
def test_popup_repo_query(driver, execute_in_page):
173
    """
174
    Test opening and closing the repo query view in popup.
175
    """
176
    reload_with_target(driver, f'mock_page_info-blocked_rule')
177

    
178
    search_but = driver.find_element_by_id("search_resources_but")
179
    WebDriverWait(driver, 10).until(lambda d: search_but.is_displayed())
180
    search_but.click()
181
    containers = dict([(name, driver.find_element_by_id(f'{name}_container'))
182
                       for name in ('page_info', 'repo_query')])
183
    assert not containers['page_info'].is_displayed()
184
    assert containers['repo_query'].is_displayed()
185
    shown = lambda d: 'https://hydril.la/' in containers['repo_query'].text
186
    WebDriverWait(driver, 10).until(shown)
187

    
188
    # Click the "Show results" button.
189
    selector = '.repo_query_buttons > button:first-child'
190
    driver.find_element_by_css_selector(selector).click()
191
    shown = lambda d: 'MAPPING_A' in containers['repo_query'].text
192
    WebDriverWait(driver, 10).until(shown)
193

    
194
    # Click the "Cancel" button
195
    selector = '.repo_query_bottom_buttons > button'
196
    driver.find_element_by_css_selector(selector).click()
197
    assert containers['page_info'].is_displayed()
198
    assert not containers['repo_query'].is_displayed()
199

    
200
@pytest.mark.ext_data(popup_ext_data)
201
@pytest.mark.usefixtures('webextension')
202
def test_popup_settings_opening(driver, execute_in_page):
203
    """
204
    Test opening the settings page from popup through button click.
205
    """
206
    driver.find_element_by_id("settings_but").click()
207

    
208
    first_handle = driver.current_window_handle
209
    WebDriverWait(driver, 10).until(lambda d: len(d.window_handles) == 2)
210
    new_handle = [h for h in driver.window_handles if h != first_handle][0]
211

    
212
    driver.switch_to.window(new_handle)
213
    driver.implicitly_wait(10)
214
    assert "Extension's options page for testing" in \
215
        driver.find_element_by_tag_name("h1").text
(18-18/24)