conftest.py
This file
Path
tests/conftest.py
307 lines · 8.9 KiB · Python
Last changed by
Drop private imports in tests/conftest.py (#2569)Florimond Mancabefore adoptionef06f7d
History of this fileTake it
The walk stopped after 200 commits: lines older than 770d4f2 point at it.
Remove unneeded installation on `install` script (#2398)Tom Christiebefore adoption770d4f2
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 ServerRemove unneeded installation on `install` script (#2398)Tom Christiebefore adoption770d4f2
line 19why, one step back19Drop private imports in tests/conftest.py (#2569)Florimond Mancabefore adoptionef06f7d
line 20why, one step back20import httpxRemove unneeded installation on `install` script (#2398)Tom Christiebefore adoption770d4f2
lines 21–50why, one step back21from 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(scope="function", autouse=True)35def clean_environ():36 """Keeps os.environ clean for every test without having to mock os.environ"""37 original_environ = os.environ.copy()38 os.environ.clear()39 os.environ.update(40 {41 k: v42 for k, v in original_environ.items()43 if k not in ENVIRONMENT_VARIABLES and k.lower() not in ENVIRONMENT_VARIABLES44 }45 )46 yield47 os.environ.clear()48 os.environ.update(original_environ)4950Drop private imports in tests/conftest.py (#2569)Florimond Mancabefore adoptionef06f7d
lines 51–56why, one step back51Message = typing.Dict[str, typing.Any]52Receive = typing.Callable[[], typing.Awaitable[Message]]53Send = typing.Callable[54 [typing.Dict[str, typing.Any]], typing.Coroutine[None, None, None]55]56Scope = typing.Dict[str, typing.Any]Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
lines 57–58why, one step back5758Drop private imports in tests/conftest.py (#2569)Florimond Mancabefore adoptionef06f7d
line 59why, one step back59async def app(scope: Scope, receive: Receive, send: Send) -> None:Remove unneeded installation on `install` script (#2398)Tom Christiebefore adoption770d4f2
lines 60–78why, one step back60 assert scope["type"] == "http"61 if scope["path"].startswith("/slow_response"):62 await slow_response(scope, receive, send)63 elif scope["path"].startswith("/status"):64 await status_code(scope, receive, send)65 elif scope["path"].startswith("/echo_body"):66 await echo_body(scope, receive, send)67 elif scope["path"].startswith("/echo_binary"):68 await echo_binary(scope, receive, send)69 elif scope["path"].startswith("/echo_headers"):70 await echo_headers(scope, receive, send)71 elif scope["path"].startswith("/redirect_301"):72 await redirect_301(scope, receive, send)73 elif scope["path"].startswith("/json"):74 await hello_world_json(scope, receive, send)75 else:76 await hello_world(scope, receive, send)7778Drop private imports in tests/conftest.py (#2569)Florimond Mancabefore adoptionef06f7d
line 79why, one step back79async def hello_world(scope: Scope, receive: Receive, send: Send) -> None:Remove unneeded installation on `install` script (#2398)Tom Christiebefore adoption770d4f2
lines 80–89why, one step back80 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": b"Hello, world!"})8889Drop private imports in tests/conftest.py (#2569)Florimond Mancabefore adoptionef06f7d
line 90why, one step back90async def hello_world_json(scope: Scope, receive: Receive, send: Send) -> None:Remove unneeded installation on `install` script (#2398)Tom Christiebefore adoption770d4f2
lines 91–100why, one step back91 await send(92 {93 "type": "http.response.start",94 "status": 200,95 "headers": [[b"content-type", b"application/json"]],96 }97 )98 await send({"type": "http.response.body", "body": b'{"Hello": "world!"}'})99100Drop private imports in tests/conftest.py (#2569)Florimond Mancabefore adoptionef06f7d
line 101why, one step back101async def slow_response(scope: Scope, receive: Receive, send: Send) -> None:Remove unneeded installation on `install` script (#2398)Tom Christiebefore adoption770d4f2
lines 102–108why, one step back102 await send(103 {104 "type": "http.response.start",105 "status": 200,106 "headers": [[b"content-type", b"text/plain"]],107 }108 )Drop private imports from test_exceptions.py (#2571)Florimond Mancabefore adoption7488b15
line 109why, one step back109 await sleep(1.0) # Allow triggering a read timeout.Remove unneeded installation on `install` script (#2398)Tom Christiebefore adoption770d4f2
lines 110–112why, one step back110 await send({"type": "http.response.body", "body": b"Hello, world!"})111112Drop private imports in tests/conftest.py (#2569)Florimond Mancabefore adoptionef06f7d
line 113why, one step back113async def status_code(scope: Scope, receive: Receive, send: Send) -> None:Remove unneeded installation on `install` script (#2398)Tom Christiebefore adoption770d4f2
lines 114–124why, one step back114 status_code = int(scope["path"].replace("/status/", ""))115 await send(116 {117 "type": "http.response.start",118 "status": status_code,119 "headers": [[b"content-type", b"text/plain"]],120 }121 )122 await send({"type": "http.response.body", "body": b"Hello, world!"})123124Drop private imports in tests/conftest.py (#2569)Florimond Mancabefore adoptionef06f7d
line 125why, one step back125async def echo_body(scope: Scope, receive: Receive, send: Send) -> None:Remove unneeded installation on `install` script (#2398)Tom Christiebefore adoption770d4f2
lines 126–143why, one step back126 body = b""127 more_body = True128129 while more_body:130 message = await receive()131 body += message.get("body", b"")132 more_body = message.get("more_body", False)133134 await send(135 {136 "type": "http.response.start",137 "status": 200,138 "headers": [[b"content-type", b"text/plain"]],139 }140 )141 await send({"type": "http.response.body", "body": body})142143Drop private imports in tests/conftest.py (#2569)Florimond Mancabefore adoptionef06f7d
line 144why, one step back144async def echo_binary(scope: Scope, receive: Receive, send: Send) -> None:Remove unneeded installation on `install` script (#2398)Tom Christiebefore adoption770d4f2
lines 145–162why, one step back145 body = b""146 more_body = True147148 while more_body:149 message = await receive()150 body += message.get("body", b"")151 more_body = message.get("more_body", False)152153 await send(154 {155 "type": "http.response.start",156 "status": 200,157 "headers": [[b"content-type", b"application/octet-stream"]],158 }159 )160 await send({"type": "http.response.body", "body": body})161162Drop private imports in tests/conftest.py (#2569)Florimond Mancabefore adoptionef06f7d
line 163why, one step back163async def echo_headers(scope: Scope, receive: Receive, send: Send) -> None:Remove unneeded installation on `install` script (#2398)Tom Christiebefore adoption770d4f2
lines 164–177why, one step back164 body = {165 name.capitalize().decode(): value.decode()166 for name, value in scope.get("headers", [])167 }168 await send(169 {170 "type": "http.response.start",171 "status": 200,172 "headers": [[b"content-type", b"application/json"]],173 }174 )175 await send({"type": "http.response.body", "body": json.dumps(body).encode()})176177Drop private imports in tests/conftest.py (#2569)Florimond Mancabefore adoptionef06f7d
line 178why, one step back178async def redirect_301(scope: Scope, receive: Receive, send: Send) -> None:Remove unneeded installation on `install` script (#2398)Tom Christiebefore adoption770d4f2
lines 179–231why, one step back179 await send(180 {"type": "http.response.start", "status": 301, "headers": [[b"location", b"/"]]}181 )182 await send({"type": "http.response.body"})183184185@pytest.fixture(scope="session")186def cert_authority():187 return trustme.CA()188189190@pytest.fixture(scope="session")191def ca_cert_pem_file(cert_authority):192 with cert_authority.cert_pem.tempfile() as tmp:193 yield tmp194195196@pytest.fixture(scope="session")197def localhost_cert(cert_authority):198 return cert_authority.issue_cert("localhost")199200201@pytest.fixture(scope="session")202def cert_pem_file(localhost_cert):203 with localhost_cert.cert_chain_pems[0].tempfile() as tmp:204 yield tmp205206207@pytest.fixture(scope="session")208def cert_private_key_file(localhost_cert):209 with localhost_cert.private_key_pem.tempfile() as tmp:210 yield tmp211212213@pytest.fixture(scope="session")214def cert_encrypted_private_key_file(localhost_cert):215 # Deserialize the private key and then reserialize with a password216 private_key = load_pem_private_key(217 localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()218 )219 encrypted_private_key_pem = trustme.Blob(220 private_key.private_bytes(221 Encoding.PEM,222 PrivateFormat.TraditionalOpenSSL,223 BestAvailableEncryption(password=b"password"),224 )225 )226 with encrypted_private_key_pem.tempfile() as tmp:227 yield tmp228229230class TestServer(Server):231 @propertyDrop private imports in tests/conftest.py (#2569)Florimond Mancabefore adoptionef06f7d
line 232why, one step back232 def url(self) -> httpx.URL:Remove unneeded installation on `install` script (#2398)Tom Christiebefore adoption770d4f2
line 233why, one step back233 protocol = "https" if self.config.is_ssl else "http"Drop private imports in tests/conftest.py (#2569)Florimond Mancabefore adoptionef06f7d
line 234why, one step back234 return httpx.URL(f"{protocol}://{self.config.host}:{self.config.port}/")Remove unneeded installation on `install` script (#2398)Tom Christiebefore adoption770d4f2
lines 235–250why, one step back235236 def install_signal_handlers(self) -> None:237 # Disable the default installation of handlers for signals such as SIGTERM,238 # because it can only be done in the main thread.239 pass240241 async def serve(self, sockets=None):242 self.restart_requested = asyncio.Event()243244 loop = asyncio.get_event_loop()245 tasks = {246 loop.create_task(super().serve(sockets=sockets)),247 loop.create_task(self.watch_restarts()),248 }249 await asyncio.wait(tasks)250use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830
line 251why, one step back251 async def restart(self) -> None: # pragma: no coverRemove unneeded installation on `install` script (#2398)Tom Christiebefore adoption770d4f2
lines 252–261why, one step back252 # This coroutine may be called from a different thread than the one the253 # server is running on, and from an async environment that's not asyncio.254 # For this reason, we use an event to coordinate with the server255 # instead of calling shutdown()/startup() directly, and should not make256 # any asyncio-specific operations.257 self.started = False258 self.restart_requested.set()259 while not self.started:260 await sleep(0.2)261Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c
line 262why, one step back262 async def watch_restarts(self) -> None: # pragma: no coverRemove unneeded installation on `install` script (#2398)Tom Christiebefore adoption770d4f2
lines 263–276why, one step back263 while True:264 if self.should_exit:265 return266267 try:268 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)269 except asyncio.TimeoutError:270 continue271272 self.restart_requested.clear()273 await self.shutdown()274 await self.startup()275276Typing: enable disallow_incomplete_defs (#2476)Martijn Pietersbefore adoption049afe5
line 277why, one step back277def serve_in_thread(server: TestServer) -> typing.Iterator[TestServer]:Remove unneeded installation on `install` script (#2398)Tom Christiebefore adoption770d4f2
lines 278–289why, one step back278 thread = threading.Thread(target=server.run)279 thread.start()280 try:281 while not server.started:282 time.sleep(1e-3)283 yield server284 finally:285 server.should_exit = True286 thread.join()287288289@pytest.fixture(scope="session")Typing: enable disallow_incomplete_defs (#2476)Martijn Pietersbefore adoption049afe5
line 290why, one step back290def server() -> typing.Iterator[TestServer]:Remove unneeded installation on `install` script (#2398)Tom Christiebefore adoption770d4f2
lines 291–307why, one step back291 config = Config(app=app, lifespan="off", loop="asyncio")292 server = TestServer(config=config)293 yield from serve_in_thread(server)294295296@pytest.fixture(scope="session")297def https_server(cert_pem_file, cert_private_key_file):298 config = Config(299 app=app,300 lifespan="off",301 ssl_certfile=cert_pem_file,302 ssl_keyfile=cert_private_key_file,303 port=8001,304 loop="asyncio",305 )306 server = TestServer(config=config)307 yield from serve_in_thread(server)