conftest.py
This file
Path
tests/conftest.py
249 lines · 6.6 KiB · Python
Last changed by
Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
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 asyncioAdd os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
line 2why, one step back2import osServe test server in thread (#292)Florimond Mancabefore adoption994403b
lines 3–4why, one step back3import threading4import timeAdd os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
line 5why, one step back5import typingUpdating docstringsTom Christiebefore adoption5f8000f
lines 6–7why, one step back67import pytestMerge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
line 8why, one step back8import trustmeSupport client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 9–13why, one step back9from cryptography.hazmat.primitives.serialization import (10 BestAvailableEncryption,11 Encoding,12 PrivateFormat,13)Updating docstringsTom Christiebefore adoption5f8000f
lines 14–16why, one step back14from uvicorn.config import Config15from uvicorn.main import Server16Add server.url property in tests (#300)Bakhtiyor Ruzievbefore adoptione34d280
line 17why, one step back17from httpx import URL, AsyncioBackendAdd os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
lines 18–39why, one step back1819ENVIRONMENT_VARIABLES = (20 "SSL_CERT_FILE",21 "REQUESTS_CA_BUNDLE",22 "CURL_CA_BUNDLE",23 "HTTP_PROXY",24 "HTTPS_PROXY",25 "ALL_PROXY",26 "NO_PROXY",27 "SSLKEYLOGFILE",28)293031@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()35 for key in ENVIRONMENT_VARIABLES:36 os.environ.pop(key, None)37 yield38 os.environ.clear()39 os.environ.update(original_environ)Updating docstringsTom Christiebefore adoption5f8000f
line 40why, one step back40Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
lines 41–47why, one step back4142@pytest.fixture(params=[pytest.param(AsyncioBackend, marks=pytest.mark.asyncio)])43def backend(request):44 backend_cls = request.param45 return backend_cls()4647Updating docstringsTom Christiebefore adoption5f8000f
lines 48–51why, one step back48async def app(scope, receive, send):49 assert scope["type"] == "http"50 if scope["path"] == "/slow_response":51 await slow_response(scope, receive, send)Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
lines 52–53why, one step back52 elif scope["path"].startswith("/status"):53 await status_code(scope, receive, send)Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0
lines 54–55why, one step back54 elif scope["path"].startswith("/echo_body"):55 await echo_body(scope, receive, send)Updating docstringsTom Christiebefore adoption5f8000f
lines 56–71why, one step back56 else:57 await hello_world(scope, receive, send)585960async def hello_world(scope, receive, send):61 await send(62 {63 "type": "http.response.start",64 "status": 200,65 "headers": [[b"content-type", b"text/plain"]],66 }67 )68 await send({"type": "http.response.body", "body": b"Hello, world!"})697071async def slow_response(scope, receive, send):Version 0.6.4 (#105)Tom Christiebefore adoption5326cd1
line 72why, one step back72 await asyncio.sleep(0.1)Updating docstringsTom Christiebefore adoption5f8000f
lines 73–76why, one step back73 await send(74 {75 "type": "http.response.start",76 "status": 200,Merge pull request #39 from matusf/29-add-raise_for_statusTom Christiebefore adoption5c1cb30
lines 77–88why, one step back77 "headers": [[b"content-type", b"text/plain"]],78 }79 )80 await send({"type": "http.response.body", "body": b"Hello, world!"})818283async def status_code(scope, receive, send):84 status_code = int(scope["path"].replace("/status/", ""))85 await send(86 {87 "type": "http.response.start",88 "status": status_code,Updating docstringsTom Christiebefore adoption5f8000f
lines 89–92why, one step back89 "headers": [[b"content-type", b"text/plain"]],90 }91 )92 await send({"type": "http.response.body", "body": b"Hello, world!"})Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0
lines 93–95why, one step back939495async def echo_body(scope, receive, send):Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 96why, one step back96 body = b""Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0
lines 97–100why, one step back97 more_body = True9899 while more_body:100 message = await receive()Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
lines 101–102why, one step back101 body += message.get("body", b"")102 more_body = message.get("more_body", False)Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0
lines 103–111why, one step back103104 await send(105 {106 "type": "http.response.start",107 "status": 200,108 "headers": [[b"content-type", b"text/plain"]],109 }110 )111 await send({"type": "http.response.body", "body": body})Updating docstringsTom Christiebefore adoption5f8000f
lines 112–113why, one step back112113Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 114–129why, one step back114class CAWithPKEncryption(trustme.CA):115 """Implementation of trustme.CA() that can emit116 private keys that are encrypted with a password.117 """118119 @property120 def encrypted_private_key_pem(self):121 return trustme.Blob(122 self._private_key.private_bytes(123 Encoding.PEM,124 PrivateFormat.TraditionalOpenSSL,125 BestAvailableEncryption(password=b"password"),126 )127 )128129Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 130–133why, one step back130SERVER_SCOPE = "session"131132133@pytest.fixture(scope=SERVER_SCOPE)Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 134–135why, one step back134def example_cert():135 ca = CAWithPKEncryption()Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8
line 136why, one step back136 ca.issue_cert("example.org")Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
line 137why, one step back137 return caMerge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8
lines 138–139why, one step back138139Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 140why, one step back140@pytest.fixture(scope=SERVER_SCOPE)Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 141–145why, one step back141def cert_pem_file(example_cert):142 with example_cert.cert_pem.tempfile() as tmp:143 yield tmp144145Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 146why, one step back146@pytest.fixture(scope=SERVER_SCOPE)Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 147–151why, one step back147def cert_private_key_file(example_cert):148 with example_cert.private_key_pem.tempfile() as tmp:149 yield tmp150151Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 152why, one step back152@pytest.fixture(scope=SERVER_SCOPE)Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 153–157why, one step back153def cert_encrypted_private_key_file(example_cert):154 with example_cert.encrypted_private_key_pem.tempfile() as tmp:155 yield tmp156157Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 158why, one step back158class TestServer(Server):Add server.url property in tests (#300)Bakhtiyor Ruzievbefore adoptione34d280
lines 159–163why, one step back159 @property160 def url(self) -> URL:161 protocol = "https" if self.config.is_ssl else "http"162 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")163Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 164–204why, one step back164 def install_signal_handlers(self) -> None:165 # Disable the default installation of handlers for signals such as SIGTERM,166 # because it can only be done in the main thread.167 pass168169 async def serve(self, sockets=None):170 self.restart_requested = asyncio.Event()171172 loop = asyncio.get_event_loop()173 tasks = {174 loop.create_task(super().serve(sockets=sockets)),175 loop.create_task(self.watch_restarts()),176 }177 await asyncio.wait(tasks)178179 async def restart(self) -> None:180 # Ensure we are in an asyncio environment.181 assert asyncio.get_event_loop() is not None182 # This may be called from a different thread than the one the server is183 # running on. For this reason, we use an event to coordinate with the server184 # instead of calling shutdown()/startup() directly.185 self.restart_requested.set()186 self.started = False187 while not self.started:188 await asyncio.sleep(0.5)189190 async def watch_restarts(self):191 while True:192 if self.should_exit:193 return194195 try:196 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)197 except asyncio.TimeoutError:198 continue199200 self.restart_requested.clear()201 await self.shutdown()202 await self.startup()203204Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
line 205why, one step back205@pytest.fixtureServe test server in thread (#292)Florimond Mancabefore adoption994403b
lines 206–221why, one step back206def restart(backend):207 """Restart the running server from an async test function.208209 This fixture deals with possible differences between the environment of the210 test function and that of the server.211 """212213 async def restart(server):214 await backend.run_in_threadpool(AsyncioBackend().run, server.restart)215216 return restart217218219def serve_in_thread(server: Server):220 thread = threading.Thread(target=server.run)221 thread.start()Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
lines 222–223why, one step back222 try:223 while not server.started:Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 224why, one step back224 time.sleep(1e-3)Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
lines 225–227why, one step back225 yield server226 finally:227 server.should_exit = TrueServe test server in thread (#292)Florimond Mancabefore adoption994403b
line 228why, one step back228 thread.join()Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
lines 229–230why, one step back229230Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 231–239why, one step back231@pytest.fixture(scope=SERVER_SCOPE)232def server():233 config = Config(app=app, lifespan="off", loop="asyncio")234 server = TestServer(config=config)235 yield from serve_in_thread(server)236237238@pytest.fixture(scope=SERVER_SCOPE)239def https_server(cert_pem_file, cert_private_key_file):Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8
line 240why, one step back240 config = Config(Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 241–245why, one step back241 app=app,242 lifespan="off",243 ssl_certfile=cert_pem_file,244 ssl_keyfile=cert_private_key_file,245 port=8001,Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 246why, one step back246 loop="asyncio",Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8
line 247why, one step back247 )Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 248–249why, one step back248 server = TestServer(config=config)249 yield from serve_in_thread(server)