Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

337 lines · 9.2 KiB · Python

Last changed by

Tighten up top-level API to only expose public API (#608)Tom Christiebefore adoptiond15dc0b

History of this file

Take it

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

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

line 1why, one step back
1import asyncio

Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac

line 2why, one step back
2import json

Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a

line 3why, one step back
3import os

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

lines 4–5why, one step back
4import threading
5import time

Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a

line 6why, one step back
6import typing

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

lines 7–9why, one step back
7
8import 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

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

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,

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

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

lines 20–21why, one step back
20from httpx import URL
21from httpx.concurrency.asyncio import AsyncioBackend

Don't check trio import in definition of backend fixture params (#447)Florimond Mancabefore adoptionfc3df51

line 22why, one step back
22from httpx.concurrency.trio import TrioBackend

Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a

line 23why, one step back
23

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

line 24why, one step back
24ENVIRONMENT_VARIABLES = {

Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a

line 25why, one step back
25 "SSL_CERT_FILE",

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

line 26why, one step back
26 "SSL_CERT_DIR",

Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a

lines 27–31why, one step back
27 "HTTP_PROXY",
28 "HTTPS_PROXY",29 "ALL_PROXY",30 "NO_PROXY",31 "SSLKEYLOGFILE",

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

line 32why, one step back
32}

Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a

lines 33–38why, one step back
33
3435@pytest.fixture(scope="function", autouse=True)36def clean_environ() -> typing.Dict[str, typing.Any]:37 """Keeps os.environ clean for every test without having to mock os.environ"""38 original_environ = os.environ.copy()

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 39–46why, one step back
39 os.environ.clear()
40 os.environ.update(41 {42 k: v43 for k, v in original_environ.items()44 if k not in ENVIRONMENT_VARIABLES and k.lower() not in ENVIRONMENT_VARIABLES45 }46 )

Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a

lines 47–49why, one step back
47 yield
48 os.environ.clear()49 os.environ.update(original_environ)

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

line 50why, one step back
50

Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058

line 51why, one step back
51

Don't check trio import in definition of backend fixture params (#447)Florimond Mancabefore adoptionfc3df51

lines 52–57why, one step back
52@pytest.fixture(
53 params=[54 pytest.param(AsyncioBackend, marks=pytest.mark.asyncio),55 pytest.param(TrioBackend, marks=pytest.mark.trio),56 ]57)

Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058

lines 58–62why, one step back
58def backend(request):
59 backend_cls = request.param60 return backend_cls()6162

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

lines 63–64why, one step back
63async def app(scope, receive, send):
64 assert scope["type"] == "http"

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

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

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

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

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

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

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

lines 69–72why, one step back
69 elif scope["path"].startswith("/status"):
70 await status_code(scope, receive, send)71 elif scope["path"].startswith("/echo_body"):72 await echo_body(scope, receive, send)

Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac

lines 73–74why, one step back
73 elif scope["path"].startswith("/echo_headers"):
74 await echo_headers(scope, receive, send)

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

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

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

lines 77–92why, one step back
77 else:
78 await hello_world(scope, receive, send)798081async def hello_world(scope, receive, send):82 await send(83 {84 "type": "http.response.start",85 "status": 200,86 "headers": [[b"content-type", b"text/plain"]],87 }88 )89 await send({"type": "http.response.body", "body": b"Hello, world!"})909192async def slow_response(scope, receive, send):

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

lines 93–98why, one step back
93 delay_ms_str: str = scope["path"].replace("/slow_response/", "")
94 try:95 delay_ms = float(delay_ms_str)96 except ValueError:97 delay_ms = 10098 await asyncio.sleep(delay_ms / 1000.0)

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

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

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

lines 107–116why, one step back
107
108109async def premature_close(scope, receive, send):110 await send(111 {112 "type": "http.response.start",113 "status": 200,114 "headers": [[b"content-type", b"text/plain"]],115 }116 )

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

lines 117–147why, one step back
117
118119async def status_code(scope, receive, send):120 status_code = int(scope["path"].replace("/status/", ""))121 await send(122 {123 "type": "http.response.start",124 "status": status_code,125 "headers": [[b"content-type", b"text/plain"]],126 }127 )128 await send({"type": "http.response.body", "body": b"Hello, world!"})129130131async def echo_body(scope, receive, send):132 body = b""133 more_body = True134135 while more_body:136 message = await receive()137 body += message.get("body", b"")138 more_body = message.get("more_body", False)139140 await send(141 {142 "type": "http.response.start",143 "status": 200,144 "headers": [[b"content-type", b"text/plain"]],145 }146 )147 await send({"type": "http.response.body", "body": body})

Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac

lines 148–162why, one step back
148
149150async def echo_headers(scope, receive, send):151 body = {}152 for name, value in scope.get("headers", []):153 body[name.capitalize().decode()] = value.decode()154155 await send(156 {157 "type": "http.response.start",158 "status": 200,159 "headers": [[b"content-type", b"application/json"]],160 }161 )162 await send({"type": "http.response.body", "body": json.dumps(body).encode()})

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

lines 163–166why, one step back
163
164165async def redirect_301(scope, receive, send):166 await send(

Drop sync (#544)Tom Christiebefore adoption206c537

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

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

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

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

lines 170–171why, one step back
170
171

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

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

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

lines 173–174why, one step back
173
174

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

lines 175–177why, one step back
175@pytest.fixture(scope=SERVER_SCOPE)
176def cert_authority():177 return trustme.CA()

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

line 178why, one step back
178

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

line 179why, one step back
179

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

lines 180–183why, one step back
180@pytest.fixture(scope=SERVER_SCOPE)
181def ca_cert_pem_file(cert_authority):182 with cert_authority.cert_pem.tempfile() as tmp:183 yield tmp

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

line 184why, one step back
184

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

line 185why, one step back
185

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

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

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

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

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

lines 189–190why, one step back
189
190

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

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

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

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

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

lines 194–196why, one step back
194 yield tmp
195196

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

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

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

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

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

lines 200–202why, one step back
200 yield tmp
201202

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

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

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

lines 204–216why, one step back
204def cert_encrypted_private_key_file(localhost_cert):
205 # Deserialize the private key and then reserialize with a password206 private_key = load_pem_private_key(207 localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()208 )209 encrypted_private_key_pem = trustme.Blob(210 private_key.private_bytes(211 Encoding.PEM,212 PrivateFormat.TraditionalOpenSSL,213 BestAvailableEncryption(password=b"password"),214 )215 )216 with encrypted_private_key_pem.tempfile() as tmp:

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

lines 217–219why, one step back
217 yield tmp
218219

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

line 220why, one step back
220class TestServer(Server):

Add server.url property in tests (#300)Bakhtiyor Ruzievbefore adoptione34d280

lines 221–225why, one step back
221 @property
222 def url(self) -> URL:223 protocol = "https" if self.config.is_ssl else "http"224 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")225

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

lines 226–266why, one step back
226 def install_signal_handlers(self) -> None:
227 # Disable the default installation of handlers for signals such as SIGTERM,228 # because it can only be done in the main thread.229 pass230231 async def serve(self, sockets=None):232 self.restart_requested = asyncio.Event()233234 loop = asyncio.get_event_loop()235 tasks = {236 loop.create_task(super().serve(sockets=sockets)),237 loop.create_task(self.watch_restarts()),238 }239 await asyncio.wait(tasks)240241 async def restart(self) -> None:242 # Ensure we are in an asyncio environment.243 assert asyncio.get_event_loop() is not None244 # This may be called from a different thread than the one the server is245 # running on. For this reason, we use an event to coordinate with the server246 # instead of calling shutdown()/startup() directly.247 self.restart_requested.set()248 self.started = False249 while not self.started:250 await asyncio.sleep(0.5)251252 async def watch_restarts(self):253 while True:254 if self.should_exit:255 return256257 try:258 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)259 except asyncio.TimeoutError:260 continue261262 self.restart_requested.clear()263 await self.shutdown()264 await self.startup()265266

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

line 267why, one step back
267@pytest.fixture

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

lines 268–283why, one step back
268def restart(backend):
269 """Restart the running server from an async test function.270271 This fixture deals with possible differences between the environment of the272 test function and that of the server.273 """274275 async def restart(server):276 await backend.run_in_threadpool(AsyncioBackend().run, server.restart)277278 return restart279280281def serve_in_thread(server: Server):282 thread = threading.Thread(target=server.run)283 thread.start()

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

lines 284–285why, one step back
284 try:
285 while not server.started:

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

line 286why, one step back
286 time.sleep(1e-3)

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

lines 287–289why, one step back
287 yield server
288 finally:289 server.should_exit = True

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

line 290why, one step back
290 thread.join()

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

lines 291–292why, one step back
291
292

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

lines 293–300why, one step back
293@pytest.fixture(scope=SERVER_SCOPE)
294def server():295 config = Config(app=app, lifespan="off", loop="asyncio")296 server = TestServer(config=config)297 yield from serve_in_thread(server)298299300@pytest.fixture(scope=SERVER_SCOPE)

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

lines 301–309why, one step back
301def uds_server():
302 uds = "test_server.sock"303 config = Config(app=app, lifespan="off", loop="asyncio", uds=uds)304 server = TestServer(config=config)305 yield from serve_in_thread(server)306 os.remove(uds)307308309@pytest.fixture(scope=SERVER_SCOPE)

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

line 310why, one step back
310def https_server(cert_pem_file, cert_private_key_file):

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

lines 311–315why, one step back
311 config = Config(
312 app=app,313 lifespan="off",314 ssl_certfile=cert_pem_file,315 ssl_keyfile=cert_private_key_file,

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

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

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

line 317why, one step back
317 port=8001,

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

line 318why, one step back
318 loop="asyncio",

Added links property to BaseResponse (#211)euri10before adoptioncad9c03

line 319why, one step back
319 )

Serve test server in thread (#292)Florimond Mancabefore adoption994403b

lines 320–321why, one step back
320 server = TestServer(config=config)
321 yield from serve_in_thread(server)

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

lines 322–337why, one step back
322
323324@pytest.fixture(scope=SERVER_SCOPE)325def https_uds_server(cert_pem_file, cert_private_key_file):326 uds = "https_test_server.sock"327 config = Config(328 app=app,329 lifespan="off",330 ssl_certfile=cert_pem_file,331 ssl_keyfile=cert_private_key_file,332 uds=uds,333 loop="asyncio",334 )335 server = TestServer(config=config)336 yield from serve_in_thread(server)337 os.remove(uds)