Project

General

Profile

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

haketilo / test / conftest.py @ 4c6a2323

1
# SPDX-License-Identifier: GPL-3.0-or-later
2

    
3
"""
4
Common fixtures for Haketilo unit tests
5
"""
6

    
7
# This file is part of Haketilo.
8
#
9
# Copyright (C) 2021 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 GNU General Public License as published by
13
# the Free Software Foundation, either version 3 of the License, or
14
# (at your option) any later version.
15
#
16
# This program is distributed in the hope that it will be useful,
17
# but WITHOUT ANY WARRANTY; without even the implied warranty of
18
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
# GNU General Public License for more details.
20
#
21
# You should have received a copy of the GNU General Public License
22
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
23
#
24
# I, Wojtek Kosior, thereby promise not to sue for violation of this file's
25
# license. Although I request that you do not make use of this code in a
26
# proprietary program, I am not going to enforce this in court.
27

    
28
import pytest
29
from pathlib import Path
30
from tempfile import TemporaryDirectory
31
from selenium.webdriver.common.by import By
32
from selenium.webdriver.support.ui import WebDriverWait
33
from selenium.webdriver.support import expected_conditions as EC
34

    
35
from .profiles           import firefox_safe_mode
36
from .server             import do_an_internet
37
from .extension_crafting import make_extension
38
from .world_wide_library import start_serving_script, dump_scripts
39
from .misc_constants     import here
40

    
41
@pytest.fixture(scope="session")
42
def proxy():
43
    httpd = do_an_internet()
44
    yield httpd
45
    httpd.shutdown()
46

    
47
@pytest.fixture(scope="session")
48
def _driver(proxy):
49
    with firefox_safe_mode() as driver:
50
        yield driver
51
        driver.quit()
52

    
53
def close_all_but_one_window(driver):
54
    while len(driver.window_handles) > 1:
55
        driver.switch_to.window(driver.window_handles[-1])
56
        driver.close()
57
    driver.switch_to.window(driver.window_handles[0])
58

    
59
@pytest.fixture()
60
def driver(_driver, request):
61
    nav_target = request.node.get_closest_marker('get_page')
62
    close_all_but_one_window(_driver)
63
    _driver.get(nav_target.args[0] if nav_target else 'about:blank')
64
    _driver.implicitly_wait(0)
65
    yield _driver
66

    
67
@pytest.fixture()
68
def webextension(driver, request):
69
    ext_data = request.node.get_closest_marker('ext_data')
70
    if ext_data is None:
71
        raise Exception('"webextension" fixture requires "ext_data" marker to be set')
72
    ext_data = ext_data.args[0].copy()
73

    
74
    navigate_to = ext_data.get('navigate_to')
75
    if navigate_to is not None:
76
        del ext_data['navigate_to']
77

    
78
    driver.get('https://gotmyowndoma.in/')
79
    ext_path = make_extension(Path(driver.firefox_profile.path), **ext_data)
80
    addon_id = driver.install_addon(str(ext_path), temporary=True)
81
    WebDriverWait(driver, 10).until(
82
        EC.url_matches('^moz-extension://.*')
83
    )
84

    
85
    if navigate_to is not None:
86
        testpage_url = driver.execute_script('return window.location.href;')
87
        driver.get(testpage_url.replace('testpage.html', navigate_to))
88

    
89
    yield
90

    
91
    close_all_but_one_window(driver)
92
    driver.get('https://gotmyowndoma.in/')
93
    driver.uninstall_addon(addon_id)
94
    ext_path.unlink()
95

    
96
@pytest.fixture()
97
def haketilo(driver):
98
    addon_id = driver.install_addon(str(here.parent / 'mozilla-build.zip'),
99
                                    temporary=True)
100

    
101
    yield
102

    
103
    driver.uninstall_addon(addon_id)
104

    
105
script_injector_script = '''\
106
/*
107
 * Selenium by default executes scripts in some weird one-time context. We want
108
 * separately-loaded scripts to be able to access global variables defined
109
 * before, including those declared with `const` or `let`. To achieve that, we
110
 * run our scripts by injecting them into the page with a <script> tag that runs
111
 * javascript served by our proxy. We use custom properties of the `window`
112
 * object to communicate with injected code.
113
 */
114
const inject = async () => {
115
    delete window.haketilo_selenium_return_value;
116
    delete window.haketilo_selenium_exception;
117
    window.returnval = val => window.haketilo_selenium_return_value = val;
118

    
119
    const injectee = document.createElement('script');
120
    injectee.src = arguments[0];
121
    injectee.type = "application/javascript";
122
    injectee.async = true;
123
    const prom = new Promise(cb => injectee.onload = cb);
124

    
125
    window.arguments = arguments[1];
126
    document.body.append(injectee);
127

    
128
    await prom;
129

    
130
    /*
131
     * To ease debugging, we want this script to signal all exceptions from the
132
     * injectee.
133
     */
134
    if (window.haketilo_selenium_exception !== false)
135
        throw ['haketilo_selenium_error',
136
               'Error in injected script! Check your geckodriver.log and ./injected_scripts/!'];
137

    
138
    return window.haketilo_selenium_return_value;
139
}
140
return inject();
141
'''
142

    
143
def _execute_in_page_context(driver, script, args):
144
    script = script + '\n;\nwindow.haketilo_selenium_exception = false;'
145
    script_url = start_serving_script(script)
146

    
147
    try:
148
        result = driver.execute_script(script_injector_script, script_url, args)
149
        if type(result) is list and len(result) == 2 and \
150
           result[0] == 'haketilo_selenium_error':
151
            raise Exception(result[1])
152
        return result
153
    except Exception as e:
154
        dump_scripts()
155
        raise e from None
156

    
157
# Some fixtures here just define functions that operate on driver. We should
158
# consider making them into webdriver wrapper class methods.
159

    
160
@pytest.fixture()
161
def execute_in_page(driver):
162
    def do_execute(script, *args):
163
        return _execute_in_page_context(driver, script, args)
164

    
165
    yield do_execute
166

    
167
@pytest.fixture()
168
def wait_elem_text(driver):
169
    def do_wait(id, text):
170
        WebDriverWait(driver, 10).until(
171
            EC.text_to_be_present_in_element((By.ID, id), text)
172
        )
173

    
174
    yield do_wait
(3-3/11)