Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

352 lines · 9.6 KiB · Python

Last changed by

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

History of this file

Take it

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

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

lines 1–9why, one step back
1import asyncio
2import json3import os4import threading5import time6import typing78import pytest9import trustme

Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360

line 10why, one step back
10from cryptography.hazmat.backends import default_backend

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

lines 11–14why, one step back
11from cryptography.hazmat.primitives.serialization import (
12 BestAvailableEncryption,13 Encoding,14 PrivateFormat,

Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085

line 15why, one step back
15 load_pem_private_key,

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

lines 16–19why, one step back
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

Rename `concurrency` directory to `backends` (#662)Andrés Álvarezbefore adoptione34df7a

lines 21–22why, one step back
21from httpx.backends.asyncio import AsyncioBackend
22from httpx.backends.base import lookup_backend

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

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

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

lines 35–58why, one step back
35@pytest.fixture(
36 params=[37 pytest.param("asyncio", marks=pytest.mark.asyncio),38 pytest.param("trio", marks=pytest.mark.trio),39 ]40)41def async_environment(request: typing.Any) -> str:42 """43 Mark a test function to be run on both asyncio and trio.4445 Equivalent to having a pair of tests, each respectively marked with46 '@pytest.mark.asyncio' and '@pytest.mark.trio'.4748 Intended usage:4950 ```51 @pytest.mark.usefixtures("async_environment")52 async def my_async_test():53 ...54 ```55 """56 return request.param5758

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

lines 59–77why, one step back
59@pytest.fixture(scope="function", autouse=True)
60def clean_environ() -> typing.Dict[str, typing.Any]:61 """Keeps os.environ clean for every test without having to mock os.environ"""62 original_environ = os.environ.copy()63 os.environ.clear()64 os.environ.update(65 {66 k: v67 for k, v in original_environ.items()68 if k not in ENVIRONMENT_VARIABLES and k.lower() not in ENVIRONMENT_VARIABLES69 }70 )71 yield72 os.environ.clear()73 os.environ.update(original_environ)747576async def app(scope, receive, send):77 assert scope["type"] == "http"

Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117

line 78why, one step back
78 if scope["path"].startswith("/slow_response"):

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

line 79why, one step back
79 await slow_response(scope, receive, send)

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

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

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

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

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

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

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

lines 90–105why, one step back
90 else:
91 await hello_world(scope, receive, send)929394async def hello_world(scope, receive, send):95 await send(96 {97 "type": "http.response.start",98 "status": 200,99 "headers": [[b"content-type", b"text/plain"]],100 }101 )102 await send({"type": "http.response.body", "body": b"Hello, world!"})103104105async def slow_response(scope, receive, send):

Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117

lines 106–111why, one step back
106 delay_ms_str: str = scope["path"].replace("/slow_response/", "")
107 try:108 delay_ms = float(delay_ms_str)109 except ValueError:110 delay_ms = 100111 await asyncio.sleep(delay_ms / 1000.0)

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

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

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

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

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

lines 130–175why, one step back
130
131132async def status_code(scope, receive, send):133 status_code = int(scope["path"].replace("/status/", ""))134 await send(135 {136 "type": "http.response.start",137 "status": status_code,138 "headers": [[b"content-type", b"text/plain"]],139 }140 )141 await send({"type": "http.response.body", "body": b"Hello, world!"})142143144async def echo_body(scope, receive, send):145 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"text/plain"]],158 }159 )160 await send({"type": "http.response.body", "body": body})161162163async def echo_headers(scope, receive, send):164 body = {}165 for name, value in scope.get("headers", []):166 body[name.capitalize().decode()] = value.decode()167168 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()})

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

