Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

329 lines · 9.4 KiB · Python

Last changed by

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

History of this file

Take 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 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 Config

Enable no_implicit_reexport (#2475)Martijn Pietersbefore adoption57aa5b0

line 18why, one step back
18from uvicorn.server import Server

📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa

lines 19–22why, one step back
19
20from httpx import URL21from tests.concurrency import sleep22

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

lines 23–25why, one step back
23if typing.TYPE_CHECKING: # pragma: no cover
24 from httpx._transports.asgi import _Receive, _Send25

📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa

lines 26–57why, one step back
26ENVIRONMENT_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(38 params=[39 pytest.param("asyncio", marks=pytest.mark.asyncio),40 pytest.param("trio", marks=pytest.mark.trio),41 ]42)43def async_environment(request: typing.Any) -> str:44 """45 Mark a test function to be run on both asyncio and trio.4647 Equivalent to having a pair of tests, each respectively marked with48 '@pytest.mark.asyncio' and '@pytest.mark.trio'.4950 Intended usage:5152 ```53 @pytest.mark.usefixtures("async_environment")54 async def my_async_test():55 ...56 ```57 """

Typing: enable warn_return_any (#2477)Martijn Pietersbefore adoption2d37321

line 58why, one step back
58 return typing.cast(str, request.param)

📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa

lines 59–77why, one step back
59
6061@pytest.fixture(scope="function", autouse=True)62def clean_environ():63 """Keeps os.environ clean for every test without having to mock os.environ"""64 original_environ = os.environ.copy()65 os.environ.clear()66 os.environ.update(67 {68 k: v69 for k, v in original_environ.items()70 if k not in ENVIRONMENT_VARIABLES and k.lower() not in ENVIRONMENT_VARIABLES71 }72 )73 yield74 os.environ.clear()75 os.environ.update(original_environ)7677

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

lines 78–81why, one step back
78_Scope = typing.Dict[str, typing.Any]
798081async def app(scope: _Scope, receive: "_Receive", send: "_Send") -> None:

📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa

lines 82–88why, one step back
82 assert scope["type"] == "http"
83 if scope["path"].startswith("/slow_response"):84 await slow_response(scope, receive, send)85 elif scope["path"].startswith("/status"):86 await status_code(scope, receive, send)87 elif scope["path"].startswith("/echo_body"):88 await echo_body(scope, receive, send)

Suppress binary output on the command line (#2049) (#2076)waterfountain1996before adoption4c30748

lines 89–90why, one step back
89 elif scope["path"].startswith("/echo_binary"):
90 await echo_binary(scope, receive, send)

📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa

lines 91–94why, one step back
91 elif scope["path"].startswith("/echo_headers"):
92 await echo_headers(scope, receive, send)93 elif scope["path"].startswith("/redirect_301"):94 await redirect_301(scope, receive, send)

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 95–96why, one step back
95 elif scope["path"].startswith("/json"):
96 await hello_world_json(scope, receive, send)

📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa

lines 97–100why, one step back
97 else:
98 await hello_world(scope, receive, send)99100

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

line 101why, one step back
101async def hello_world(scope: _Scope, receive: "_Receive", send: "_Send") -> None:

📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa

lines 102–109why, one step back
102 await send(
103 {104 "type": "http.response.start",105 "status": 200,106 "headers": [[b"content-type", b"text/plain"]],107 }108 )109 await send({"type": "http.response.body", "body": b"Hello, world!"})

Add cli support (#1855)Tom Christiebefore adoptionee9250d

lines 110–111why, one step back
110
111

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

line 112why, one step back
112async def hello_world_json(scope: _Scope, receive: "_Receive", send: "_Send") -> None:

Add cli support (#1855)Tom Christiebefore adoptionee9250d

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

📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa

lines 121–122why, one step back
121
122

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

line 123why, one step back
123async def slow_response(scope: _Scope, receive: "_Receive", send: "_Send") -> None:

📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa

lines 124–134why, one step back
124 await sleep(1.0)
125 await send(126 {127 "type": "http.response.start",128 "status": 200,129 "headers": [[b"content-type", b"text/plain"]],130 }131 )132 await send({"type": "http.response.body", "body": b"Hello, world!"})133134

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

line 135why, one step back
135async def status_code(scope: _Scope, receive: "_Receive", send: "_Send") -> None:

📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa

lines 136–146why, one step back
136 status_code = int(scope["path"].replace("/status/", ""))
137 await send(138 {139 "type": "http.response.start",140 "status": status_code,141 "headers": [[b"content-type", b"text/plain"]],142 }143 )144 await send({"type": "http.response.body", "body": b"Hello, world!"})145146

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

line 147why, one step back
147async def echo_body(scope: _Scope, receive: "_Receive", send: "_Send") -> None:

📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa

lines 148–160why, one step back
148 body = b""
149 more_body = True150151 while more_body:152 message = await receive()153 body += message.get("body", b"")154 more_body = message.get("more_body", False)155156 await send(157 {158 "type": "http.response.start",159 "status": 200,160 "headers": [[b"content-type", b"text/plain"]],

Suppress binary output on the command line (#2049) (#2076)waterfountain1996before adoption4c30748

lines 161–165why, one step back
161 }
162 )163 await send({"type": "http.response.body", "body": body})164165

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

line 166why, one step back
166async def echo_binary(scope: _Scope, receive: "_Receive", send: "_Send") -> None:

Suppress binary output on the command line (#2049) (#2076)waterfountain1996before adoption4c30748

lines 167–179why, one step back
167 body = b""
168 more_body = True169170 while more_body:171 message = await receive()172 body += message.get("body", b"")173 more_body = message.get("more_body", False)174175 await send(176 {177 "type": "http.response.start",178 "status": 200,179 "headers": [[b"content-type", b"application/octet-stream"]],

📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa

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

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

line 185why, one step back
185async def echo_headers(scope: _Scope, receive: "_Receive", send: "_Send") -> None:

📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa

lines 186–199why, one step back
186 body = {
187 name.capitalize().decode(): value.decode()188 for name, value in scope.get("headers", [])189 }190 await send(191 {192 "type": "http.response.start",193 "status": 200,194 "headers": [[b"content-type", b"application/json"]],195 }196 )197 await send({"type": "http.response.body", "body": json.dumps(body).encode()})198199

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

line 200why, one step back
200async def redirect_301(scope: _Scope, receive: "_Receive", send: "_Send") -> None:

📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa

lines 201–272why, one step back
201 await send(
202 {"type": "http.response.start", "status": 301, "headers": [[b"location", b"/"]]}203 )204 await send({"type": "http.response.body"})205206207@pytest.fixture(scope="session")208def cert_authority():209 return trustme.CA()210211212@pytest.fixture(scope="session")213def ca_cert_pem_file(cert_authority):214 with cert_authority.cert_pem.tempfile() as tmp:215 yield tmp216217218@pytest.fixture(scope="session")219def localhost_cert(cert_authority):220 return cert_authority.issue_cert("localhost")221222223@pytest.fixture(scope="session")224def cert_pem_file(localhost_cert):225 with localhost_cert.cert_chain_pems[0].tempfile() as tmp:226 yield tmp227228229@pytest.fixture(scope="session")230def cert_private_key_file(localhost_cert):231 with localhost_cert.private_key_pem.tempfile() as tmp:232 yield tmp233234235@pytest.fixture(scope="session")236def cert_encrypted_private_key_file(localhost_cert):237 # Deserialize the private key and then reserialize with a password238 private_key = load_pem_private_key(239 localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()240 )241 encrypted_private_key_pem = trustme.Blob(242 private_key.private_bytes(243 Encoding.PEM,244 PrivateFormat.TraditionalOpenSSL,245 BestAvailableEncryption(password=b"password"),246 )247 )248 with encrypted_private_key_pem.tempfile() as tmp:249 yield tmp250251252class TestServer(Server):253 @property254 def url(self) -> URL:255 protocol = "https" if self.config.is_ssl else "http"256 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")257258 def install_signal_handlers(self) -> None:259 # Disable the default installation of handlers for signals such as SIGTERM,260 # because it can only be done in the main thread.261 pass262263 async def serve(self, sockets=None):264 self.restart_requested = asyncio.Event()265266 loop = asyncio.get_event_loop()267 tasks = {268 loop.create_task(super().serve(sockets=sockets)),269 loop.create_task(self.watch_restarts()),270 }271 await asyncio.wait(tasks)272

use # pragma: no cover instead of # pragma: nocover (#2471)Adrian Garcia Badaraccobefore adoption16e2830

line 273why, one step back
273 async def restart(self) -> None: # pragma: no cover

📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa

lines 274–283why, one step back
274 # This coroutine may be called from a different thread than the one the
275 # server is running on, and from an async environment that's not asyncio.276 # For this reason, we use an event to coordinate with the server277 # instead of calling shutdown()/startup() directly, and should not make278 # any asyncio-specific operations.279 self.started = False280 self.restart_requested.set()281 while not self.started:282 await sleep(0.2)283

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

line 284why, one step back
284 async def watch_restarts(self) -> None: # pragma: no cover

📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa

lines 285–298why, one step back
285 while True:
286 if self.should_exit:287 return288289 try:290 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)291 except asyncio.TimeoutError:292 continue293294 self.restart_requested.clear()295 await self.shutdown()296 await self.startup()297298

Typing: enable disallow_incomplete_defs (#2476)Martijn Pietersbefore adoption049afe5

line 299why, one step back
299def serve_in_thread(server: TestServer) -> typing.Iterator[TestServer]:

📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa

lines 300–311why, one step back
300 thread = threading.Thread(target=server.run)
301 thread.start()302 try:303 while not server.started:304 time.sleep(1e-3)305 yield server306 finally:307 server.should_exit = True308 thread.join()309310311@pytest.fixture(scope="session")

Typing: enable disallow_incomplete_defs (#2476)Martijn Pietersbefore adoption049afe5

line 312why, one step back
312def server() -> typing.Iterator[TestServer]:

📌 Pin development requirements (#1721)Marcelo Trylesinskibefore adoption0ccc3fa

lines 313–329why, one step back
313 config = Config(app=app, lifespan="off", loop="asyncio")
314 server = TestServer(config=config)315 yield from serve_in_thread(server)316317318@pytest.fixture(scope="session")319def https_server(cert_pem_file, cert_private_key_file):320 config = Config(321 app=app,322 lifespan="off",323 ssl_certfile=cert_pem_file,324 ssl_keyfile=cert_private_key_file,325 port=8001,326 loop="asyncio",327 )328 server = TestServer(config=config)329 yield from serve_in_thread(server)