conftest.py
This file
Path
tests/conftest.py
225 lines · 6.0 KiB · Python
Last changed by
Add server.url property in tests (#300)Bakhtiyor Ruzievbefore adoptione34d280
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 Server14Add server.url property in tests (#300)Bakhtiyor Ruzievbefore adoptione34d280
line 15why, one step back15from httpx import URL, 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
line 134why, one step back134class TestServer(Server):Add server.url property in tests (#300)Bakhtiyor Ruzievbefore adoptione34d280
lines 135–139why, one step back135 @property136 def url(self) -> URL:137 protocol = "https" if self.config.is_ssl else "http"138 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")139Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 140–180why, one step back140 def install_signal_handlers(self) -> None:141 # Disable the default installation of handlers for signals such as SIGTERM,142 # because it can only be done in the main thread.143 pass144145 async def serve(self, sockets=None):146 self.restart_requested = asyncio.Event()147148 loop = asyncio.get_event_loop()149 tasks = {150 loop.create_task(super().serve(sockets=sockets)),151 loop.create_task(self.watch_restarts()),152 }153 await asyncio.wait(tasks)154155 async def restart(self) -> None:156 # Ensure we are in an asyncio environment.157 assert asyncio.get_event_loop() is not None158 # This may be called from a different thread than the one the server is159 # running on. For this reason, we use an event to coordinate with the server160 # instead of calling shutdown()/startup() directly.161 self.restart_requested.set()162 self.started = False163 while not self.started:164 await asyncio.sleep(0.5)165166 async def watch_restarts(self):167 while True:168 if self.should_exit:169 return170171 try:172 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)173 except asyncio.TimeoutError:174 continue175176 self.restart_requested.clear()177 await self.shutdown()178 await self.startup()179180Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
line 181why, one step back181@pytest.fixtureServe test server in thread (#292)Florimond Mancabefore adoption994403b
lines 182–197why, one step back182def restart(backend):183 """Restart the running server from an async test function.184185 This fixture deals with possible differences between the environment of the186 test function and that of the server.187 """188189 async def restart(server):190 await backend.run_in_threadpool(AsyncioBackend().run, server.restart)191192 return restart193194195def serve_in_thread(server: Server):196 thread = threading.Thread(target=server.run)197 thread.start()Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
lines 198–199why, one step back198 try:199 while not server.started:Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 200why, one step back200 time.sleep(1e-3)Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
lines 201–203why, one step back201 yield server202 finally:203 server.should_exit = TrueServe test server in thread (#292)Florimond Mancabefore adoption994403b
line 204why, one step back204 thread.join()Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
lines 205–206why, one step back205206Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 207–215why, one step back207@pytest.fixture(scope=SERVER_SCOPE)208def server():209 config = Config(app=app, lifespan="off", loop="asyncio")210 server = TestServer(config=config)211 yield from serve_in_thread(server)212213214@pytest.fixture(scope=SERVER_SCOPE)215def https_server(cert_pem_file, cert_private_key_file):Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8
line 216why, one step back216 config = Config(Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 217–221why, one step back217 app=app,218 lifespan="off",219 ssl_certfile=cert_pem_file,220 ssl_keyfile=cert_private_key_file,221 port=8001,Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 222why, one step back222 loop="asyncio",Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8
line 223why, one step back223 )Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 224–225why, one step back224 server = TestServer(config=config)225 yield from serve_in_thread(server)