forked from jupyter-server/jupyter_server
/
test_launch.py
113 lines (85 loc) · 2.54 KB
/
test_launch.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
"""Test launching Jupyter Server Applications
through as ExtensionApp launch_instance.
"""
import os
import subprocess
import sys
import time
from binascii import hexlify
from pathlib import Path
import pytest
import requests
HERE = os.path.dirname(os.path.abspath(__file__))
@pytest.fixture
def port():
return 9999
@pytest.fixture
def token():
return hexlify(os.urandom(4)).decode("ascii")
@pytest.fixture
def auth_header(token):
return {"Authorization": "token %s" % token}
def wait_up(url, interval=0.1, check=None):
while True:
try:
r = requests.get(url)
except Exception:
if check:
assert check()
# print("waiting for %s" % url)
time.sleep(interval)
else:
break
@pytest.fixture
def launch_instance(request, port, token):
def _run_in_subprocess(argv=[], add_token=True):
def _kill_extension_app():
try:
process.terminate()
except OSError:
# Already dead.
pass
process.wait(10)
if add_token:
f'--ServerApp.token="{token}"',
root = Path(HERE).parent.parent
process = subprocess.Popen(
[
sys.executable,
"-m",
"tests.extension.mockextensions.app",
f"--port={port}",
"--ip=127.0.0.1",
"--no-browser",
*argv,
],
cwd=str(root),
)
request.addfinalizer(_kill_extension_app)
url = f"http://127.0.0.1:{port}"
wait_up(url, check=lambda: process.poll() is None)
return process
return _run_in_subprocess
@pytest.fixture
def fetch(port, auth_header):
def _get(endpoint):
url = f"http://127.0.0.1:{port}" + endpoint
return requests.get(url, headers=auth_header)
return _get
def test_launch_instance(launch_instance, fetch):
launch_instance()
r = fetch("/mock")
assert r.status_code == 200
def test_base_url(launch_instance, fetch):
launch_instance(["--ServerApp.base_url=/foo"])
r = fetch("/foo/mock")
assert r.status_code == 200
def test_token_file(launch_instance, fetch, token):
token_file = HERE / Path("token_file.txt")
os.environ["JUPYTER_TOKEN_FILE"] = str(token_file)
token_file.write_text(token, encoding="utf-8")
launch_instance(add_token=False)
r = fetch("/mock")
del os.environ["JUPYTER_TOKEN_FILE"]
token_file.unlink()
assert r.status_code == 200