conftest.py
This file
Path
tests/conftest.py
305 lines · 8.9 KiB · Python
Last changed by
Drop private imports from test_exceptions.py (#2571)Florimond Mancabefore adoption7488b15
History of this fileTake it
1import 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 Config18from uvicorn.server import Server1920from httpx import URL21from tests.concurrency import sleep2223if typing.TYPE_CHECKING: # pragma: no cover24 from httpx._transports.asgi import _Receive, _Send2526ENVIRONMENT_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)525354_Scope = typing.Dict[str, typing.Any]555657async def app(scope: _Scope, receive: "_Receive", send: "_Send") -> None:58 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)65 elif scope["path"].startswith("/echo_binary"):66 await echo_binary(scope, receive, send)67 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)71 elif scope["path"].startswith("/json"):72 await hello_world_json(scope, receive, send)73 else:74 await hello_world(scope, receive, send)757677async def hello_world(scope: _Scope, receive: "_Receive", send: "_Send") -> None:78 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!"})868788async def hello_world_json(scope: _Scope, receive: "_Receive", send: "_Send") -> None:89 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!"}'})979899async def slow_response(scope: _Scope, receive: "_Receive", send: "_Send") -> None:100 await send(101 {102 "type": "http.response.start",103 "status": 200,104 "headers": [[b"content-type", b"text/plain"]],105 }106 )107 await sleep(1.0) # Allow triggering a read timeout.108 await send({"type": "http.response.body", "body": b"Hello, world!"})109110111async def status_code(scope: _Scope, receive: "_Receive", send: "_Send") -> None:112 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!"})121122123async def echo_body(scope: _Scope, receive: "_Receive", send: "_Send") -> None:124 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"]],137 }138 )139 await send({"type": "http.response.body", "body": body})140141142async def echo_binary(scope: _Scope, receive: "_Receive", send: "_Send") -> None:143 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"]],156 }157 )158 await send({"type": "http.response.body", "body": body})159160161async def echo_headers(scope: _Scope, receive: "_Receive", send: "_Send") -> None:162 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()})174175176async def redirect_301(scope: _Scope, receive: "_Receive", send: "_Send") -> None:177 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)248249 async def restart(self) -> None: # pragma: no cover250 # 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)259260 async def watch_restarts(self) -> None: # pragma: no cover261 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()273274275def serve_in_thread(server: TestServer) -> typing.Iterator[TestServer]:276 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")288def server() -> typing.Iterator[TestServer]:289 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)