Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

335 lines · 9.1 KiB · Python

Last changed by

Drop `run` and `run_in_threadpool` (#710)Tom Christiebefore adoption6ac49da

History of this file

Take it

The walk stopped after 200 commits: lines older than e1da6b9 point at it.

Add tool for profiling (#364)Florimond Mancabefore adoptione1da6b9

lines 1–19why, one step back
1import asyncio
2import 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 Config18from uvicorn.main import Server19

Tighten up top-level API to only expose public API (#608)Tom Christiebefore adoptiond15dc0b

line 20why, one step back
20from httpx import URL

Drop `run` and `run_in_threadpool` (#710)Tom Christiebefore adoption6ac49da

line 21why, one step back
21from tests.concurrency import sleep

Add tool for profiling (#364)Florimond Mancabefore adoptione1da6b9

lines 22–33why, one step back
22
23ENVIRONMENT_VARIABLES = {24 "SSL_CERT_FILE",25 "SSL_CERT_DIR",26 "HTTP_PROXY",27 "HTTPS_PROXY",28 "ALL_PROXY",29 "NO_PROXY",30 "SSLKEYLOGFILE",31}3233

Clean up 'backend' fixture (#664)Florimond Mancabefore adoptiond0427be

lines 34–57why, one step back
34@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 """55 return request.param5657

Add tool for profiling (#364)Florimond Mancabefore adoptione1da6b9

lines 58–78why, one step back
58@pytest.fixture(scope="function", autouse=True)
59def clean_environ() -> typing.Dict[str, typing.Any]: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)

Handle h11.Connection.next_event() RemoteProtocolError (#524)toppkbefore adoptionf06ca87

lines 79–80why, one step back
79 elif scope["path"].startswith("/premature_close"):
80 await premature_close(scope, receive, send)

Add tool for profiling (#364)Florimond Mancabefore adoptione1da6b9

lines 81–86why, one step back
81 elif scope["path"].startswith("/status"):
82 await status_code(scope, receive, send)83 elif scope["path"].startswith("/echo_body"):84 await echo_body(scope, receive, send)85 elif scope["path"].startswith("/echo_headers"):86 await echo_headers(scope, receive, send)

Add DEBUG logs of HTTP requests (#502)Florimond Mancabefore adoption08069e9

lines 87–88why, one step back
87 elif scope["path"].startswith("/redirect_301"):
88 await redirect_301(scope, receive, send)

Add tool for profiling (#364)Florimond Mancabefore adoptione1da6b9

lines 89–109why, one step back
89 else:
90 await hello_world(scope, receive, send)919293async def hello_world(scope, receive, send):94 await send(95 {96 "type": "http.response.start",97 "status": 200,98 "headers": [[b"content-type", b"text/plain"]],99 }100 )101 await send({"type": "http.response.body", "body": b"Hello, world!"})102103104async def slow_response(scope, receive, send):105 delay_ms_str: str = scope["path"].replace("/slow_response/", "")106 try:107 delay_ms = float(delay_ms_str)108 except ValueError:109 delay_ms = 100

Drop `run` and `run_in_threadpool` (#710)Tom Christiebefore adoption6ac49da

line 110why, one step back
110 await sleep(delay_ms / 1000.0)

Add tool for profiling (#364)Florimond Mancabefore adoptione1da6b9

lines 111–118why, one step back
111 await send(
112 {113 "type": "http.response.start",114 "status": 200,115 "headers": [[b"content-type", b"text/plain"]],116 }117 )118 await send({"type": "http.response.body", "body": b"Hello, world!"})

Handle h11.Connection.next_event() RemoteProtocolError (#524)toppkbefore adoptionf06ca87

lines 119–128why, one step back
119
120121async def premature_close(scope, receive, send):122 await send(123 {124 "type": "http.response.start",125 "status": 200,126 "headers": [[b"content-type", b"text/plain"]],127 }128 )

Add tool for profiling (#364)Florimond Mancabefore adoptione1da6b9

lines 129–174why, one step back
129
130131async def status_code(scope, receive, send):132 status_code = int(scope["path"].replace("/status/", ""))133 await send(134 {135 "type": "http.response.start",136 "status": status_code,137 "headers": [[b"content-type", b"text/plain"]],138 }139 )140 await send({"type": "http.response.body", "body": b"Hello, world!"})141142143async def echo_body(scope, receive, send):144 body = b""145 more_body = True146147 while more_body:148 message = await receive()149 body += message.get("body", b"")150 more_body = message.get("more_body", False)151152 await send(153 {154 "type": "http.response.start",155 "status": 200,156 "headers": [[b"content-type", b"text/plain"]],157 }158 )159 await send({"type": "http.response.body", "body": body})160161162async def echo_headers(scope, receive, send):163 body = {}164 for name, value in scope.get("headers", []):165 body[name.capitalize().decode()] = value.decode()166167 await send(168 {169 "type": "http.response.start",170 "status": 200,171 "headers": [[b"content-type", b"application/json"]],172 }173 )174 await send({"type": "http.response.body", "body": json.dumps(body).encode()})

Add DEBUG logs of HTTP requests (#502)Florimond Mancabefore adoption08069e9

lines 175–178why, one step back
175
176177async def redirect_301(scope, receive, send):178 await send(

Drop sync (#544)Tom Christiebefore adoption206c537

line 179why, one step back
179 {"type": "http.response.start", "status": 301, "headers": [[b"location", b"/"]]}

Add DEBUG logs of HTTP requests (#502)Florimond Mancabefore adoption08069e9

lines 180–181why, one step back
180 )
181 await send({"type": "http.response.body"})

Add tool for profiling (#364)Florimond Mancabefore adoptione1da6b9

lines 182–253why, one step back
182
183184SERVER_SCOPE = "session"185186187@pytest.fixture(scope=SERVER_SCOPE)188def cert_authority():189 return trustme.CA()190191192@pytest.fixture(scope=SERVER_SCOPE)193def ca_cert_pem_file(cert_authority):194 with cert_authority.cert_pem.tempfile() as tmp:195 yield tmp196197198@pytest.fixture(scope=SERVER_SCOPE)199def localhost_cert(cert_authority):200 return cert_authority.issue_cert("localhost")201202203@pytest.fixture(scope=SERVER_SCOPE)204def cert_pem_file(localhost_cert):205 with localhost_cert.cert_chain_pems[0].tempfile() as tmp:206 yield tmp207208209@pytest.fixture(scope=SERVER_SCOPE)210def cert_private_key_file(localhost_cert):211 with localhost_cert.private_key_pem.tempfile() as tmp:212 yield tmp213214215@pytest.fixture(scope=SERVER_SCOPE)216def cert_encrypted_private_key_file(localhost_cert):217 # Deserialize the private key and then reserialize with a password218 private_key = load_pem_private_key(219 localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()220 )221 encrypted_private_key_pem = trustme.Blob(222 private_key.private_bytes(223 Encoding.PEM,224 PrivateFormat.TraditionalOpenSSL,225 BestAvailableEncryption(password=b"password"),226 )227 )228 with encrypted_private_key_pem.tempfile() as tmp:229 yield tmp230231232class TestServer(Server):233 @property234 def url(self) -> URL:235 protocol = "https" if self.config.is_ssl else "http"236 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")237238 def install_signal_handlers(self) -> None:239 # Disable the default installation of handlers for signals such as SIGTERM,240 # because it can only be done in the main thread.241 pass242243 async def serve(self, sockets=None):244 self.restart_requested = asyncio.Event()245246 loop = asyncio.get_event_loop()247 tasks = {248 loop.create_task(super().serve(sockets=sockets)),249 loop.create_task(self.watch_restarts()),250 }251 await asyncio.wait(tasks)252253 async def restart(self) -> None:

Drop `run` and `run_in_threadpool` (#710)Tom Christiebefore adoption6ac49da

lines 254–258why, one step back
254 # This coroutine may be called from a different thread than the one the
255 # server is running on, and from an async environment that's not asyncio.256 # For this reason, we use an event to coordinate with the server257 # instead of calling shutdown()/startup() directly, and should not make258 # any asyncio-specific operations.

Add tool for profiling (#364)Florimond Mancabefore adoptione1da6b9

line 259why, one step back
259 self.started = False

Drop `run` and `run_in_threadpool` (#710)Tom Christiebefore adoption6ac49da

line 260why, one step back
260 self.restart_requested.set()

Add tool for profiling (#364)Florimond Mancabefore adoptione1da6b9

line 261why, one step back
261 while not self.started:

Drop `run` and `run_in_threadpool` (#710)Tom Christiebefore adoption6ac49da

line 262why, one step back
262 await sleep(0.2)

Add tool for profiling (#364)Florimond Mancabefore adoptione1da6b9

lines 263–298why, one step back
263
264 async def watch_restarts(self):265 while True:266 if self.should_exit:267 return268269 try:270 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)271 except asyncio.TimeoutError:272 continue273274 self.restart_requested.clear()275 await self.shutdown()276 await self.startup()277278279def serve_in_thread(server: Server):280 thread = threading.Thread(target=server.run)281 thread.start()282 try:283 while not server.started:284 time.sleep(1e-3)285 yield server286 finally:287 server.should_exit = True288 thread.join()289290291@pytest.fixture(scope=SERVER_SCOPE)292def server():293 config = Config(app=app, lifespan="off", loop="asyncio")294 server = TestServer(config=config)295 yield from serve_in_thread(server)296297298@pytest.fixture(scope=SERVER_SCOPE)

Add support for unix domain sockets (#511)Jonas Lundbergbefore adoption7a96a2c

lines 299–307why, one step back
299def uds_server():
300 uds = "test_server.sock"301 config = Config(app=app, lifespan="off", loop="asyncio", uds=uds)302 server = TestServer(config=config)303 yield from serve_in_thread(server)304 os.remove(uds)305306307@pytest.fixture(scope=SERVER_SCOPE)

Add tool for profiling (#364)Florimond Mancabefore adoptione1da6b9

lines 308–319why, one step back
308def https_server(cert_pem_file, cert_private_key_file):
309 config = Config(310 app=app,311 lifespan="off",312 ssl_certfile=cert_pem_file,313 ssl_keyfile=cert_private_key_file,314 host="localhost",315 port=8001,316 loop="asyncio",317 )318 server = TestServer(config=config)319 yield from serve_in_thread(server)

Add support for unix domain sockets (#511)Jonas Lundbergbefore adoption7a96a2c

lines 320–335why, one step back
320
321322@pytest.fixture(scope=SERVER_SCOPE)323def https_uds_server(cert_pem_file, cert_private_key_file):324 uds = "https_test_server.sock"325 config = Config(326 app=app,327 lifespan="off",328 ssl_certfile=cert_pem_file,329 ssl_keyfile=cert_private_key_file,330 uds=uds,331 loop="asyncio",332 )333 server = TestServer(config=config)334 yield from serve_in_thread(server)335 os.remove(uds)