Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

277 lines · 7.4 KiB · Python

Last changed by

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

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

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

lines 10–14why, one step back
10from cryptography.hazmat.primitives.serialization import (
11 BestAvailableEncryption,12 Encoding,13 PrivateFormat,14)

Minor docstring tweakTom Christiebefore adoptionf1b10e5

lines 15–17why, one step back
15from uvicorn.config import Config
16from uvicorn.main import Server17

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

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

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

line 19why, one step back
19

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

line 20why, one step back
20ENVIRONMENT_VARIABLES = {

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

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

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

line 28why, one step back
28}

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

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

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

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

Minor docstring tweakTom Christiebefore adoptionf1b10e5

line 46why, one step back
46

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

lines 47–53why, one step back
47
48@pytest.fixture(params=[pytest.param(AsyncioBackend, marks=pytest.mark.asyncio)])49def backend(request):50 backend_cls = request.param51 return backend_cls()5253

Minor docstring tweakTom Christiebefore adoptionf1b10e5

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

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

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

Minor docstring tweakTom Christiebefore adoptionf1b10e5

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

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

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

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

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

Minor docstring tweakTom Christiebefore adoptionf1b10e5

lines 64–79why, one step back
64 else:
65 await hello_world(scope, receive, send)666768async def hello_world(scope, receive, send):69 await send(70 {71 "type": "http.response.start",72 "status": 200,73 "headers": [[b"content-type", b"text/plain"]],74 }75 )76 await send({"type": "http.response.body", "body": b"Hello, world!"})777879async def slow_response(scope, receive, send):

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

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

Minor docstring tweakTom Christiebefore adoptionf1b10e5

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

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

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

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

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

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

lines 110–113why, one step back
110 more_body = True
111112 while more_body:113 message = await receive()

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

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

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

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

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

lines 125–139why, one step back
125
126127async def echo_headers(scope, receive, send):128 body = {}129 for name, value in scope.get("headers", []):130 body[name.capitalize().decode()] = value.decode()131132 await send(133 {134 "type": "http.response.start",135 "status": 200,136 "headers": [[b"content-type", b"application/json"]],137 }138 )139 await send({"type": "http.response.body", "body": json.dumps(body).encode()})

Minor docstring tweakTom Christiebefore adoptionf1b10e5

lines 140–141why, one step back
140
141

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

lines 142–157why, one step back
142class CAWithPKEncryption(trustme.CA):
143 """Implementation of trustme.CA() that can emit144 private keys that are encrypted with a password.145 """146147 @property148 def encrypted_private_key_pem(self):149 return trustme.Blob(150 self._private_key.private_bytes(151 Encoding.PEM,152 PrivateFormat.TraditionalOpenSSL,153 BestAvailableEncryption(password=b"password"),154 )155 )156157

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

lines 158–161why, one step back
158SERVER_SCOPE = "session"
159160161@pytest.fixture(scope=SERVER_SCOPE)

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

lines 162–163why, one step back
162def example_cert():
163 ca = CAWithPKEncryption()

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

line 164why, one step back
164 ca.issue_cert("example.org")

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

line 165why, one step back
165 return ca

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

lines 166–167why, one step back
166
167

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

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

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

lines 169–173why, one step back
169def cert_pem_file(example_cert):
170 with example_cert.cert_pem.tempfile() as tmp:171 yield tmp172173

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

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

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

lines 175–179why, one step back
175def cert_private_key_file(example_cert):
176 with example_cert.private_key_pem.tempfile() as tmp:177 yield tmp178179

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

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

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

lines 181–185why, one step back
181def cert_encrypted_private_key_file(example_cert):
182 with example_cert.encrypted_private_key_pem.tempfile() as tmp:183 yield tmp184185

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

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

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

lines 187–191why, one step back
187 @property
188 def url(self) -> URL:189 protocol = "https" if self.config.is_ssl else "http"190 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")191

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

lines 192–232why, one step back
192 def install_signal_handlers(self) -> None:
193 # Disable the default installation of handlers for signals such as SIGTERM,194 # because it can only be done in the main thread.195 pass196197 async def serve(self, sockets=None):198 self.restart_requested = asyncio.Event()199200 loop = asyncio.get_event_loop()201 tasks = {202 loop.create_task(super().serve(sockets=sockets)),203 loop.create_task(self.watch_restarts()),204 }205 await asyncio.wait(tasks)206207 async def restart(self) -> None:208 # Ensure we are in an asyncio environment.209 assert asyncio.get_event_loop() is not None210 # This may be called from a different thread than the one the server is211 # running on. For this reason, we use an event to coordinate with the server212 # instead of calling shutdown()/startup() directly.213 self.restart_requested.set()214 self.started = False215 while not self.started:216 await asyncio.sleep(0.5)217218 async def watch_restarts(self):219 while True:220 if self.should_exit:221 return222223 try:224 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)225 except asyncio.TimeoutError:226 continue227228 self.restart_requested.clear()229 await self.shutdown()230 await self.startup()231232

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

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

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

lines 234–249why, one step back
234def restart(backend):
235 """Restart the running server from an async test function.236237 This fixture deals with possible differences between the environment of the238 test function and that of the server.239 """240241 async def restart(server):242 await backend.run_in_threadpool(AsyncioBackend().run, server.restart)243244 return restart245246247def serve_in_thread(server: Server):248 thread = threading.Thread(target=server.run)249 thread.start()

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

lines 250–251why, one step back
250 try:
251 while not server.started:

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

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

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

lines 253–255why, one step back
253 yield server
254 finally:255 server.should_exit = True

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

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

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

lines 257–258why, one step back
257
258

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

lines 259–267why, one step back
259@pytest.fixture(scope=SERVER_SCOPE)
260def server():261 config = Config(app=app, lifespan="off", loop="asyncio")262 server = TestServer(config=config)263 yield from serve_in_thread(server)264265266@pytest.fixture(scope=SERVER_SCOPE)267def https_server(cert_pem_file, cert_private_key_file):

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

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

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

lines 269–273why, one step back
269 app=app,
270 lifespan="off",271 ssl_certfile=cert_pem_file,272 ssl_keyfile=cert_private_key_file,273 port=8001,

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

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

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

line 275why, one step back
275 )

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

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