Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

303 lines · 8.2 KiB · Python

Last changed by

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

History of this file

Take it

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

Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8

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

Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8

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

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

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,

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

line 16why, one step back
16)

Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8

lines 17–19why, one step back
17from uvicorn.config import Config
18from uvicorn.main import Server19

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

line 20why, one step back
20from httpx import URL, AsyncioBackend

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

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

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

line 22why, one step back
22

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

line 23why, one step back
23ENVIRONMENT_VARIABLES = {

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

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

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

line 31why, one step back
31}

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

lines 38–45why, one step back
38 os.environ.clear()
39 os.environ.update(40 {41 k: v42 for k, v in original_environ.items()43 if k not in ENVIRONMENT_VARIABLES and k.lower() not in ENVIRONMENT_VARIABLES44 }45 )

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

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

Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8

line 49why, one step back
49

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

line 50why, one step back
50

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

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

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

lines 57–61why, one step back
57def backend(request):
58 backend_cls = request.param59 return backend_cls()6061

Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8

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

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

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

Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8

lines 65–69why, one step back
65 await slow_response(scope, receive, send)
66 elif scope["path"].startswith("/status"):67 await status_code(scope, receive, send)68 elif scope["path"].startswith("/echo_body"):69 await echo_body(scope, receive, send)

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

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

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

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

Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8

lines 74–89why, one step back
74 else:
75 await hello_world(scope, receive, send)767778async def hello_world(scope, receive, send):79 await send(80 {81 "type": "http.response.start",82 "status": 200,83 "headers": [[b"content-type", b"text/plain"]],84 }85 )86 await send({"type": "http.response.body", "body": b"Hello, world!"})878889async def slow_response(scope, receive, send):

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

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

Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8

lines 96–134why, one step back
96 await send(
97 {98 "type": "http.response.start",99 "status": 200,100 "headers": [[b"content-type", b"text/plain"]],101 }102 )103 await send({"type": "http.response.body", "body": b"Hello, world!"})104105106async def status_code(scope, receive, send):107 status_code = int(scope["path"].replace("/status/", ""))108 await send(109 {110 "type": "http.response.start",111 "status": status_code,112 "headers": [[b"content-type", b"text/plain"]],113 }114 )115 await send({"type": "http.response.body", "body": b"Hello, world!"})116117118async def echo_body(scope, receive, send):119 body = b""120 more_body = True121122 while more_body:123 message = await receive()124 body += message.get("body", b"")125 more_body = message.get("more_body", False)126127 await send(128 {129 "type": "http.response.start",130 "status": 200,131 "headers": [[b"content-type", b"text/plain"]],132 }133 )134 await send({"type": "http.response.body", "body": body})

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

lines 135–149why, one step back
135
136137async def echo_headers(scope, receive, send):138 body = {}139 for name, value in scope.get("headers", []):140 body[name.capitalize().decode()] = value.decode()141142 await send(143 {144 "type": "http.response.start",145 "status": 200,146 "headers": [[b"content-type", b"application/json"]],147 }148 )149 await send({"type": "http.response.body", "body": json.dumps(body).encode()})

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

lines 150–160why, one step back
150
151152async def redirect_301(scope, receive, send):153 await send(154 {155 "type": "http.response.start",156 "status": 301,157 "headers": [[b"location", b"/"]],158 }159 )160 await send({"type": "http.response.body"})

Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8

lines 161–162why, one step back
161
162

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

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

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

lines 164–165why, one step back
164
165

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

lines 166–168why, one step back
166@pytest.fixture(scope=SERVER_SCOPE)
167def cert_authority():168 return trustme.CA()

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

line 169why, one step back
169

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

line 170why, one step back
170

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

lines 171–174why, one step back
171@pytest.fixture(scope=SERVER_SCOPE)
172def ca_cert_pem_file(cert_authority):173 with cert_authority.cert_pem.tempfile() as tmp:174 yield tmp

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

line 175why, one step back
175

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

line 176why, one step back
176

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

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

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

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

Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8

lines 180–181why, one step back
180
181

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

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

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

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

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

lines 185–187why, one step back
185 yield tmp
186187

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

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

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

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

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

lines 191–193why, one step back
191 yield tmp
192193

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

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

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

lines 195–207why, one step back
195def cert_encrypted_private_key_file(localhost_cert):
196 # Deserialize the private key and then reserialize with a password197 private_key = load_pem_private_key(198 localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()199 )200 encrypted_private_key_pem = trustme.Blob(201 private_key.private_bytes(202 Encoding.PEM,203 PrivateFormat.TraditionalOpenSSL,204 BestAvailableEncryption(password=b"password"),205 )206 )207 with encrypted_private_key_pem.tempfile() as tmp:

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

lines 208–210why, one step back
208 yield tmp
209210

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

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

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

lines 212–216why, one step back
212 @property
213 def url(self) -> URL:214 protocol = "https" if self.config.is_ssl else "http"215 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")216

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

lines 217–257why, one step back
217 def install_signal_handlers(self) -> None:
218 # Disable the default installation of handlers for signals such as SIGTERM,219 # because it can only be done in the main thread.220 pass221222 async def serve(self, sockets=None):223 self.restart_requested = asyncio.Event()224225 loop = asyncio.get_event_loop()226 tasks = {227 loop.create_task(super().serve(sockets=sockets)),228 loop.create_task(self.watch_restarts()),229 }230 await asyncio.wait(tasks)231232 async def restart(self) -> None:233 # Ensure we are in an asyncio environment.234 assert asyncio.get_event_loop() is not None235 # This may be called from a different thread than the one the server is236 # running on. For this reason, we use an event to coordinate with the server237 # instead of calling shutdown()/startup() directly.238 self.restart_requested.set()239 self.started = False240 while not self.started:241 await asyncio.sleep(0.5)242243 async def watch_restarts(self):244 while True:245 if self.should_exit:246 return247248 try:249 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)250 except asyncio.TimeoutError:251 continue252253 self.restart_requested.clear()254 await self.shutdown()255 await self.startup()256257

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

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

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

lines 259–274why, one step back
259def restart(backend):
260 """Restart the running server from an async test function.261262 This fixture deals with possible differences between the environment of the263 test function and that of the server.264 """265266 async def restart(server):267 await backend.run_in_threadpool(AsyncioBackend().run, server.restart)268269 return restart270271272def serve_in_thread(server: Server):273 thread = threading.Thread(target=server.run)274 thread.start()

Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8

lines 275–276why, one step back
275 try:
276 while not server.started:

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

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

Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8

lines 278–280why, one step back
278 yield server
279 finally:280 server.should_exit = True

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

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

Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8

lines 282–283why, one step back
282
283

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

lines 284–292why, one step back
284@pytest.fixture(scope=SERVER_SCOPE)
285def server():286 config = Config(app=app, lifespan="off", loop="asyncio")287 server = TestServer(config=config)288 yield from serve_in_thread(server)289290291@pytest.fixture(scope=SERVER_SCOPE)292def https_server(cert_pem_file, cert_private_key_file):

Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8

line 293why, one step back
293 config = Config(

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

lines 294–297why, one step back
294 app=app,
295 lifespan="off",296 ssl_certfile=cert_pem_file,297 ssl_keyfile=cert_private_key_file,

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

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

Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29

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

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

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

Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8

line 301why, one step back
301 )

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

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