lines 176–179why, one step back
176
177178async def redirect_301(scope, receive, send):179 await send(

Drop sync (#544)Tom Christiebefore adoption206c537

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

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

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

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

lines 183–184why, one step back
183
184

Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360

line 185why, one step back
185SERVER_SCOPE = "session"

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

lines 186–187why, one step back
186
187

Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360

lines 188–190why, one step back
188@pytest.fixture(scope=SERVER_SCOPE)
189def cert_authority():190 return trustme.CA()

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

lines 191–192why, one step back
191
192

Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360

lines 193–196why, one step back
193@pytest.fixture(scope=SERVER_SCOPE)
194def ca_cert_pem_file(cert_authority):195 with cert_authority.cert_pem.tempfile() as tmp:196 yield tmp

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

line 197why, one step back
197

Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360

line 198why, one step back
198

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

line 199why, one step back
199@pytest.fixture(scope=SERVER_SCOPE)

Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360

lines 200–201why, one step back
200def localhost_cert(cert_authority):
201 return cert_authority.issue_cert("localhost")

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

lines 202–204why, one step back
202
203204@pytest.fixture(scope=SERVER_SCOPE)

Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360

lines 205–206why, one step back
205def cert_pem_file(localhost_cert):
206 with localhost_cert.cert_chain_pems[0].tempfile() as tmp:

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

lines 207–210why, one step back
207 yield tmp
208209210@pytest.fixture(scope=SERVER_SCOPE)

Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360

lines 211–212why, one step back
211def cert_private_key_file(localhost_cert):
212 with localhost_cert.private_key_pem.tempfile() as tmp:

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

lines 213–216why, one step back
213 yield tmp
214215216@pytest.fixture(scope=SERVER_SCOPE)

Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360

lines 217–229why, one step back
217def cert_encrypted_private_key_file(localhost_cert):
218 # Deserialize the private key and then reserialize with a password219 private_key = load_pem_private_key(220 localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()221 )222 encrypted_private_key_pem = trustme.Blob(223 private_key.private_bytes(224 Encoding.PEM,225 PrivateFormat.TraditionalOpenSSL,226 BestAvailableEncryption(password=b"password"),227 )228 )229 with encrypted_private_key_pem.tempfile() as tmp:

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

lines 230–280why, one step back
230 yield tmp
231232233class TestServer(Server):234 @property235 def url(self) -> URL:236 protocol = "https" if self.config.is_ssl else "http"237 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")238239 def install_signal_handlers(self) -> None:240 # Disable the default installation of handlers for signals such as SIGTERM,241 # because it can only be done in the main thread.242 pass243244 async def serve(self, sockets=None):245 self.restart_requested = asyncio.Event()246247 loop = asyncio.get_event_loop()248 tasks = {249 loop.create_task(super().serve(sockets=sockets)),250 loop.create_task(self.watch_restarts()),251 }252 await asyncio.wait(tasks)253254 async def restart(self) -> None:255 # Ensure we are in an asyncio environment.256 assert asyncio.get_event_loop() is not None257 # This may be called from a different thread than the one the server is258 # running on. For this reason, we use an event to coordinate with the server259 # instead of calling shutdown()/startup() directly.260 self.restart_requested.set()261 self.started = False262 while not self.started:263 await asyncio.sleep(0.5)264265 async def watch_restarts(self):266 while True:267 if self.should_exit:268 return269270 try:271 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)272 except asyncio.TimeoutError:273 continue274275 self.restart_requested.clear()276 await self.shutdown()277 await self.startup()278279280@pytest.fixture

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

line 281why, one step back
281def restart():

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

lines 282–286why, one step back
282 """Restart the running server from an async test function.
283284 This fixture deals with possible differences between the environment of the285 test function and that of the server.286 """

Refactor tests in the light of backend auto-detection (#615)Florimond Mancabefore adoptionab41a5d

line 287why, one step back
287 asyncio_backend = AsyncioBackend()

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

lines 288–289why, one step back
288
289 async def restart(server):

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

lines 290–291why, one step back
290 backend = lookup_backend()
291 await backend.run_in_threadpool(asyncio_backend.run, server.restart)

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

lines 292–315why, one step back
292
293 return restart294295296def serve_in_thread(server: Server):297 thread = threading.Thread(target=server.run)298 thread.start()299 try:300 while not server.started:301 time.sleep(1e-3)302 yield server303 finally:304 server.should_exit = True305 thread.join()306307308@pytest.fixture(scope=SERVER_SCOPE)309def server():310 config = Config(app=app, lifespan="off", loop="asyncio")311 server = TestServer(config=config)312 yield from serve_in_thread(server)313314315@pytest.fixture(scope=SERVER_SCOPE)

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

lines 316–324why, one step back
316def uds_server():
317 uds = "test_server.sock"318 config = Config(app=app, lifespan="off", loop="asyncio", uds=uds)319 server = TestServer(config=config)320 yield from serve_in_thread(server)321 os.remove(uds)322323324@pytest.fixture(scope=SERVER_SCOPE)

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

lines 325–330why, one step back
325def https_server(cert_pem_file, cert_private_key_file):
326 config = Config(327 app=app,328 lifespan="off",329 ssl_certfile=cert_pem_file,330 ssl_keyfile=cert_private_key_file,

Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360

line 331why, one step back
331 host="localhost",

Document digest auth (#348)Yeray Diaz Diazbefore adoption8155352

lines 332–336why, one step back
332 port=8001,
333 loop="asyncio",334 )335 server = TestServer(config=config)336 yield from serve_in_thread(server)

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

lines 337–352why, one step back
337
338339@pytest.fixture(scope=SERVER_SCOPE)340def https_uds_server(cert_pem_file, cert_private_key_file):341 uds = "https_test_server.sock"342 config = Config(343 app=app,344 lifespan="off",345 ssl_certfile=cert_pem_file,346 ssl_keyfile=cert_private_key_file,347 uds=uds,348 loop="asyncio",349 )350 server = TestServer(config=config)351 yield from serve_in_thread(server)352 os.remove(uds)