forked from pyodide/pyodide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conftest.py
425 lines (348 loc) · 12.9 KB
/
conftest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
"""
Various common utilities for testing.
"""
import contextlib
import multiprocessing
import textwrap
import tempfile
import time
import os
import pathlib
import queue
import sys
import shutil
ROOT_PATH = pathlib.Path(__file__).parents[0].resolve()
TEST_PATH = ROOT_PATH / "test"
BUILD_PATH = ROOT_PATH / 'build'
sys.path.append(str(ROOT_PATH))
from pyodide_build._fixes import _selenium_is_connectable # noqa: E402
import selenium.webdriver.common.utils # noqa: E402
# XXX: Temporary fix for ConnectionError in selenium
selenium.webdriver.common.utils.is_connectable = _selenium_is_connectable
try:
import pytest
def pytest_addoption(parser):
group = parser.getgroup("general")
group.addoption(
'--build-dir', action="store", default=BUILD_PATH,
help="Path to the build directory")
group.addoption(
'--run-xfail', action="store_true",
help="If provided, tests marked as xfail will be run")
except ImportError:
pytest = None
class PyodideInited:
def __call__(self, driver):
inited = driver.execute_script(
"return window.pyodide && window.pyodide.runPython")
return inited is not None
class PackageLoaded:
def __call__(self, driver):
inited = driver.execute_script(
"return window.done")
return bool(inited)
def _display_driver_logs(browser, driver):
if browser == 'chrome':
print('# Selenium browser logs')
print(driver.get_log("browser"))
elif browser == 'firefox':
# browser logs are not available in GeckoDriver
# https://github.com/mozilla/geckodriver/issues/284
print('Accessing raw browser logs with Selenium is not '
'supported by Firefox.')
class SeleniumWrapper:
def __init__(self, server_port, server_hostname='127.0.0.1',
server_log=None, build_dir=None):
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import TimeoutException
if build_dir is None:
build_dir = BUILD_PATH
driver = self.get_driver()
wait = WebDriverWait(driver, timeout=20)
if not (pathlib.Path(build_dir) / 'test.html').exists():
# selenium does not expose HTTP response codes
raise ValueError(f"{(build_dir / 'test.html').resolve()} "
f"does not exist!")
driver.get(f'http://{server_hostname}:{server_port}/test.html')
try:
wait.until(PyodideInited())
except TimeoutException:
_display_driver_logs(self.browser, driver)
raise TimeoutException()
self.wait = wait
self.driver = driver
self.server_port = server_port
self.server_hostname = server_hostname
self.server_log = server_log
@property
def logs(self):
logs = self.driver.execute_script("return window.logs")
return '\n'.join(str(x) for x in logs)
def clean_logs(self):
self.driver.execute_script("window.logs = []")
def run(self, code):
return self.run_js(
'return pyodide.runPython({!r})'.format(code))
def run_async(self, code):
from selenium.common.exceptions import TimeoutException
self.run_js(
"""
window.done = false;
pyodide.runPythonAsync({!r})
.then(function(output)
{{ window.output = output; window.error = false; }},
function(output)
{{ window.output = output; window.error = true; }})
.finally(() => window.done = true);
""".format(code)
)
try:
self.wait.until(PackageLoaded())
except TimeoutException:
_display_driver_logs(self.browser, self.driver)
print(self.logs)
raise TimeoutException('runPythonAsync timed out')
return self.run_js(
"""
if (window.error) {
throw window.output;
}
return window.output;
"""
)
def run_js(self, code):
if isinstance(code, str) and code.startswith('\n'):
# we have a multiline string, fix indentation
code = textwrap.dedent(code)
catch = f"""
Error.stackTraceLimit = Infinity;
try {{ {code} }}
catch (error) {{ console.log(error.stack); throw error; }}"""
return self.driver.execute_script(catch)
def setup_webworker(self):
hostname = self.server_hostname
port = self.server_port
url = f'http://{hostname}:{port}/webworker_dev.js'
self.run_js(
f"""
window.done = false;
window.pyodideWorker = new Worker( '{url}' );
window.pyodideWorker.onerror = function(e) {{
window.output = e;
window.error = true;
window.done = true;
}};
window.pyodideWorker.onmessage = function(e) {{
if (e.data.results) {{
window.output = e.data.results;
window.error = false;
}} else {{
window.output = e.data.error;
window.error = true;
}}
window.done = true;
}};
"""
)
def run_webworker(self, code):
from selenium.common.exceptions import TimeoutException
self.setup_webworker()
if isinstance(code, str) and code.startswith('\n'):
# we have a multiline string, fix indentation
code = textwrap.dedent(code)
self.run_js(
"""
var data = {{
python: {!r}
}};
window.pyodideWorker.postMessage(data);
""".format(code)
)
try:
self.wait.until(PackageLoaded())
except TimeoutException:
_display_driver_logs(self.browser, self.driver)
print(self.logs)
raise TimeoutException('run_webworker timed out')
return self.run_js(
"""
if (window.error) {
if (window.output instanceof Error) {
throw window.output;
} else {
throw new Error(String(window.output))
}
}
return window.output;
"""
)
def load_package(self, packages):
self.run_js(
'window.done = false\n' +
'pyodide.loadPackage({!r})'.format(packages) +
'.finally(function() { window.done = true; })')
__tracebackhide__ = True
self.wait_until_packages_loaded()
def wait_until_packages_loaded(self):
from selenium.common.exceptions import TimeoutException
__tracebackhide__ = True
try:
self.wait.until(PackageLoaded())
except TimeoutException:
_display_driver_logs(self.browser, self.driver)
print(self.logs)
raise TimeoutException('wait_until_packages_loaded timed out')
@property
def urls(self):
for handle in self.driver.window_handles:
self.driver.switch_to.window(handle)
yield self.driver.current_url
class FirefoxWrapper(SeleniumWrapper):
browser = 'firefox'
def get_driver(self):
from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options
from selenium.common.exceptions import JavascriptException
options = Options()
options.add_argument('-headless')
self.JavascriptException = JavascriptException
return Firefox(
executable_path='geckodriver', options=options)
class ChromeWrapper(SeleniumWrapper):
browser = 'chrome'
def get_driver(self):
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import WebDriverException
options = Options()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
self.JavascriptException = WebDriverException
return Chrome(options=options)
if pytest is not None:
@pytest.fixture(params=['firefox', 'chrome'])
def selenium_standalone(request, web_server_main):
server_hostname, server_port, server_log = web_server_main
if request.param == 'firefox':
cls = FirefoxWrapper
elif request.param == 'chrome':
cls = ChromeWrapper
selenium = cls(build_dir=request.config.option.build_dir,
server_port=server_port,
server_hostname=server_hostname,
server_log=server_log)
try:
yield selenium
finally:
print(selenium.logs)
selenium.driver.quit()
@pytest.fixture(params=['firefox', 'chrome'], scope='module')
def _selenium_cached(request, web_server_main):
# Cached selenium instance. This is a copy-paste of
# selenium_standalone to avoid fixture scope issues
server_hostname, server_port, server_log = web_server_main
if request.param == 'firefox':
cls = FirefoxWrapper
elif request.param == 'chrome':
cls = ChromeWrapper
selenium = cls(build_dir=request.config.option.build_dir,
server_port=server_port,
server_hostname=server_hostname,
server_log=server_log)
try:
yield selenium
finally:
selenium.driver.quit()
@pytest.fixture
def selenium(_selenium_cached):
# selenium instance cached at the module level
try:
_selenium_cached.clean_logs()
yield _selenium_cached
finally:
print(_selenium_cached.logs)
@pytest.fixture(scope='session')
def web_server_main(request):
with spawn_web_server(request.config.option.build_dir) as output:
yield output
@pytest.fixture(scope='session')
def web_server_secondary(request):
with spawn_web_server(request.config.option.build_dir) as output:
yield output
@contextlib.contextmanager
def spawn_web_server(build_dir=None):
if build_dir is None:
build_dir = BUILD_PATH
tmp_dir = tempfile.mkdtemp()
log_path = pathlib.Path(tmp_dir) / 'http-server.log'
q = multiprocessing.Queue()
p = multiprocessing.Process(target=run_web_server,
args=(q, log_path, build_dir))
try:
p.start()
port = q.get()
hostname = '127.0.0.1'
print(f"Spawning webserver at http://{hostname}:{port} "
f"(see logs in {log_path})")
yield hostname, port, log_path
finally:
q.put("TERMINATE")
p.join()
shutil.rmtree(tmp_dir)
def run_web_server(q, log_filepath, build_dir):
"""Start the HTTP web server
Parameters
----------
q : Queue
communication queue
log_path : pathlib.Path
path to the file where to store the logs
"""
import http.server
import socketserver
os.chdir(build_dir)
log_fh = log_filepath.open('w', buffering=1)
sys.stdout = log_fh
sys.stderr = log_fh
class Handler(http.server.CGIHTTPRequestHandler):
def translate_path(self, path):
if path.startswith('/test/'):
return TEST_PATH / path[6:]
return super(Handler, self).translate_path(path)
def is_cgi(self):
if self.path.startswith('/test/') and self.path.endswith('.cgi'):
self.cgi_info = '/test', self.path[6:]
return True
return False
def log_message(self, format_, *args):
print("[%s] source: %s:%s - %s"
% (self.log_date_time_string(),
*self.client_address,
format_ % args))
def end_headers(self):
# Enable Cross-Origin Resource Sharing (CORS)
self.send_header('Access-Control-Allow-Origin', '*')
super().end_headers()
Handler.extensions_map['.wasm'] = 'application/wasm'
with socketserver.TCPServer(("", 0), Handler) as httpd:
host, port = httpd.server_address
print(f"Starting webserver at http://{host}:{port}")
httpd.server_name = 'test-server'
httpd.server_port = port
q.put(port)
def service_actions():
try:
if q.get(False) == "TERMINATE":
print('Stopping server...')
sys.exit(0)
except queue.Empty:
pass
httpd.service_actions = service_actions
httpd.serve_forever()
if (__name__ == '__main__'
and multiprocessing.current_process().name == 'MainProcess'
and not hasattr(sys, "_pytest_session")):
with spawn_web_server():
# run forever
while True:
time.sleep(1)