Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

284 lines · 7.8 KiB · Python

Last changed by

Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360

History of this file

Take it

The walk stopped after 200 commits: lines older than f1b10e5 point at it.

Minor docstring tweakTom Christiebefore adoptionf1b10e5

line 1why, one step back
1import asyncio

Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac

line 2why, one step back
2import json

Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a

line 3why, one step back
3import os

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

lines 4–5why, one step back
4import threading
5import time

Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a

line 6why, one step back
6import typing

Minor docstring tweakTom Christiebefore adoptionf1b10e5

lines 7–8why, one step back
7
8import pytest

Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635

line 9why, one step back
9import trustme

Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360

line 10why, one step back
10from cryptography.hazmat.backends import default_backend

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

line 11why, one step back
11from cryptography.hazmat.primitives.serialization import (

Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360

line 12why, one step back
12 load_pem_private_key,

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

lines 13–16why, one step back
13 BestAvailableEncryption,
14 Encoding,15 PrivateFormat,16)

Minor docstring tweakTom Christiebefore adoptionf1b10e5

lines 17–19why, one step back
17from uvicorn.config import Config
18from uvicorn.main import Server19

Add server.url property in tests (#300)Bakhtiyor Ruzievbefore adoptione34d280

line 20why, one step back
20from httpx import URL, AsyncioBackend

Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a

line 21why, one step back
21

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

line 22why, one step back
22ENVIRONMENT_VARIABLES = {

Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a

line 23why, one step back
23 "SSL_CERT_FILE",

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

line 24why, one step back
24 "SSL_CERT_DIR",

Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a

lines 25–29why, one step back
25 "HTTP_PROXY",
26 "HTTPS_PROXY",27 "ALL_PROXY",28 "NO_PROXY",29 "SSLKEYLOGFILE",

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

line 30why, one step back
30}

Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a

lines 31–36why, one step back
31
3233@pytest.fixture(scope="function", autouse=True)34def clean_environ() -> typing.Dict[str, typing.Any]:35 """Keeps os.environ clean for every test without having to mock os.environ"""36 original_environ = os.environ.copy()

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 37–44why, one step back
37 os.environ.clear()
38 os.environ.update(39 {40 k: v41 for k, v in original_environ.items()42 if k not in ENVIRONMENT_VARIABLES and k.lower() not in ENVIRONMENT_VARIABLES43 }44 )

Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a

lines 45–47why, one step back
45 yield
46 os.environ.clear()47 os.environ.update(original_environ)

Minor docstring tweakTom Christiebefore adoptionf1b10e5

line 48why, one step back
48

Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058

lines 49–55why, one step back
49
50@pytest.fixture(params=[pytest.param(AsyncioBackend, marks=pytest.mark.asyncio)])51def backend(request):52 backend_cls = request.param53 return backend_cls()5455

Minor docstring tweakTom Christiebefore adoptionf1b10e5

lines 56–57why, one step back
56async def app(scope, receive, send):
57 assert scope["type"] == "http"

Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117

line 58why, one step back
58 if scope["path"].startswith("/slow_response"):

Minor docstring tweakTom Christiebefore adoptionf1b10e5

lines 59–61why, one step back
59 await slow_response(scope, receive, send)
60 elif scope["path"].startswith("/status"):61 await status_code(scope, receive, send)

Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0

lines 62–63why, one step back
62 elif scope["path"].startswith("/echo_body"):
63 await echo_body(scope, receive, send)

Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac

lines 64–65why, one step back
64 elif scope["path"].startswith("/echo_headers"):
65 await echo_headers(scope, receive, send)

Minor docstring tweakTom Christiebefore adoptionf1b10e5

lines 66–81why, one step back
66 else:
67 await hello_world(scope, receive, send)686970async def hello_world(scope, receive, send):71 await send(72 {73 "type": "http.response.start",74 "status": 200,75 "headers": [[b"content-type", b"text/plain"]],76 }77 )78 await send({"type": "http.response.body", "body": b"Hello, world!"})798081async def slow_response(scope, receive, send):

Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117

lines 82–87why, one step back
82 delay_ms_str: str = scope["path"].replace("/slow_response/", "")
83 try:84 delay_ms = float(delay_ms_str)85 except ValueError:86 delay_ms = 10087 await asyncio.sleep(delay_ms / 1000.0)

Minor docstring tweakTom Christiebefore adoptionf1b10e5

lines 88–107why, one step back
88 await send(
89 {90 "type": "http.response.start",91 "status": 200,92 "headers": [[b"content-type", b"text/plain"]],93 }94 )95 await send({"type": "http.response.body", "body": b"Hello, world!"})969798async def status_code(scope, receive, send):99 status_code = int(scope["path"].replace("/status/", ""))100 await send(101 {102 "type": "http.response.start",103 "status": status_code,104 "headers": [[b"content-type", b"text/plain"]],105 }106 )107 await send({"type": "http.response.body", "body": b"Hello, world!"})

Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0

lines 108–110why, one step back
108
109110async def echo_body(scope, receive, send):

Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885

line 111why, one step back
111 body = b""

Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0

lines 112–115why, one step back
112 more_body = True
113114 while more_body:115 message = await receive()

Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885

lines 116–117why, one step back
116 body += message.get("body", b"")
117 more_body = message.get("more_body", False)

Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0

lines 118–126why, one step back
118
119 await send(120 {121 "type": "http.response.start",122 "status": 200,123 "headers": [[b"content-type", b"text/plain"]],124 }125 )126 await send({"type": "http.response.body", "body": body})

Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac

lines 127–141why, one step back
127
128129async def echo_headers(scope, receive, send):130 body = {}131 for name, value in scope.get("headers", []):132 body[name.capitalize().decode()] = value.decode()133134 await send(135 {136 "type": "http.response.start",137 "status": 200,138 "headers": [[b"content-type", b"application/json"]],139 }140 )141 await send({"type": "http.response.body", "body": json.dumps(body).encode()})

Minor docstring tweakTom Christiebefore adoptionf1b10e5

lines 142–143why, one step back
142
143

Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360

line 144why, one step back
144SERVER_SCOPE = "session"

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

lines 145–146why, one step back
145
146

Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360

lines 147–149why, one step back
147@pytest.fixture(scope=SERVER_SCOPE)
148def cert_authority():149 return trustme.CA()

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

line 150why, one step back
150

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

line 151why, one step back
151

Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360

lines 152–155why, one step back
152@pytest.fixture(scope=SERVER_SCOPE)
153def ca_cert_pem_file(cert_authority):154 with cert_authority.cert_pem.tempfile() as tmp:155 yield tmp

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

line 156why, one step back
156

Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360

line 157why, one step back
157

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

line 158why, one step back
158@pytest.fixture(scope=SERVER_SCOPE)

Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360

lines 159–160why, one step back
159def localhost_cert(cert_authority):
160 return cert_authority.issue_cert("localhost")

Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8

lines 161–162why, one step back
161
162

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

line 163why, one step back
163@pytest.fixture(scope=SERVER_SCOPE)

Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360

lines 164–165why, one step back
164def cert_pem_file(localhost_cert):
165 with localhost_cert.cert_chain_pems[0].tempfile() as tmp:

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

lines 166–168why, one step back
166 yield tmp
167168

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

line 169why, one step back
169@pytest.fixture(scope=SERVER_SCOPE)

Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360

lines 170–171why, one step back
170def cert_private_key_file(localhost_cert):
171 with localhost_cert.private_key_pem.tempfile() as tmp:

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

lines 172–174why, one step back
172 yield tmp
173174

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

line 175why, one step back
175@pytest.fixture(scope=SERVER_SCOPE)

Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360

lines 176–188why, one step back
176def cert_encrypted_private_key_file(localhost_cert):
177 # Deserialize the private key and then reserialize with a password178 private_key = load_pem_private_key(179 localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()180 )181 encrypted_private_key_pem = trustme.Blob(182 private_key.private_bytes(183 Encoding.PEM,184 PrivateFormat.TraditionalOpenSSL,185 BestAvailableEncryption(password=b"password"),186 )187 )188 with encrypted_private_key_pem.tempfile() as tmp:

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

lines 189–191why, one step back
189 yield tmp
190191

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

line 192why, one step back
192class TestServer(Server):

Add server.url property in tests (#300)Bakhtiyor Ruzievbefore adoptione34d280

lines 193–197why, one step back
193 @property
194 def url(self) -> URL:195 protocol = "https" if self.config.is_ssl else "http"196 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")197

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

lines 198–238why, one step back
198 def install_signal_handlers(self) -> None:
199 # Disable the default installation of handlers for signals such as SIGTERM,200 # because it can only be done in the main thread.201 pass202203 async def serve(self, sockets=None):204 self.restart_requested = asyncio.Event()205206 loop = asyncio.get_event_loop()207 tasks = {208 loop.create_task(super().serve(sockets=sockets)),209 loop.create_task(self.watch_restarts()),210 }211 await asyncio.wait(tasks)212213 async def restart(self) -> None:214 # Ensure we are in an asyncio environment.215 assert asyncio.get_event_loop() is not None216 # This may be called from a different thread than the one the server is217 # running on. For this reason, we use an event to coordinate with the server218 # instead of calling shutdown()/startup() directly.219 self.restart_requested.set()220 self.started = False221 while not self.started:222 await asyncio.sleep(0.5)223224 async def watch_restarts(self):225 while True:226 if self.should_exit:227 return228229 try:230 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)231 except asyncio.TimeoutError:232 continue233234 self.restart_requested.clear()235 await self.shutdown()236 await self.startup()237238

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

line 239why, one step back
239@pytest.fixture

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

lines 240–255why, one step back
240def restart(backend):
241 """Restart the running server from an async test function.242243 This fixture deals with possible differences between the environment of the244 test function and that of the server.245 """246247 async def restart(server):248 await backend.run_in_threadpool(AsyncioBackend().run, server.restart)249250 return restart251252253def serve_in_thread(server: Server):254 thread = threading.Thread(target=server.run)255 thread.start()

Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635

lines 256–257why, one step back
256 try:
257 while not server.started:

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

line 258why, one step back
258 time.sleep(1e-3)

Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635

lines 259–261why, one step back
259 yield server
260 finally:261 server.should_exit = True

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

line 262why, one step back
262 thread.join()

Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635

lines 263–264why, one step back
263
264

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

lines 265–273why, one step back
265@pytest.fixture(scope=SERVER_SCOPE)
266def server():267 config = Config(app=app, lifespan="off", loop="asyncio")268 server = TestServer(config=config)269 yield from serve_in_thread(server)270271272@pytest.fixture(scope=SERVER_SCOPE)273def https_server(cert_pem_file, cert_private_key_file):

Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8

line 274why, one step back
274 config = Config(

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

lines 275–278why, one step back
275 app=app,
276 lifespan="off",277 ssl_certfile=cert_pem_file,278 ssl_keyfile=cert_private_key_file,

Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360

line 279why, one step back
279 host="localhost",

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

line 280why, one step back
280 port=8001,

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

line 281why, one step back
281 loop="asyncio",

Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8

line 282why, one step back
282 )

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

lines 283–284why, one step back
283 server = TestServer(config=config)
284 yield from serve_in_thread(server)