Debian Codegraph @

tests/conftest.py

raw
1 import httpx
2 import os
3 import pathlib
4 import pytest
5 import re
6 import subprocess
7 import tempfile
8 import time
9 import trustme
10
11
12 try:
13 import pysqlite3 as sqlite3
14 except ImportError:
15 import sqlite3
16
17 UNDOCUMENTED_PERMISSIONS = {
18 "this_is_allowed",
19 "this_is_denied",
20 "this_is_allowed_async",
21 "this_is_denied_async",
22 "no_match",
23 }
24
25
26 def wait_until_responds(url, timeout=5.0, client=httpx, **kwargs):
27 start = time.time()
28 while time.time() - start < timeout:
29 try:
30 client.get(url, **kwargs)
31 return
32 except httpx.ConnectError:
33 time.sleep(0.1)
34 raise AssertionError("Timed out waiting for {} to respond".format(url))
35
36
37 def pytest_report_header(config):
38 return "SQLite: {}".format(
39 sqlite3.connect(":memory:").execute("select sqlite_version()").fetchone()[0]
40 )
41
42
43 def pytest_configure(config):
44 import sys
45
46 sys._called_from_test = True
47
48
49 def pytest_unconfigure(config):
50 import sys
51
52 del sys._called_from_test
53
54
55 def pytest_collection_modifyitems(items):
56 # Ensure test_cli.py and test_black.py and test_inspect.py run first before any asyncio code kicks in
57 move_to_front(items, "test_cli")
58 move_to_front(items, "test_black")
59 move_to_front(items, "test_inspect_cli")
60 move_to_front(items, "test_serve_with_get")
61 move_to_front(items, "test_serve_with_get_exit_code_for_error")
62 move_to_front(items, "test_inspect_cli_writes_to_file")
63 move_to_front(items, "test_spatialite_error_if_attempt_to_open_spatialite")
64 move_to_front(items, "test_package")
65 move_to_front(items, "test_package_with_port")
66
67
68 def move_to_front(items, test_name):
69 test = [fn for fn in items if fn.name == test_name]
70 if test:
71 items.insert(0, items.pop(items.index(test[0])))
72
73
74 @pytest.fixture
75 def restore_working_directory(tmpdir, request):
76 try:
77 previous_cwd = os.getcwd()
78 except OSError:
79 # https://github.com/simonw/datasette/issues/1361
80 previous_cwd = None
81 tmpdir.chdir()
82
83 def return_to_previous():
84 os.chdir(previous_cwd)
85
86 if previous_cwd is not None:
87 request.addfinalizer(return_to_previous)
88
89
90 @pytest.fixture(scope="session", autouse=True)
91 def check_permission_actions_are_documented():
92 from datasette.plugins import pm
93
94 content = (
95 pathlib.Path(__file__).parent.parent / "docs" / "authentication.rst"
96 ).read_text()
97 permissions_re = re.compile(r"\.\. _permissions_([^\s:]+):")
98 documented_permission_actions = set(permissions_re.findall(content)).union(
99 UNDOCUMENTED_PERMISSIONS
100 )
101
102 def before(hook_name, hook_impls, kwargs):
103 if hook_name == "permission_allowed":
104 action = kwargs.get("action").replace("-", "_")
105 assert (
106 action in documented_permission_actions
107 ), "Undocumented permission action: {}, resource: {}".format(
108 action, kwargs["resource"]
109 )
110
111 pm.add_hookcall_monitoring(
112 before=before, after=lambda outcome, hook_name, hook_impls, kwargs: None
113 )
114
115
116 @pytest.fixture(scope="session")
117 def ds_localhost_http_server():
118 ds_proc = subprocess.Popen(
119 ["datasette", "--memory", "-p", "8041"],
120 stdout=subprocess.PIPE,
121 stderr=subprocess.STDOUT,
122 # Avoid FileNotFoundError: [Errno 2] No such file or directory:
123 cwd=tempfile.gettempdir(),
124 )
125 wait_until_responds("http://localhost:8041/")
126 # Check it started successfully
127 assert not ds_proc.poll(), ds_proc.stdout.read().decode("utf-8")
128 yield ds_proc
129 # Shut it down at the end of the pytest session
130 ds_proc.terminate()
131
132
133 @pytest.fixture(scope="session")
134 def ds_unix_domain_socket_server(tmp_path_factory):
135 # This used to use tmp_path_factory.mktemp("uds") but that turned out to
136 # produce paths that were too long to use as UDS on macOS, see
137 # https://github.com/simonw/datasette/issues/1407 - so I switched to
138 # using tempfile.gettempdir()
139 uds = str(pathlib.Path(tempfile.gettempdir()) / "datasette.sock")
140 ds_proc = subprocess.Popen(
141 ["datasette", "--memory", "--uds", uds],
142 stdout=subprocess.PIPE,
143 stderr=subprocess.STDOUT,
144 cwd=tempfile.gettempdir(),
145 )
146 # Poll until available
147 transport = httpx.HTTPTransport(uds=uds)
148 client = httpx.Client(transport=transport)
149 wait_until_responds("http://localhost/_memory.json", client=client)
150 # Check it started successfully
151 assert not ds_proc.poll(), ds_proc.stdout.read().decode("utf-8")
152 yield ds_proc, uds
153 # Shut it down at the end of the pytest session
154 ds_proc.terminate()