|
| 1 | +"""Fixtures for pytest/playwright end_to_end tests.""" |
| 2 | + |
| 3 | + |
| 4 | +import datetime |
| 5 | +import os |
| 6 | +import json |
| 7 | +import sys |
| 8 | +import time |
| 9 | +from os.path import join as pjoin |
| 10 | +from subprocess import Popen |
| 11 | +from tempfile import mkstemp |
| 12 | +from urllib.parse import urljoin |
| 13 | + |
| 14 | +import pytest |
| 15 | +import requests |
| 16 | +from testpath.tempdir import TemporaryDirectory |
| 17 | + |
| 18 | +import nbformat |
| 19 | +from nbformat.v4 import new_notebook, new_code_cell |
| 20 | +from .utils import NotebookFrontend, BROWSER_CONTEXT, BROWSER_OBJ, TREE_PAGE, SERVER_INFO |
| 21 | + |
| 22 | + |
| 23 | +def _wait_for_server(proc, info_file_path): |
| 24 | + """Wait 30 seconds for the notebook server to start""" |
| 25 | + for i in range(300): |
| 26 | + if proc.poll() is not None: |
| 27 | + raise RuntimeError("Notebook server failed to start") |
| 28 | + if os.path.exists(info_file_path): |
| 29 | + try: |
| 30 | + with open(info_file_path) as f: |
| 31 | + return json.load(f) |
| 32 | + except ValueError: |
| 33 | + # If the server is halfway through writing the file, we may |
| 34 | + # get invalid JSON; it should be ready next iteration. |
| 35 | + pass |
| 36 | + time.sleep(0.1) |
| 37 | + raise RuntimeError("Didn't find %s in 30 seconds", info_file_path) |
| 38 | + |
| 39 | + |
| 40 | +@pytest.fixture(scope='function') |
| 41 | +def notebook_server(): |
| 42 | + info = {} |
| 43 | + with TemporaryDirectory() as td: |
| 44 | + nbdir = info['nbdir'] = pjoin(td, 'notebooks') |
| 45 | + os.makedirs(pjoin(nbdir, 'sub ∂ir1', 'sub ∂ir 1a')) |
| 46 | + os.makedirs(pjoin(nbdir, 'sub ∂ir2', 'sub ∂ir 1b')) |
| 47 | + |
| 48 | + info['extra_env'] = { |
| 49 | + 'JUPYTER_CONFIG_DIR': pjoin(td, 'jupyter_config'), |
| 50 | + 'JUPYTER_RUNTIME_DIR': pjoin(td, 'jupyter_runtime'), |
| 51 | + 'IPYTHONDIR': pjoin(td, 'ipython'), |
| 52 | + } |
| 53 | + env = os.environ.copy() |
| 54 | + env.update(info['extra_env']) |
| 55 | + |
| 56 | + command = [sys.executable, '-m', 'nbclassic', |
| 57 | + '--no-browser', |
| 58 | + '--notebook-dir', nbdir, |
| 59 | + # run with a base URL that would be escaped, |
| 60 | + # to test that we don't double-escape URLs |
| 61 | + '--ServerApp.base_url=/a@b/', |
| 62 | + ] |
| 63 | + print("command=", command) |
| 64 | + proc = info['popen'] = Popen(command, cwd=nbdir, env=env) |
| 65 | + info_file_path = pjoin(td, 'jupyter_runtime', |
| 66 | + f'jpserver-{proc.pid:d}.json') |
| 67 | + info.update(_wait_for_server(proc, info_file_path)) |
| 68 | + |
| 69 | + print("Notebook server info:", info) |
| 70 | + yield info |
| 71 | + |
| 72 | + # Shut the server down |
| 73 | + requests.post(urljoin(info['url'], 'api/shutdown'), |
| 74 | + headers={'Authorization': 'token '+info['token']}) |
| 75 | + |
| 76 | + |
| 77 | +@pytest.fixture(scope='function') |
| 78 | +def playwright_browser(playwright): |
| 79 | + start = datetime.datetime.now() |
| 80 | + while (datetime.datetime.now() - start).seconds < 30: |
| 81 | + try: |
| 82 | + if os.environ.get('JUPYTER_TEST_BROWSER') == 'chrome': |
| 83 | + browser = playwright.chromium.launch() |
| 84 | + else: |
| 85 | + browser = playwright.firefox.launch() |
| 86 | + break |
| 87 | + except Exception: |
| 88 | + time.sleep(.2) |
| 89 | + |
| 90 | + yield browser |
| 91 | + |
| 92 | + # Teardown |
| 93 | + browser.close() |
| 94 | + |
| 95 | + |
| 96 | +@pytest.fixture(scope='function') |
| 97 | +def authenticated_browser_data(playwright_browser, notebook_server): |
| 98 | + browser_obj = playwright_browser |
| 99 | + browser_context = browser_obj.new_context() |
| 100 | + browser_context.jupyter_server_info = notebook_server |
| 101 | + tree_page = browser_context.new_page() |
| 102 | + tree_page.goto("{url}?token={token}".format(**notebook_server)) |
| 103 | + |
| 104 | + auth_browser_data = { |
| 105 | + BROWSER_CONTEXT: browser_context, |
| 106 | + TREE_PAGE: tree_page, |
| 107 | + SERVER_INFO: notebook_server, |
| 108 | + BROWSER_OBJ: browser_obj, |
| 109 | + } |
| 110 | + |
| 111 | + return auth_browser_data |
| 112 | + |
| 113 | + |
| 114 | +@pytest.fixture(scope='function') |
| 115 | +def notebook_frontend(authenticated_browser_data): |
| 116 | + yield NotebookFrontend.new_notebook_frontend(authenticated_browser_data) |
| 117 | + |
| 118 | + |
| 119 | +@pytest.fixture(scope='function') |
| 120 | +def prefill_notebook(playwright_browser, notebook_server): |
| 121 | + browser_obj = playwright_browser |
| 122 | + browser_context = browser_obj.new_context() |
| 123 | + # playwright_browser is the browser_context, |
| 124 | + # notebook_server is the server with directories |
| 125 | + |
| 126 | + # the return of function inner takes in a dictionary of strings to populate cells |
| 127 | + def inner(cells): |
| 128 | + cells = [new_code_cell(c) if isinstance(c, str) else c |
| 129 | + for c in cells] |
| 130 | + # new_notebook is an nbformat function that is imported so that it can create a |
| 131 | + # notebook that is formatted as it needs to be |
| 132 | + nb = new_notebook(cells=cells) |
| 133 | + |
| 134 | + # Create temporary file directory and store it's reference as well as the path |
| 135 | + fd, path = mkstemp(dir=notebook_server['nbdir'], suffix='.ipynb') |
| 136 | + |
| 137 | + # Open the file and write the format onto the file |
| 138 | + with open(fd, 'w', encoding='utf-8') as f: |
| 139 | + nbformat.write(nb, f) |
| 140 | + |
| 141 | + # Grab the name of the file |
| 142 | + fname = os.path.basename(path) |
| 143 | + |
| 144 | + # Add the notebook server as a property of the playwright browser with the name jupyter_server_info |
| 145 | + browser_context.jupyter_server_info = notebook_server |
| 146 | + # Open a new page in the browser and refer to it as the tree page |
| 147 | + tree_page = browser_context.new_page() |
| 148 | + |
| 149 | + # Navigate that page to the base URL page AKA the tree page |
| 150 | + tree_page.goto("{url}?token={token}".format(**notebook_server)) |
| 151 | + |
| 152 | + auth_browser_data = { |
| 153 | + BROWSER_CONTEXT: browser_context, |
| 154 | + TREE_PAGE: tree_page, |
| 155 | + SERVER_INFO: notebook_server, |
| 156 | + BROWSER_OBJ: browser_obj |
| 157 | + } |
| 158 | + |
| 159 | + return NotebookFrontend.new_notebook_frontend(auth_browser_data, existing_file_name=fname) |
| 160 | + |
| 161 | + # Return the function that will take in the dict of code strings |
| 162 | + return inner |
0 commit comments