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 fileTake it
The walk stopped after 200 commits: lines older than f1b10e5 point at it.
Minor docstring tweakTom Christiebefore adoptionf1b10e5
line 1why, one step back1import asyncioAdd `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac
line 2why, one step back2import jsonAdd os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
line 3why, one step back3import osServe test server in thread (#292)Florimond Mancabefore adoption994403b
lines 4–5why, one step back4import threading5import timeAdd os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
line 6why, one step back6import typingMinor docstring tweakTom Christiebefore adoptionf1b10e5
lines 7–8why, one step back78import pytestMerge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
line 9why, one step back9import trustmeSupport client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 10–14why, one step back10from cryptography.hazmat.primitives.serialization import (11 BestAvailableEncryption,12 Encoding,13 PrivateFormat,14)Minor docstring tweakTom Christiebefore adoptionf1b10e5
lines 15–17why, one step back15from uvicorn.config import Config16from uvicorn.main import Server17Add server.url property in tests (#300)Bakhtiyor Ruzievbefore adoptione34d280
line 18why, one step back18from httpx import URL, AsyncioBackendAdd os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
line 19why, one step back19Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
line 20why, one step back20ENVIRONMENT_VARIABLES = {Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
line 21why, one step back21 "SSL_CERT_FILE",Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
line 22why, one step back22 "SSL_CERT_DIR",Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
lines 23–27why, one step back23 "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 back28}Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
lines 29–34why, one step back293031@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 back35 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 back43 yield44 os.environ.clear()45 os.environ.update(original_environ)Minor docstring tweakTom Christiebefore adoptionf1b10e5
line 46why, one step back46Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
lines 47–53why, one step back4748@pytest.fixture(params=[pytest.param(AsyncioBackend, marks=pytest.mark.asyncio)])49def backend(request):50 backend_cls = request.param51 return backend_cls()5253Minor docstring tweakTom Christiebefore adoptionf1b10e5
lines 54–55why, one step back54async 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 back56 if scope["path"].startswith("/slow_response"):Minor docstring tweakTom Christiebefore adoptionf1b10e5
lines 57–59why, one step back57 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 back60 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 back62 elif scope["path"].startswith("/echo_headers"):63 await echo_headers(scope, receive, send)Minor docstring tweakTom Christiebefore adoptionf1b10e5
lines 64–79why, one step back64 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 back80 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 back86 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 back106107108async def echo_body(scope, receive, send):Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 109why, one step back109 body = b""Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0
lines 110–113why, one step back110 more_body = True111112 while more_body:113 message = await receive()Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
lines 114–115why, one step back114 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 back116117 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 back125126127async 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 back140141Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 142–157why, one step back142class 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 )156157Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 158–161why, one step back158SERVER_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 back162def example_cert():163 ca = CAWithPKEncryption()Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8
line 164why, one step back164 ca.issue_cert("example.org")Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
line 165why, one step back165 return caMerge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8
lines 166–167why, one step back166167Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 168why, one step back168@pytest.fixture(scope=SERVER_SCOPE)Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 169–173why, one step back169def cert_pem_file(example_cert):170 with example_cert.cert_pem.tempfile() as tmp:171 yield tmp172173Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 174why, one step back174@pytest.fixture(scope=SERVER_SCOPE)Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 175–179why, one step back175def cert_private_key_file(example_cert):176 with example_cert.private_key_pem.tempfile() as tmp:177 yield tmp178179Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 180why, one step back180@pytest.fixture(scope=SERVER_SCOPE)Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 181–185why, one step back181def cert_encrypted_private_key_file(example_cert):182 with example_cert.encrypted_private_key_pem.tempfile() as tmp:183 yield tmp184185Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 186why, one step back186class TestServer(Server):Add server.url property in tests (#300)Bakhtiyor Ruzievbefore adoptione34d280
lines 187–191why, one step back187 @property188 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}/")191Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 192–232why, one step back192 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()231232Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
line 233why, one step back233@pytest.fixtureServe test server in thread (#292)Florimond Mancabefore adoption994403b
lines 234–249why, one step back234def 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 back250 try:251 while not server.started:Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 252why, one step back252 time.sleep(1e-3)Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
lines 253–255why, one step back253 yield server254 finally:255 server.should_exit = TrueServe test server in thread (#292)Florimond Mancabefore adoption994403b
line 256why, one step back256 thread.join()Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
lines 257–258why, one step back257258Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 259–267why, one step back259@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 back268 config = Config(Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 269–273why, one step back269 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 back274 loop="asyncio",Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8
line 275why, one step back275 )Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 276–277why, one step back276 server = TestServer(config=config)277 yield from serve_in_thread(server)