pyodide/test/conftest.py

248 lines
6.7 KiB
Python
Raw Normal View History

2018-03-30 14:51:13 +00:00
"""
Various common utilities for testing.
"""
2018-07-09 19:09:49 +00:00
import atexit
import multiprocessing
2018-09-07 12:01:58 +00:00
import textwrap
2018-07-09 19:09:49 +00:00
import os
2018-03-30 14:51:13 +00:00
import pathlib
2018-07-09 21:15:04 +00:00
import queue
import sys
2018-03-30 14:51:13 +00:00
2018-04-05 22:07:33 +00:00
try:
import pytest
except ImportError:
pytest = None
2018-03-30 14:51:13 +00:00
TEST_PATH = pathlib.Path(__file__).parents[0].resolve()
BUILD_PATH = TEST_PATH / '..' / 'build'
class PyodideInited:
def __call__(self, driver):
2018-05-04 17:09:32 +00:00
inited = driver.execute_script(
"return window.pyodide && window.pyodide.runPython")
2018-03-30 14:51:13 +00:00
return inited is not None
2018-05-04 17:09:32 +00:00
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
2018-08-28 15:45:42 +00:00
print('Accessing raw browser logs with Selenium is not '
'supported by Firefox.')
2018-03-30 14:51:13 +00:00
class SeleniumWrapper:
def __init__(self):
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import TimeoutException
2018-03-30 14:51:13 +00:00
2018-07-09 19:09:49 +00:00
driver = self.get_driver()
2018-03-30 14:51:13 +00:00
wait = WebDriverWait(driver, timeout=20)
2018-08-28 09:59:12 +00:00
if not (BUILD_PATH / 'test.html').exists():
# selenium does not expose HTTP response codes
raise ValueError(f"{(BUILD_PATH / 'test.html').resolve()} "
f"does not exist!")
2018-07-09 21:15:04 +00:00
driver.get(f'http://127.0.0.1:{PORT}/test.html')
try:
wait.until(PyodideInited())
except TimeoutException as exc:
_display_driver_logs(self.browser, driver)
raise TimeoutException()
2018-05-04 17:09:32 +00:00
self.wait = wait
2018-03-30 14:51:13 +00:00
self.driver = driver
@property
def logs(self):
2018-08-22 10:47:04 +00:00
logs = self.driver.execute_script("return window.logs")
return '\n'.join(str(x) for x in logs)
2018-03-30 14:51:13 +00:00
2018-08-22 12:37:23 +00:00
def clean_logs(self):
self.driver.execute_script("window.logs = []")
2018-03-30 14:51:13 +00:00
def run(self, code):
2018-09-07 12:01:58 +00:00
if isinstance(code, str) and code.startswith('\n'):
# we have a multiline string, fix indentation
code = textwrap.dedent(code)
2018-05-04 17:09:32 +00:00
return self.run_js(
2018-03-30 14:51:13 +00:00
'return pyodide.runPython({!r})'.format(code))
2018-05-04 17:09:32 +00:00
def run_js(self, code):
2018-09-07 12:01:58 +00:00
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)
2018-05-04 17:09:32 +00:00
def load_package(self, packages):
self.run_js(
2018-06-21 14:14:25 +00:00
'window.done = false\n' +
'pyodide.loadPackage({!r})'.format(packages) +
'.finally(function() { window.done = true; })')
self.wait_until_packages_loaded()
def wait_until_packages_loaded(self):
from selenium.common.exceptions import TimeoutException
try:
self.wait.until(PackageLoaded())
except TimeoutException as exc:
_display_driver_logs(self.browser, self.driver)
print(self.logs)
raise TimeoutException()
2018-05-04 17:09:32 +00:00
2018-03-30 14:51:13 +00:00
@property
def urls(self):
for handle in self.driver.window_handles:
self.driver.switch_to.window(handle)
yield self.driver.current_url
2018-07-09 19:09:49 +00:00
class FirefoxWrapper(SeleniumWrapper):
browser = 'firefox'
2018-07-09 19:09:49 +00:00
def get_driver(self):
from selenium.webdriver import Firefox
from selenium.webdriver.firefox.options import Options
from selenium.common.exceptions import JavascriptException
2018-07-09 19:09:49 +00:00
options = Options()
options.add_argument('-headless')
self.JavascriptException = JavascriptException
2018-07-09 19:09:49 +00:00
return Firefox(
executable_path='geckodriver', firefox_options=options)
class ChromeWrapper(SeleniumWrapper):
browser = 'chrome'
2018-07-09 19:09:49 +00:00
def get_driver(self):
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import WebDriverException
2018-07-09 19:09:49 +00:00
options = Options()
options.add_argument('--headless')
self.JavascriptException = WebDriverException
2018-07-09 19:09:49 +00:00
return Chrome(chrome_options=options)
2018-04-05 22:07:33 +00:00
if pytest is not None:
@pytest.fixture(params=['firefox', 'chrome'])
2018-08-28 13:17:38 +00:00
def selenium_standalone(request):
2018-07-09 19:09:49 +00:00
if request.param == 'firefox':
cls = FirefoxWrapper
elif request.param == 'chrome':
cls = ChromeWrapper
selenium = cls()
try:
yield selenium
finally:
2018-08-22 10:47:04 +00:00
print(selenium.logs)
selenium.driver.quit()
2018-07-09 19:09:49 +00:00
@pytest.fixture(params=['firefox', 'chrome'], scope='module')
2018-08-28 13:17:38 +00:00
def _selenium_cached(request):
2018-08-20 17:10:32 +00:00
# Cached selenium instance. This is a copy-paste of
# selenium_standalone to avoid fixture scope issues
if request.param == 'firefox':
cls = FirefoxWrapper
elif request.param == 'chrome':
cls = ChromeWrapper
selenium = cls()
try:
yield selenium
finally:
selenium.driver.quit()
@pytest.fixture
def selenium(_selenium_cached):
2018-08-20 17:10:32 +00:00
# selenium instance cached at the module level
try:
2018-08-22 12:37:23 +00:00
_selenium_cached.clean_logs()
yield _selenium_cached
finally:
2018-08-22 12:37:23 +00:00
print(_selenium_cached.logs)
2018-07-09 19:09:49 +00:00
2018-07-09 21:15:04 +00:00
PORT = 0
2018-07-09 19:09:49 +00:00
def spawn_web_server():
2018-07-09 21:15:04 +00:00
global PORT
2018-07-09 19:09:49 +00:00
print("Spawning webserver...")
2018-07-09 21:15:04 +00:00
q = multiprocessing.Queue()
p = multiprocessing.Process(target=run_web_server, args=(q,))
2018-07-09 19:09:49 +00:00
def shutdown_webserver():
2018-07-09 21:15:04 +00:00
q.put("TERMINATE")
p.join()
2018-07-09 19:09:49 +00:00
atexit.register(shutdown_webserver)
p.start()
2018-07-09 21:15:04 +00:00
PORT = q.get()
2018-07-09 19:09:49 +00:00
2018-07-09 21:15:04 +00:00
def run_web_server(q):
2018-07-09 19:09:49 +00:00
import http.server
import socketserver
print("Running webserver...")
os.chdir(BUILD_PATH)
Handler = http.server.SimpleHTTPRequestHandler
Handler.extensions_map['.wasm'] = 'application/wasm'
def dummy_log(*args, **kwargs):
pass
Handler.log_message = dummy_log
2018-07-09 21:15:04 +00:00
with socketserver.TCPServer(("", 0), Handler) as httpd:
host, port = httpd.server_address
print("serving at port", port)
q.put(port)
def service_actions():
try:
if q.get(False) == "TERMINATE":
sys.exit(0)
httpd.shutdown()
except queue.Empty:
pass
httpd.service_actions = service_actions
2018-07-09 19:09:49 +00:00
httpd.serve_forever()
2018-08-23 08:32:52 +00:00
@pytest.fixture
def web_server():
return '127.0.0.1', PORT
2018-07-09 19:09:49 +00:00
if multiprocessing.current_process().name == 'MainProcess':
spawn_web_server()