2018-03-30 14:51:13 +00:00
|
|
|
"""
|
|
|
|
Various common utilities for testing.
|
|
|
|
"""
|
|
|
|
|
2018-09-18 17:04:53 +00:00
|
|
|
import contextlib
|
2018-07-09 19:09:49 +00:00
|
|
|
import multiprocessing
|
2018-09-07 12:01:58 +00:00
|
|
|
import textwrap
|
2018-09-18 17:04:53 +00:00
|
|
|
import tempfile
|
|
|
|
import time
|
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-09-18 17:04:53 +00:00
|
|
|
import shutil
|
2018-03-30 14:51:13 +00:00
|
|
|
|
2018-10-02 08:39:25 +00:00
|
|
|
TEST_PATH = pathlib.Path(__file__).parents[0].resolve()
|
|
|
|
BUILD_PATH = TEST_PATH / '..' / 'build'
|
|
|
|
|
2018-10-04 11:24:57 +00:00
|
|
|
sys.path.append(TEST_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
|
|
|
|
|
2018-04-05 22:07:33 +00:00
|
|
|
try:
|
|
|
|
import pytest
|
2018-03-30 14:51:13 +00:00
|
|
|
|
2018-10-02 08:39:25 +00:00
|
|
|
def pytest_addoption(parser):
|
|
|
|
group = parser.getgroup("general")
|
|
|
|
group.addoption(
|
|
|
|
'--build-dir', action="store", default=BUILD_PATH,
|
|
|
|
help="Path to the build directory")
|
2018-10-03 14:36:45 +00:00
|
|
|
group.addoption(
|
|
|
|
'--run-xfail', action="store_true",
|
|
|
|
help="If provided, tests marked as xfail will be run")
|
2018-03-30 14:51:13 +00:00
|
|
|
|
2018-10-02 08:39:25 +00:00
|
|
|
except ImportError:
|
|
|
|
pytest = None
|
2018-03-30 14:51:13 +00:00
|
|
|
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
|
|
|
|
2018-08-28 14:30:46 +00:00
|
|
|
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-08-28 14:30:46 +00:00
|
|
|
|
|
|
|
|
2018-03-30 14:51:13 +00:00
|
|
|
class SeleniumWrapper:
|
2018-10-03 12:38:27 +00:00
|
|
|
def __init__(self, server_port, server_hostname='127.0.0.1',
|
|
|
|
server_log=None, build_dir=None):
|
2018-03-30 14:51:13 +00:00
|
|
|
from selenium.webdriver.support.wait import WebDriverWait
|
2018-08-28 14:30:46 +00:00
|
|
|
from selenium.common.exceptions import TimeoutException
|
2018-03-30 14:51:13 +00:00
|
|
|
|
2018-10-03 12:38:27 +00:00
|
|
|
if build_dir is None:
|
|
|
|
build_dir = BUILD_PATH
|
|
|
|
|
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-10-02 08:39:25 +00:00
|
|
|
if not (pathlib.Path(build_dir) / 'test.html').exists():
|
2018-08-28 09:59:12 +00:00
|
|
|
# selenium does not expose HTTP response codes
|
2018-10-02 08:39:25 +00:00
|
|
|
raise ValueError(f"{(build_dir / 'test.html').resolve()} "
|
2018-08-28 09:59:12 +00:00
|
|
|
f"does not exist!")
|
2018-09-18 17:04:53 +00:00
|
|
|
driver.get(f'http://{server_hostname}:{server_port}/test.html')
|
2018-08-28 14:30:46 +00:00
|
|
|
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
|
2018-09-18 17:04:53 +00:00
|
|
|
self.server_port = server_port
|
|
|
|
self.server_hostname = server_hostname
|
|
|
|
self.server_log = server_log
|
2018-03-30 14:51:13 +00:00
|
|
|
|
|
|
|
@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-10-10 18:17:29 +00:00
|
|
|
def run_async(self, code):
|
|
|
|
from selenium.common.exceptions import TimeoutException
|
|
|
|
if isinstance(code, str) and code.startswith('\n'):
|
|
|
|
# we have a multiline string, fix indentation
|
|
|
|
code = textwrap.dedent(code)
|
|
|
|
self.run_js(
|
|
|
|
"""
|
|
|
|
window.done = false;
|
|
|
|
pyodide.runPythonAsync({!r})
|
2018-10-10 18:38:58 +00:00
|
|
|
.then(function(output)
|
|
|
|
{{ window.output = output; window.error = false; }},
|
|
|
|
function(output)
|
|
|
|
{{ window.output = output; window.error = true; }})
|
2018-10-10 18:17:29 +00:00
|
|
|
.finally(() => window.done = true);
|
|
|
|
""".format(code)
|
|
|
|
)
|
|
|
|
try:
|
|
|
|
self.wait.until(PackageLoaded())
|
|
|
|
except TimeoutException as exc:
|
|
|
|
_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;
|
|
|
|
"""
|
|
|
|
)
|
|
|
|
|
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)
|
2018-07-23 15:09:16 +00:00
|
|
|
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) +
|
2018-09-06 19:20:01 +00:00
|
|
|
'.finally(function() { window.done = true; })')
|
2018-09-20 10:51:11 +00:00
|
|
|
__tracebackhide__ = True
|
2018-09-06 14:38:32 +00:00
|
|
|
self.wait_until_packages_loaded()
|
|
|
|
|
|
|
|
def wait_until_packages_loaded(self):
|
|
|
|
from selenium.common.exceptions import TimeoutException
|
|
|
|
|
2018-09-20 10:51:11 +00:00
|
|
|
__tracebackhide__ = True
|
2018-08-28 14:30:46 +00:00
|
|
|
try:
|
|
|
|
self.wait.until(PackageLoaded())
|
|
|
|
except TimeoutException as exc:
|
|
|
|
_display_driver_logs(self.browser, self.driver)
|
|
|
|
print(self.logs)
|
2018-09-20 10:51:11 +00:00
|
|
|
raise TimeoutException('wait_until_packages_loaded timed out')
|
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):
|
2018-08-20 15:09:23 +00:00
|
|
|
|
|
|
|
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
|
2018-07-10 00:59:03 +00:00
|
|
|
from selenium.common.exceptions import JavascriptException
|
2018-07-09 19:09:49 +00:00
|
|
|
|
|
|
|
options = Options()
|
|
|
|
options.add_argument('-headless')
|
2018-07-10 00:59:03 +00:00
|
|
|
|
|
|
|
self.JavascriptException = JavascriptException
|
|
|
|
|
2018-07-09 19:09:49 +00:00
|
|
|
return Firefox(
|
2018-09-10 19:08:14 +00:00
|
|
|
executable_path='geckodriver', options=options)
|
2018-07-09 19:09:49 +00:00
|
|
|
|
|
|
|
|
|
|
|
class ChromeWrapper(SeleniumWrapper):
|
2018-08-20 15:09:23 +00:00
|
|
|
|
|
|
|
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
|
2018-07-10 00:59:03 +00:00
|
|
|
from selenium.common.exceptions import WebDriverException
|
2018-07-09 19:09:49 +00:00
|
|
|
|
|
|
|
options = Options()
|
|
|
|
options.add_argument('--headless')
|
2018-07-10 00:59:03 +00:00
|
|
|
|
|
|
|
self.JavascriptException = WebDriverException
|
|
|
|
|
2018-09-10 19:08:14 +00:00
|
|
|
return Chrome(options=options)
|
2018-07-09 19:09:49 +00:00
|
|
|
|
|
|
|
|
2018-04-05 22:07:33 +00:00
|
|
|
if pytest is not None:
|
2018-08-20 17:02:12 +00:00
|
|
|
@pytest.fixture(params=['firefox', 'chrome'])
|
2018-09-18 17:04:53 +00:00
|
|
|
def selenium_standalone(request, web_server_main):
|
|
|
|
server_hostname, server_port, server_log = web_server_main
|
2018-07-09 19:09:49 +00:00
|
|
|
if request.param == 'firefox':
|
|
|
|
cls = FirefoxWrapper
|
|
|
|
elif request.param == 'chrome':
|
|
|
|
cls = ChromeWrapper
|
2018-10-02 08:39:25 +00:00
|
|
|
selenium = cls(build_dir=request.config.option.build_dir,
|
|
|
|
server_port=server_port,
|
2018-09-18 17:04:53 +00:00
|
|
|
server_hostname=server_hostname,
|
|
|
|
server_log=server_log)
|
2018-04-20 13:52:54 +00:00
|
|
|
try:
|
|
|
|
yield selenium
|
|
|
|
finally:
|
2018-08-22 10:47:04 +00:00
|
|
|
print(selenium.logs)
|
2018-04-20 13:52:54 +00:00
|
|
|
selenium.driver.quit()
|
2018-07-09 19:09:49 +00:00
|
|
|
|
2018-08-20 17:02:12 +00:00
|
|
|
@pytest.fixture(params=['firefox', 'chrome'], scope='module')
|
2018-09-18 17:04:53 +00:00
|
|
|
def _selenium_cached(request, web_server_main):
|
2018-08-20 17:10:32 +00:00
|
|
|
# Cached selenium instance. This is a copy-paste of
|
|
|
|
# selenium_standalone to avoid fixture scope issues
|
2018-09-18 17:04:53 +00:00
|
|
|
server_hostname, server_port, server_log = web_server_main
|
2018-08-20 17:02:12 +00:00
|
|
|
if request.param == 'firefox':
|
|
|
|
cls = FirefoxWrapper
|
|
|
|
elif request.param == 'chrome':
|
|
|
|
cls = ChromeWrapper
|
2018-10-02 14:06:56 +00:00
|
|
|
selenium = cls(build_dir=request.config.option.build_dir,
|
|
|
|
server_port=server_port,
|
2018-09-18 17:04:53 +00:00
|
|
|
server_hostname=server_hostname,
|
|
|
|
server_log=server_log)
|
2018-08-20 17:02:12 +00:00
|
|
|
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
|
2018-08-20 17:02:12 +00:00
|
|
|
try:
|
2018-08-22 12:37:23 +00:00
|
|
|
_selenium_cached.clean_logs()
|
2018-08-20 17:02:12 +00:00
|
|
|
yield _selenium_cached
|
|
|
|
finally:
|
2018-08-22 12:37:23 +00:00
|
|
|
print(_selenium_cached.logs)
|
2018-08-20 17:02:12 +00:00
|
|
|
|
2018-07-09 19:09:49 +00:00
|
|
|
|
2018-09-18 17:04:53 +00:00
|
|
|
@pytest.fixture(scope='session')
|
2018-10-02 08:39:25 +00:00
|
|
|
def web_server_main(request):
|
|
|
|
with spawn_web_server(request.config.option.build_dir) as output:
|
2018-09-18 17:04:53 +00:00
|
|
|
yield output
|
2018-07-09 21:15:04 +00:00
|
|
|
|
|
|
|
|
2018-09-18 17:04:53 +00:00
|
|
|
@pytest.fixture(scope='session')
|
2018-10-02 08:39:25 +00:00
|
|
|
def web_server_secondary(request):
|
|
|
|
with spawn_web_server(request.config.option.build_dir) as output:
|
2018-09-18 17:04:53 +00:00
|
|
|
yield output
|
|
|
|
|
2018-07-09 21:15:04 +00:00
|
|
|
|
2018-09-18 17:04:53 +00:00
|
|
|
@contextlib.contextmanager
|
2018-10-03 12:38:27 +00:00
|
|
|
def spawn_web_server(build_dir=None):
|
|
|
|
|
|
|
|
if build_dir is None:
|
|
|
|
build_dir = BUILD_PATH
|
2018-07-09 19:09:49 +00:00
|
|
|
|
2018-09-18 17:04:53 +00:00
|
|
|
tmp_dir = tempfile.mkdtemp()
|
|
|
|
log_path = pathlib.Path(tmp_dir) / 'http-server.log'
|
2018-07-09 21:15:04 +00:00
|
|
|
q = multiprocessing.Queue()
|
2018-10-02 08:39:25 +00:00
|
|
|
p = multiprocessing.Process(target=run_web_server,
|
|
|
|
args=(q, log_path, build_dir))
|
2018-07-09 19:09:49 +00:00
|
|
|
|
2018-09-18 17:04:53 +00:00
|
|
|
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:
|
2018-07-09 21:15:04 +00:00
|
|
|
q.put("TERMINATE")
|
|
|
|
p.join()
|
2018-09-18 17:04:53 +00:00
|
|
|
shutil.rmtree(tmp_dir)
|
2018-07-09 19:09:49 +00:00
|
|
|
|
|
|
|
|
2018-10-02 08:39:25 +00:00
|
|
|
def run_web_server(q, log_filepath, build_dir):
|
2018-09-18 17:04:53 +00:00
|
|
|
"""Start the HTTP web server
|
2018-07-09 19:09:49 +00:00
|
|
|
|
2018-09-18 17:04:53 +00:00
|
|
|
Parameters
|
|
|
|
----------
|
|
|
|
q : Queue
|
|
|
|
communication queue
|
|
|
|
log_path : pathlib.Path
|
|
|
|
path to the file where to store the logs
|
|
|
|
"""
|
2018-07-09 19:09:49 +00:00
|
|
|
import http.server
|
|
|
|
import socketserver
|
|
|
|
|
2018-10-02 08:39:25 +00:00
|
|
|
os.chdir(build_dir)
|
2018-07-09 19:09:49 +00:00
|
|
|
|
2018-09-18 17:04:53 +00:00
|
|
|
log_fh = log_filepath.open('w', buffering=1)
|
|
|
|
sys.stdout = log_fh
|
|
|
|
sys.stderr = log_fh
|
|
|
|
|
2018-09-12 14:14:51 +00:00
|
|
|
class Handler(http.server.CGIHTTPRequestHandler):
|
2018-09-18 17:04:53 +00:00
|
|
|
|
2018-09-12 14:14:51 +00:00
|
|
|
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
|
|
|
|
|
2018-09-18 17:04:53 +00:00
|
|
|
def log_message(self, format_, *args):
|
|
|
|
print("[%s] source: %s:%s - %s"
|
|
|
|
% (self.log_date_time_string(),
|
|
|
|
*self.client_address,
|
|
|
|
format_ % args))
|
2018-09-12 14:14:51 +00:00
|
|
|
|
2018-09-19 16:12:05 +00:00
|
|
|
def end_headers(self):
|
|
|
|
# Enable Cross-Origin Resource Sharing (CORS)
|
|
|
|
self.send_header('Access-Control-Allow-Origin', '*')
|
|
|
|
super().end_headers()
|
|
|
|
|
2018-09-12 14:14:51 +00:00
|
|
|
Handler.extensions_map['.wasm'] = 'application/wasm'
|
2018-07-09 19:09:49 +00:00
|
|
|
|
2018-07-09 21:15:04 +00:00
|
|
|
with socketserver.TCPServer(("", 0), Handler) as httpd:
|
|
|
|
host, port = httpd.server_address
|
2018-09-18 17:04:53 +00:00
|
|
|
print(f"Starting webserver at http://{host}:{port}")
|
2018-09-12 14:14:51 +00:00
|
|
|
httpd.server_name = 'test-server'
|
|
|
|
httpd.server_port = port
|
2018-07-09 21:15:04 +00:00
|
|
|
q.put(port)
|
|
|
|
|
|
|
|
def service_actions():
|
|
|
|
try:
|
|
|
|
if q.get(False) == "TERMINATE":
|
2018-09-18 17:04:53 +00:00
|
|
|
print('Stopping server...')
|
2018-07-09 21:15:04 +00:00
|
|
|
sys.exit(0)
|
|
|
|
except queue.Empty:
|
|
|
|
pass
|
|
|
|
|
|
|
|
httpd.service_actions = service_actions
|
2018-07-09 19:09:49 +00:00
|
|
|
httpd.serve_forever()
|
|
|
|
|
|
|
|
|
2018-09-18 17:04:53 +00:00
|
|
|
if (__name__ == '__main__'
|
|
|
|
and multiprocessing.current_process().name == 'MainProcess'
|
|
|
|
and not hasattr(sys, "_pytest_session")):
|
2018-10-03 12:38:27 +00:00
|
|
|
with spawn_web_server():
|
2018-09-18 17:04:53 +00:00
|
|
|
# run forever
|
|
|
|
while True:
|
|
|
|
time.sleep(1)
|