conftest.py
This file
Path
tests/conftest.py
305 lines · 8.8 KiB · Python
Last changed by
replace pytest-asyncio and pytest-trio with anyio (#2512)Thomas Graingerbefore adoptione27d1b8
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–22why, one step back1920from httpx import URL21from tests.concurrency import sleep22Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
lines 23–25why, one step back23if typing.TYPE_CHECKING: # pragma: no cover24 from httpx._transports.asgi import _Receive, _Send25📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 26–53why, one step back26ENVIRONMENT_VARIABLES = {27 "SSL_CERT_FILE",28 "SSL_CERT_DIR",29 "HTTP_PROXY",30 "HTTPS_PROXY",31 "ALL_PROXY",32 "NO_PROXY",33 "SSLKEYLOGFILE",34}353637@pytest.fixture(scope="function", autouse=True)38def clean_environ():39 """Keeps os.environ clean for every test without having to mock os.environ"""40 original_environ = os.environ.copy()41 os.environ.clear()42 os.environ.update(43 {44 k: v45 for k, v in original_environ.items()46 if k not in ENVIRONMENT_VARIABLES and k.lower() not in ENVIRONMENT_VARIABLES47 }48 )49 yield50 os.environ.clear()51 os.environ.update(original_environ)5253Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
lines 54–57why, one step back54_Scope = typing.Dict[str, typing.Any]555657async def app(scope: _Scope, receive: "_Receive", send: "_Send") -> None:📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 58–64why, one step back58 assert scope["type"] == "http"59 if scope["path"].startswith("/slow_response"):60 await slow_response(scope, receive, send)61 elif scope["path"].startswith("/status"):62 await status_code(scope, receive, send)63 elif scope["path"].startswith("/echo_body"):64 await echo_body(scope, receive, send)Suppress binary output on the command line (#2049) (#2076)waterfountain1996before adoption4c30748
lines 65–66why, one step back65 elif scope["path"].startswith("/echo_binary"):66 await echo_binary(scope, receive, send)📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 67–70why, one step back67 elif scope["path"].startswith("/echo_headers"):68 await echo_headers(scope, receive, send)69 elif scope["path"].startswith("/redirect_301"):70 await redirect_301(scope, receive, send)Add cli support (#1855)Tom Christiebefore adoptionee9250d
lines 71–72why, one step back71 elif scope["path"].startswith("/json"):72 await hello_world_json(scope, receive, send)📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 73–76why, one step back73 else:74 await hello_world(scope, receive, send)7576Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 77why, one step back77async def hello_world(scope: _Scope, receive: "_Receive", send: "_Send") -> None:📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 78–85why, one step back78 await send(79 {80 "type": "http.response.start",81 "status": 200,82 "headers": [[b"content-type", b"text/plain"]],83 }84 )85 await send({"type": "http.response.body", "body": b"Hello, world!"})Add cli support (#1855)Tom Christiebefore adoptionee9250d
lines 86–87why, one step back8687Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 88why, one step back88async def hello_world_json(scope: _Scope, receive: "_Receive", send: "_Send") -> None:Add cli support (#1855)Tom Christiebefore adoptionee9250d
lines 89–96why, one step back89 await send(90 {91 "type": "http.response.start",92 "status": 200,93 "headers": [[b"content-type", b"application/json"]],94 }95 )96 await send({"type": "http.response.body", "body": b'{"Hello": "world!"}'})📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 97–98why, one step back9798Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 99why, one step back99async def slow_response(scope: _Scope, receive: "_Receive", send: "_Send") -> None:📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 100–110why, one step back100 await sleep(1.0)101 await send(102 {103 "type": "http.response.start",104 "status": 200,105 "headers": [[b"content-type", b"text/plain"]],106 }107 )108 await send({"type": "http.response.body", "body": b"Hello, world!"})109110Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 111why, one step back111async def status_code(scope: _Scope, receive: "_Receive", send: "_Send") -> None:📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 112–122why, one step back112 status_code = int(scope["path"].replace("/status/", ""))113 await send(114 {115 "type": "http.response.start",116 "status": status_code,117 "headers": [[b"content-type", b"text/plain"]],118 }119 )120 await send({"type": "http.response.body", "body": b"Hello, world!"})121122Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 123why, one step back123async def echo_body(scope: _Scope, receive: "_Receive", send: "_Send") -> None:📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 124–136why, one step back124 body = b""125 more_body = True126127 while more_body:128 message = await receive()129 body += message.get("body", b"")130 more_body = message.get("more_body", False)131132 await send(133 {134 "type": "http.response.start",135 "status": 200,136 "headers": [[b"content-type", b"text/plain"]],Suppress binary output on the command line (#2049) (#2076)waterfountain1996before adoption4c30748
lines 137–141why, one step back137 }138 )139 await send({"type": "http.response.body", "body": body})140141Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 142why, one step back142async def echo_binary(scope: _Scope, receive: "_Receive", send: "_Send") -> None:Suppress binary output on the command line (#2049) (#2076)waterfountain1996before adoption4c30748
lines 143–155why, one step back143 body = b""144 more_body = True145146 while more_body:147 message = await receive()148 body += message.get("body", b"")149 more_body = message.get("more_body", False)150151 await send(152 {153 "type": "http.response.start",154 "status": 200,155 "headers": [[b"content-type", b"application/octet-stream"]],📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 156–160why, one step back156 }157 )158 await send({"type": "http.response.body", "body": body})159160Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 161why, one step back161async def echo_headers(scope: _Scope, receive: "_Receive", send: "_Send") -> None:📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 162–175why, one step back162 body = {163 name.capitalize().decode(): value.decode()164 for name, value in scope.get("headers", [])165 }166 await send(167 {168 "type": "http.response.start",169 "status": 200,170 "headers": [[b"content-type", b"application/json"]],171 }172 )173 await send({"type": "http.response.body", "body": json.dumps(body).encode()})174175Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 176why, one step back176async def redirect_301(scope: _Scope, receive: "_Receive", send: "_Send") -> None:📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 177–248why, one step back177 await send(178 {"type": "http.response.start", "status": 301, "headers": [[b"location", b"/"]]}179 )180 await send({"type": "http.response.body"})181182183@pytest.fixture(scope="session")184def cert_authority():185 return trustme.CA()186187188@pytest.fixture(scope="session")189def ca_cert_pem_file(cert_authority):190 with cert_authority.cert_pem.tempfile() as tmp:191 yield tmp192193194@pytest.fixture(scope="session")195def localhost_cert(cert_authority):196 return cert_authority.issue_cert("localhost")197198199@pytest.fixture(scope="session")200def cert_pem_file(localhost_cert):201 with localhost_cert.cert_chain_pems[0].tempfile() as tmp:202 yield tmp203204205@pytest.fixture(scope="session")206def cert_private_key_file(localhost_cert):207 with localhost_cert.private_key_pem.tempfile() as tmp:208 yield tmp209210211@pytest.fixture(scope="session")212def cert_encrypted_private_key_file(localhost_cert):213 # Deserialize the private key and then reserialize with a password214 private_key = load_pem_private_key(215 localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()216 )217 encrypted_private_key_pem = trustme.Blob(218 private_key.private_bytes(219 Encoding.PEM,220 PrivateFormat.TraditionalOpenSSL,221 BestAvailableEncryption(password=b"password"),222 )223 )224 with encrypted_private_key_pem.tempfile() as tmp:225 yield tmp226227228class TestServer(Server):229 @property230 def url(self) -> URL:231 protocol = "https" if self.config.is_ssl else "http"232 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")233234 def install_signal_handlers(self) -> None:235 # Disable the default installation of handlers for signals such as SIGTERM,236 # because it can only be done in the main thread.237 pass238239 async def serve(self, sockets=None):240 self.restart_requested = asyncio.Event()241242 loop = asyncio.get_event_loop()243 tasks = {244 loop.create_task(super().serve(sockets=sockets)),245 loop.create_task(self.watch_restarts()),246 }247 await asyncio.wait(tasks)248use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830
line 249why, one step back249 async def restart(self) -> None: # pragma: no cover📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 250–259why, one step back250 # This coroutine may be called from a different thread than the one the251 # server is running on, and from an async environment that's not asyncio.252 # For this reason, we use an event to coordinate with the server253 # instead of calling shutdown()/startup() directly, and should not make254 # any asyncio-specific operations.255 self.started = False256 self.restart_requested.set()257 while not self.started:258 await sleep(0.2)259Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 260why, one step back260 async def watch_restarts(self) -> None: # pragma: no cover📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 261–274why, one step back261 while True:262 if self.should_exit:263 return264265 try:266 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)267 except asyncio.TimeoutError:268 continue269270 self.restart_requested.clear()271 await self.shutdown()272 await self.startup()273274Typing: enable disallow_incomplete_defs (#2476)Martijn Pietersbefore adoption049afe5
line 275why, one step back275def serve_in_thread(server: TestServer) -> typing.Iterator[TestServer]:📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 276–287why, one step back276 thread = threading.Thread(target=server.run)277 thread.start()278 try:279 while not server.started:280 time.sleep(1e-3)281 yield server282 finally:283 server.should_exit = True284 thread.join()285286287@pytest.fixture(scope="session")Typing: enable disallow_incomplete_defs (#2476)Martijn Pietersbefore adoption049afe5
line 288why, one step back288def server() -> typing.Iterator[TestServer]:📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa
lines 289–305why, one step back289 config = Config(app=app, lifespan="off", loop="asyncio")290 server = TestServer(config=config)291 yield from serve_in_thread(server)292293294@pytest.fixture(scope="session")295def https_server(cert_pem_file, cert_private_key_file):296 config = Config(297 app=app,298 lifespan="off",299 ssl_certfile=cert_pem_file,300 ssl_keyfile=cert_private_key_file,301 port=8001,302 loop="asyncio",303 )304 server = TestServer(config=config)305 yield from serve_in_thread(server)