conftest.py
This file
Path
tests/conftest.py
323 lines · 8.9 KiB · Python
Last changed by
Enable no_implicit_reexport (#2475)Martijn Pietersbefore adoption57aa5b0
History of this fileTake it
The walk stopped after 200 commits: lines older than 0ccc3fa point at it.
📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 1–17why, one step back1import asyncio2import json3import os4import threading5import time6import typing78import pytest9import trustme10from cryptography.hazmat.backends import default_backend11from cryptography.hazmat.primitives.serialization import (12 BestAvailableEncryption,13 Encoding,14 PrivateFormat,15 load_pem_private_key,16)17from uvicorn.config import ConfigEnable no_implicit_reexport (#2475)Martijn Pietersbefore adoption57aa5b0
line 18why, one step back18from uvicorn.server import Server📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 19–54why, one step back1920from httpx import URL21from tests.concurrency import sleep2223ENVIRONMENT_VARIABLES = {24 "SSL_CERT_FILE",25 "SSL_CERT_DIR",26 "HTTP_PROXY",27 "HTTPS_PROXY",28 "ALL_PROXY",29 "NO_PROXY",30 "SSLKEYLOGFILE",31}323334@pytest.fixture(35 params=[36 pytest.param("asyncio", marks=pytest.mark.asyncio),37 pytest.param("trio", marks=pytest.mark.trio),38 ]39)40def async_environment(request: typing.Any) -> str:41 """42 Mark a test function to be run on both asyncio and trio.4344 Equivalent to having a pair of tests, each respectively marked with45 '@pytest.mark.asyncio' and '@pytest.mark.trio'.4647 Intended usage:4849 ```50 @pytest.mark.usefixtures("async_environment")51 async def my_async_test():52 ...53 ```54 """Typing: enable warn_return_any (#2477)Martijn Pietersbefore adoption2d37321
line 55why, one step back55 return typing.cast(str, request.param)📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 56–82why, one step back565758@pytest.fixture(scope="function", autouse=True)59def clean_environ():60 """Keeps os.environ clean for every test without having to mock os.environ"""61 original_environ = os.environ.copy()62 os.environ.clear()63 os.environ.update(64 {65 k: v66 for k, v in original_environ.items()67 if k not in ENVIRONMENT_VARIABLES and k.lower() not in ENVIRONMENT_VARIABLES68 }69 )70 yield71 os.environ.clear()72 os.environ.update(original_environ)737475async def app(scope, receive, send):76 assert scope["type"] == "http"77 if scope["path"].startswith("/slow_response"):78 await slow_response(scope, receive, send)79 elif scope["path"].startswith("/status"):80 await status_code(scope, receive, send)81 elif scope["path"].startswith("/echo_body"):82 await echo_body(scope, receive, send)Suppress binary output on the command line (#2049) (#2076)waterfountain1996before adoption4c30748
lines 83–84why, one step back83 elif scope["path"].startswith("/echo_binary"):84 await echo_binary(scope, receive, send)📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 85–88why, one step back85 elif scope["path"].startswith("/echo_headers"):86 await echo_headers(scope, receive, send)87 elif scope["path"].startswith("/redirect_301"):88 await redirect_301(scope, receive, send)Add cli support (#1855)Tom Christiebefore adoptionee9250d
lines 89–90why, one step back89 elif scope["path"].startswith("/json"):90 await hello_world_json(scope, receive, send)📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 91–103why, one step back91 else:92 await hello_world(scope, receive, send)939495async def hello_world(scope, receive, send):96 await send(97 {98 "type": "http.response.start",99 "status": 200,100 "headers": [[b"content-type", b"text/plain"]],101 }102 )103 await send({"type": "http.response.body", "body": b"Hello, world!"})Add cli support (#1855)Tom Christiebefore adoptionee9250d
lines 104–114why, one step back104105106async def hello_world_json(scope, receive, send):107 await send(108 {109 "type": "http.response.start",110 "status": 200,111 "headers": [[b"content-type", b"application/json"]],112 }113 )114 await send({"type": "http.response.body", "body": b'{"Hello": "world!"}'})📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 115–154why, one step back115116117async def slow_response(scope, receive, send):118 await sleep(1.0)119 await send(120 {121 "type": "http.response.start",122 "status": 200,123 "headers": [[b"content-type", b"text/plain"]],124 }125 )126 await send({"type": "http.response.body", "body": b"Hello, world!"})127128129async def status_code(scope, receive, send):130 status_code = int(scope["path"].replace("/status/", ""))131 await send(132 {133 "type": "http.response.start",134 "status": status_code,135 "headers": [[b"content-type", b"text/plain"]],136 }137 )138 await send({"type": "http.response.body", "body": b"Hello, world!"})139140141async def echo_body(scope, receive, send):142 body = b""143 more_body = True144145 while more_body:146 message = await receive()147 body += message.get("body", b"")148 more_body = message.get("more_body", False)149150 await send(151 {152 "type": "http.response.start",153 "status": 200,154 "headers": [[b"content-type", b"text/plain"]],Suppress binary output on the command line (#2049) (#2076)waterfountain1996before adoption4c30748
lines 155–173why, one step back155 }156 )157 await send({"type": "http.response.body", "body": body})158159160async def echo_binary(scope, receive, send):161 body = b""162 more_body = True163164 while more_body:165 message = await receive()166 body += message.get("body", b"")167 more_body = message.get("more_body", False)168169 await send(170 {171 "type": "http.response.start",172 "status": 200,173 "headers": [[b"content-type", b"application/octet-stream"]],📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 174–266why, one step back174 }175 )176 await send({"type": "http.response.body", "body": body})177178179async def echo_headers(scope, receive, send):180 body = {181 name.capitalize().decode(): value.decode()182 for name, value in scope.get("headers", [])183 }184 await send(185 {186 "type": "http.response.start",187 "status": 200,188 "headers": [[b"content-type", b"application/json"]],189 }190 )191 await send({"type": "http.response.body", "body": json.dumps(body).encode()})192193194async def redirect_301(scope, receive, send):195 await send(196 {"type": "http.response.start", "status": 301, "headers": [[b"location", b"/"]]}197 )198 await send({"type": "http.response.body"})199200201@pytest.fixture(scope="session")202def cert_authority():203 return trustme.CA()204205206@pytest.fixture(scope="session")207def ca_cert_pem_file(cert_authority):208 with cert_authority.cert_pem.tempfile() as tmp:209 yield tmp210211212@pytest.fixture(scope="session")213def localhost_cert(cert_authority):214 return cert_authority.issue_cert("localhost")215216217@pytest.fixture(scope="session")218def cert_pem_file(localhost_cert):219 with localhost_cert.cert_chain_pems[0].tempfile() as tmp:220 yield tmp221222223@pytest.fixture(scope="session")224def cert_private_key_file(localhost_cert):225 with localhost_cert.private_key_pem.tempfile() as tmp:226 yield tmp227228229@pytest.fixture(scope="session")230def cert_encrypted_private_key_file(localhost_cert):231 # Deserialize the private key and then reserialize with a password232 private_key = load_pem_private_key(233 localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()234 )235 encrypted_private_key_pem = trustme.Blob(236 private_key.private_bytes(237 Encoding.PEM,238 PrivateFormat.TraditionalOpenSSL,239 BestAvailableEncryption(password=b"password"),240 )241 )242 with encrypted_private_key_pem.tempfile() as tmp:243 yield tmp244245246class TestServer(Server):247 @property248 def url(self) -> URL:249 protocol = "https" if self.config.is_ssl else "http"250 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")251252 def install_signal_handlers(self) -> None:253 # Disable the default installation of handlers for signals such as SIGTERM,254 # because it can only be done in the main thread.255 pass256257 async def serve(self, sockets=None):258 self.restart_requested = asyncio.Event()259260 loop = asyncio.get_event_loop()261 tasks = {262 loop.create_task(super().serve(sockets=sockets)),263 loop.create_task(self.watch_restarts()),264 }265 await asyncio.wait(tasks)266use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830
line 267why, one step back267 async def restart(self) -> None: # pragma: no cover📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 268–277why, one step back268 # This coroutine may be called from a different thread than the one the269 # server is running on, and from an async environment that's not asyncio.270 # For this reason, we use an event to coordinate with the server271 # instead of calling shutdown()/startup() directly, and should not make272 # any asyncio-specific operations.273 self.started = False274 self.restart_requested.set()275 while not self.started:276 await sleep(0.2)277use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830
line 278why, one step back278 async def watch_restarts(self): # pragma: no cover📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 279–292why, one step back279 while True:280 if self.should_exit:281 return282283 try:284 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)285 except asyncio.TimeoutError:286 continue287288 self.restart_requested.clear()289 await self.shutdown()290 await self.startup()291292Typing: enable disallow_incomplete_defs (#2476)Martijn Pietersbefore adoption049afe5
line 293why, one step back293def serve_in_thread(server: TestServer) -> typing.Iterator[TestServer]:📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 294–305why, one step back294 thread = threading.Thread(target=server.run)295 thread.start()296 try:297 while not server.started:298 time.sleep(1e-3)299 yield server300 finally:301 server.should_exit = True302 thread.join()303304305@pytest.fixture(scope="session")Typing: enable disallow_incomplete_defs (#2476)Martijn Pietersbefore adoption049afe5
line 306why, one step back306def server() -> typing.Iterator[TestServer]:📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 307–323why, one step back307 config = Config(app=app, lifespan="off", loop="asyncio")308 server = TestServer(config=config)309 yield from serve_in_thread(server)310311312@pytest.fixture(scope="session")313def https_server(cert_pem_file, cert_private_key_file):314 config = Config(315 app=app,316 lifespan="off",317 ssl_certfile=cert_pem_file,318 ssl_keyfile=cert_private_key_file,319 port=8001,320 loop="asyncio",321 )322 server = TestServer(config=config)323 yield from serve_in_thread(server)