Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

345 lines · 9.6 KiB · Python

Last changed by

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

History of this file

Take it

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

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,

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

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

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

line 22why, one step back
22from httpx.concurrency.base import lookup_backend

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)

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 50–51why, one step back
50
51

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

lines 52–53why, one step back
52@pytest.fixture(
53 params=[

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

lines 54–60why, one step back
54 # pytest uses the marks to set up the specified async environment and run
55 # 'async def' test functions. The "auto" backend should then auto-detect56 # the environment it's running in.57 # Passing the backend explicitly, e.g. `backend="asyncio"`,58 # is tested separately.59 pytest.param("auto", marks=pytest.mark.asyncio),60 pytest.param("auto", marks=pytest.mark.trio),

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

lines 61–62why, one step back
61 ]
62)

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

line 63why, one step back
63def backend(request):

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

line 64why, one step back
64 return request.param

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

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

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

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

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

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

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

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

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

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

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

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 81–96why, one step back
81 else:
82 await hello_world(scope, receive, send)838485async def hello_world(scope, receive, send):86 await send(87 {88 "type": "http.response.start",89 "status": 200,90 "headers": [[b"content-type", b"text/plain"]],91 }92 )93 await send({"type": "http.response.body", "body": b"Hello, world!"})949596async def slow_response(scope, receive, send):

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

lines 97–102why, one step back
97 delay_ms_str: str = scope["path"].replace("/slow_response/", "")
98 try:99 delay_ms = float(delay_ms_str)100 except ValueError:101 delay_ms = 100102 await asyncio.sleep(delay_ms / 1000.0)

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

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

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

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 121–151why, one step back
121
122123async def status_code(scope, receive, send):124 status_code = int(scope["path"].replace("/status/", ""))125 await send(126 {127 "type": "http.response.start",128 "status": status_code,129 "headers": [[b"content-type", b"text/plain"]],130 }131 )132 await send({"type": "http.response.body", "body": b"Hello, world!"})133134135async def echo_body(scope, receive, send):136 body = b""137 more_body = True138139 while more_body:140 message = await receive()141 body += message.get("body", b"")142 more_body = message.get("more_body", False)143144 await send(145 {146 "type": "http.response.start",147 "status": 200,148 "headers": [[b"content-type", b"text/plain"]],149 }150 )151 await send({"type": "http.response.body", "body": body})

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

lines 152–166why, one step back
152
153154async def echo_headers(scope, receive, send):155 body = {}156 for name, value in scope.get("headers", []):157 body[name.capitalize().decode()] = value.decode()158159 await send(160 {161 "type": "http.response.start",162 "status": 200,163 "headers": [[b"content-type", b"application/json"]],164 }165 )166 await send({"type": "http.response.body", "body": json.dumps(body).encode()})

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

lines 167–170why, one step back
167
168169async def redirect_301(scope, receive, send):170 await send(

Drop sync (#544)Tom Christiebefore adoption206c537

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

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

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 174–175why, one step back
174
175

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

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 177–178why, one step back
177
178

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

lines 179–181why, one step back
179@pytest.fixture(scope=SERVER_SCOPE)
180def cert_authority():181 return trustme.CA()

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

line 182why, one step back
182

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

line 183why, one step back
183

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

lines 184–187why, one step back
184@pytest.fixture(scope=SERVER_SCOPE)
185def ca_cert_pem_file(cert_authority):186 with cert_authority.cert_pem.tempfile() as tmp:187 yield tmp

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

line 188why, one step back
188

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

line 189why, one step back
189

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

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

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

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 193–194why, one step back
193
194

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

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

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

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 198–200why, one step back
198 yield tmp
199200

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

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

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

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 204–206why, one step back
204 yield tmp
205206

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

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

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

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 221–223why, one step back
221 yield tmp
222223

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

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

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

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

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

lines 230–270why, one step back
230 def install_signal_handlers(self) -> None:
231 # Disable the default installation of handlers for signals such as SIGTERM,232 # because it can only be done in the main thread.233 pass234235 async def serve(self, sockets=None):236 self.restart_requested = asyncio.Event()237238 loop = asyncio.get_event_loop()239 tasks = {240 loop.create_task(super().serve(sockets=sockets)),241 loop.create_task(self.watch_restarts()),242 }243 await asyncio.wait(tasks)244245 async def restart(self) -> None:246 # Ensure we are in an asyncio environment.247 assert asyncio.get_event_loop() is not None248 # This may be called from a different thread than the one the server is249 # running on. For this reason, we use an event to coordinate with the server250 # instead of calling shutdown()/startup() directly.251 self.restart_requested.set()252 self.started = False253 while not self.started:254 await asyncio.sleep(0.5)255256 async def watch_restarts(self):257 while True:258 if self.should_exit:259 return260261 try:262 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)263 except asyncio.TimeoutError:264 continue265266 self.restart_requested.clear()267 await self.shutdown()268 await self.startup()269270

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

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

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

lines 272–277why, one step back
272def restart(backend):
273 """Restart the running server from an async test function.274275 This fixture deals with possible differences between the environment of the276 test function and that of the server.277 """

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

lines 278–279why, one step back
278 asyncio_backend = AsyncioBackend()
279 backend_implementation = lookup_backend(backend)

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

lines 280–281why, one step back
280
281 async def restart(server):

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

lines 282–284why, one step back
282 await backend_implementation.run_in_threadpool(
283 asyncio_backend.run, server.restart284 )

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

lines 285–291why, one step back
285
286 return restart287288289def serve_in_thread(server: Server):290 thread = threading.Thread(target=server.run)291 thread.start()

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 292–293why, one step back
292 try:
293 while not server.started:

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

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 295–297why, one step back
295 yield server
296 finally:297 server.should_exit = True

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

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 299–300why, one step back
299
300

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

lines 301–308why, one step back
301@pytest.fixture(scope=SERVER_SCOPE)
302def server():303 config = Config(app=app, lifespan="off", loop="asyncio")304 server = TestServer(config=config)305 yield from serve_in_thread(server)306307308@pytest.fixture(scope=SERVER_SCOPE)

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

lines 309–317why, one step back
309def uds_server():
310 uds = "test_server.sock"311 config = Config(app=app, lifespan="off", loop="asyncio", uds=uds)312 server = TestServer(config=config)313 yield from serve_in_thread(server)314 os.remove(uds)315316317@pytest.fixture(scope=SERVER_SCOPE)

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

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

lines 319–323why, one step back
319 config = Config(
320 app=app,321 lifespan="off",322 ssl_certfile=cert_pem_file,323 ssl_keyfile=cert_private_key_file,

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

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

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

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

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

Automatically convert Client.cookies and Client.headers on set (#274)toppkbefore adoption9e420a5

line 327why, one step back
327 )

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

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

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

lines 330–345why, one step back
330
331332@pytest.fixture(scope=SERVER_SCOPE)333def https_uds_server(cert_pem_file, cert_private_key_file):334 uds = "https_test_server.sock"335 config = Config(336 app=app,337 lifespan="off",338 ssl_certfile=cert_pem_file,339 ssl_keyfile=cert_private_key_file,340 uds=uds,341 loop="asyncio",342 )343 server = TestServer(config=config)344 yield from serve_in_thread(server)345 os.remove(uds)