conftest.py
This file
Path
tests/conftest.py
221 lines · 5.9 KiB · Python
Last changed by
Serve test server in thread (#292)Florimond Mancabefore adoption994403b
History of this fileTake it
The walk stopped after 200 commits: lines older than 5f8000f point at it.
Updating docstringsTom Christiebefore adoption5f8000f
line 1why, one step back1import asyncioServe test server in thread (#292)Florimond Mancabefore adoption994403b
lines 2–3why, one step back2import threading3import timeUpdating docstringsTom Christiebefore adoption5f8000f
lines 4–5why, one step back45import pytestMerge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
line 6why, one step back6import trustmeSupport client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 7–11why, one step back7from cryptography.hazmat.primitives.serialization import (8 BestAvailableEncryption,9 Encoding,10 PrivateFormat,11)Updating docstringsTom Christiebefore adoption5f8000f
lines 12–14why, one step back12from uvicorn.config import Config13from uvicorn.main import Server14Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 15why, one step back15from httpx import AsyncioBackendUpdating docstringsTom Christiebefore adoption5f8000f
line 16why, one step back16Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
lines 17–23why, one step back1718@pytest.fixture(params=[pytest.param(AsyncioBackend, marks=pytest.mark.asyncio)])19def backend(request):20 backend_cls = request.param21 return backend_cls()2223Updating docstringsTom Christiebefore adoption5f8000f
lines 24–27why, one step back24async def app(scope, receive, send):25 assert scope["type"] == "http"26 if scope["path"] == "/slow_response":27 await slow_response(scope, receive, send)Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
lines 28–29why, one step back28 elif scope["path"].startswith("/status"):29 await status_code(scope, receive, send)Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0
lines 30–31why, one step back30 elif scope["path"].startswith("/echo_body"):31 await echo_body(scope, receive, send)Updating docstringsTom Christiebefore adoption5f8000f
lines 32–47why, one step back32 else:33 await hello_world(scope, receive, send)343536async def hello_world(scope, receive, send):37 await send(38 {39 "type": "http.response.start",40 "status": 200,41 "headers": [[b"content-type", b"text/plain"]],42 }43 )44 await send({"type": "http.response.body", "body": b"Hello, world!"})454647async def slow_response(scope, receive, send):Version 0.6.4 (#105)Tom Christiebefore adoption5326cd1
line 48why, one step back48 await asyncio.sleep(0.1)Updating docstringsTom Christiebefore adoption5f8000f
lines 49–52why, one step back49 await send(50 {51 "type": "http.response.start",52 "status": 200,Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
lines 53–64why, one step back53 "headers": [[b"content-type", b"text/plain"]],54 }55 )56 await send({"type": "http.response.body", "body": b"Hello, world!"})575859async def status_code(scope, receive, send):60 status_code = int(scope["path"].replace("/status/", ""))61 await send(62 {63 "type": "http.response.start",64 "status": status_code,Updating docstringsTom Christiebefore adoption5f8000f
lines 65–68why, one step back65 "headers": [[b"content-type", b"text/plain"]],66 }67 )68 await send({"type": "http.response.body", "body": b"Hello, world!"})Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0
lines 69–71why, one step back697071async def echo_body(scope, receive, send):Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 72why, one step back72 body = b""Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0
lines 73–76why, one step back73 more_body = True7475 while more_body:76 message = await receive()Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
lines 77–78why, one step back77 body += message.get("body", b"")78 more_body = message.get("more_body", False)Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0
lines 79–87why, one step back7980 await send(81 {82 "type": "http.response.start",83 "status": 200,84 "headers": [[b"content-type", b"text/plain"]],85 }86 )87 await send({"type": "http.response.body", "body": body})Updating docstringsTom Christiebefore adoption5f8000f
lines 88–89why, one step back8889Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 90–105why, one step back90class CAWithPKEncryption(trustme.CA):91 """Implementation of trustme.CA() that can emit92 private keys that are encrypted with a password.93 """9495 @property96 def encrypted_private_key_pem(self):97 return trustme.Blob(98 self._private_key.private_bytes(99 Encoding.PEM,100 PrivateFormat.TraditionalOpenSSL,101 BestAvailableEncryption(password=b"password"),102 )103 )104105Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 106–109why, one step back106SERVER_SCOPE = "session"107108109@pytest.fixture(scope=SERVER_SCOPE)Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 110–111why, one step back110def example_cert():111 ca = CAWithPKEncryption()Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8
line 112why, one step back112 ca.issue_cert("example.org")Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
line 113why, one step back113 return caMerge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8
lines 114–115why, one step back114115Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 116why, one step back116@pytest.fixture(scope=SERVER_SCOPE)Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 117–121why, one step back117def cert_pem_file(example_cert):118 with example_cert.cert_pem.tempfile() as tmp:119 yield tmp120121Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 122why, one step back122@pytest.fixture(scope=SERVER_SCOPE)Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 123–127why, one step back123def cert_private_key_file(example_cert):124 with example_cert.private_key_pem.tempfile() as tmp:125 yield tmp126127Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 128why, one step back128@pytest.fixture(scope=SERVER_SCOPE)Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 129–133why, one step back129def cert_encrypted_private_key_file(example_cert):130 with example_cert.encrypted_private_key_pem.tempfile() as tmp:131 yield tmp132133Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 134–176why, one step back134class TestServer(Server):135 def install_signal_handlers(self) -> None:136 # Disable the default installation of handlers for signals such as SIGTERM,137 # because it can only be done in the main thread.138 pass139140 async def serve(self, sockets=None):141 self.restart_requested = asyncio.Event()142143 loop = asyncio.get_event_loop()144 tasks = {145 loop.create_task(super().serve(sockets=sockets)),146 loop.create_task(self.watch_restarts()),147 }148149 await asyncio.wait(tasks)150151 async def restart(self) -> None:152 # Ensure we are in an asyncio environment.153 assert asyncio.get_event_loop() is not None154 # This may be called from a different thread than the one the server is155 # running on. For this reason, we use an event to coordinate with the server156 # instead of calling shutdown()/startup() directly.157 self.restart_requested.set()158 self.started = False159 while not self.started:160 await asyncio.sleep(0.5)161162 async def watch_restarts(self):163 while True:164 if self.should_exit:165 return166167 try:168 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)169 except asyncio.TimeoutError:170 continue171172 self.restart_requested.clear()173 await self.shutdown()174 await self.startup()175176Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
line 177why, one step back177@pytest.fixtureServe test server in thread (#292)Florimond Mancabefore adoption994403b
lines 178–193why, one step back178def restart(backend):179 """Restart the running server from an async test function.180181 This fixture deals with possible differences between the environment of the182 test function and that of the server.183 """184185 async def restart(server):186 await backend.run_in_threadpool(AsyncioBackend().run, server.restart)187188 return restart189190191def serve_in_thread(server: Server):192 thread = threading.Thread(target=server.run)193 thread.start()Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
lines 194–195why, one step back194 try:195 while not server.started:Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 196why, one step back196 time.sleep(1e-3)Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
lines 197–199why, one step back197 yield server198 finally:199 server.should_exit = TrueServe test server in thread (#292)Florimond Mancabefore adoption994403b
line 200why, one step back200 thread.join()Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
lines 201–202why, one step back201202Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 203–211why, one step back203@pytest.fixture(scope=SERVER_SCOPE)204def server():205 config = Config(app=app, lifespan="off", loop="asyncio")206 server = TestServer(config=config)207 yield from serve_in_thread(server)208209210@pytest.fixture(scope=SERVER_SCOPE)211def https_server(cert_pem_file, cert_private_key_file):Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8
line 212why, one step back212 config = Config(Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 213–217why, one step back213 app=app,214 lifespan="off",215 ssl_certfile=cert_pem_file,216 ssl_keyfile=cert_private_key_file,217 port=8001,Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 218why, one step back218 loop="asyncio",Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8
line 219why, one step back219 )Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 220–221why, one step back220 server = TestServer(config=config)221 yield from serve_in_thread(server)