Skip to content
Myr

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 file

Take it

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

Bump flake8-bugbear from 21.4.3 to 21.9.2 (#1917)dependabot[bot]before adoptionc531263

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

Bump flake8-bugbear from 21.4.3 to 21.9.2 (#1917)dependabot[bot]before adoptionc531263

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

Bump flake8-bugbear from 21.4.3 to 21.9.2 (#1917)dependabot[bot]before adoptionc531263

lines 26–53why, 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(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)5253

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

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

Bump flake8-bugbear from 21.4.3 to 21.9.2 (#1917)dependabot[bot]before adoptionc531263

lines 58–64why, one step back
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)

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

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

Bump flake8-bugbear from 21.4.3 to 21.9.2 (#1917)dependabot[bot]before adoptionc531263

lines 67–76why, one step back
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)7576

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

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

Bump flake8-bugbear from 21.4.3 to 21.9.2 (#1917)dependabot[bot]before adoptionc531263

lines 78–87why, one step back
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!"})8687

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

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

Bump flake8-bugbear from 21.4.3 to 21.9.2 (#1917)dependabot[bot]before adoptionc531263

lines 89–98why, one step back
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!"}'})9798

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

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

Bump flake8-bugbear from 21.4.3 to 21.9.2 (#1917)dependabot[bot]before adoptionc531263

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

Drop private imports from test_exceptions.py (#2571)Florimond Mancabefore adoption7488b15

line 107why, one step back
107 await sleep(1.0) # Allow triggering a read timeout.

Bump flake8-bugbear from 21.4.3 to 21.9.2 (#1917)dependabot[bot]before adoptionc531263

lines 108–110why, one step back
108 await send({"type": "http.response.body", "body": b"Hello, world!"})
109110

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

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

Bump flake8-bugbear from 21.4.3 to 21.9.2 (#1917)dependabot[bot]before adoptionc531263

lines 112–122why, one step back
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!"})121122

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

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

Bump flake8-bugbear from 21.4.3 to 21.9.2 (#1917)dependabot[bot]before adoptionc531263

lines 124–136why, one step back
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"]],

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

lines 137–141why, one step back
137 }
138 )139 await send({"type": "http.response.body", "body": body})140141

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

line 142why, one step back
142async 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 back
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"]],

Bump flake8-bugbear from 21.4.3 to 21.9.2 (#1917)dependabot[bot]before adoptionc531263

lines 156–160why, one step back
156 }
157 )158 await send({"type": "http.response.body", "body": body})159160

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

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

Bump flake8-bugbear from 21.4.3 to 21.9.2 (#1917)dependabot[bot]before adoptionc531263

lines 162–175why, one step back
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()})174175

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

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

Bump flake8-bugbear from 21.4.3 to 21.9.2 (#1917)dependabot[bot]before adoptionc531263

lines 177–248why, one step back
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)248

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

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

Bump flake8-bugbear from 21.4.3 to 21.9.2 (#1917)dependabot[bot]before adoptionc531263

lines 250–259why, one step back
250 # This coroutine may be called from a different thread than the one the
251 # 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)259

Typing: enable disallow_untyped_calls (#2479)Martijn Pietersbefore adoption933551c

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

Bump flake8-bugbear from 21.4.3 to 21.9.2 (#1917)dependabot[bot]before adoptionc531263

lines 261–274why, one step back
261 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()273274

Typing: enable disallow_incomplete_defs (#2476)Martijn Pietersbefore adoption049afe5

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

Bump flake8-bugbear from 21.4.3 to 21.9.2 (#1917)dependabot[bot]before adoptionc531263

lines 276–287why, one step back
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")

Typing: enable disallow_incomplete_defs (#2476)Martijn Pietersbefore adoption049afe5

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

Bump flake8-bugbear from 21.4.3 to 21.9.2 (#1917)dependabot[bot]before adoptionc531263

lines 289–305why, one step back
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)