Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

290 lines · 7.9 KiB · Python

Last changed by

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

History of this file

Take it

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

Version 0.3.1Tom Christiebefore adoptionf4591f0

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

Version 0.3.1Tom Christiebefore adoptionf4591f0

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)

Version 0.3.1Tom Christiebefore adoptionf4591f0

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)

Version 0.3.1Tom Christiebefore adoptionf4591f0

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

Version 0.3.1Tom Christiebefore adoptionf4591f0

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"):

Version 0.3.1Tom Christiebefore adoptionf4591f0

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)

Version 0.3.1Tom Christiebefore adoptionf4591f0

lines 72–87why, one step back
72 else:
73 await hello_world(scope, receive, send)747576async def hello_world(scope, receive, send):77 await send(78 {79 "type": "http.response.start",80 "status": 200,81 "headers": [[b"content-type", b"text/plain"]],82 }83 )84 await send({"type": "http.response.body", "body": b"Hello, world!"})858687async def slow_response(scope, receive, send):

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

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

Version 0.3.1Tom Christiebefore adoptionf4591f0

lines 94–132why, one step back
94 await send(
95 {96 "type": "http.response.start",97 "status": 200,98 "headers": [[b"content-type", b"text/plain"]],99 }100 )101 await send({"type": "http.response.body", "body": b"Hello, world!"})102103104async def status_code(scope, receive, send):105 status_code = int(scope["path"].replace("/status/", ""))106 await send(107 {108 "type": "http.response.start",109 "status": status_code,110 "headers": [[b"content-type", b"text/plain"]],111 }112 )113 await send({"type": "http.response.body", "body": b"Hello, world!"})114115116async def echo_body(scope, receive, send):117 body = b""118 more_body = True119120 while more_body:121 message = await receive()122 body += message.get("body", b"")123 more_body = message.get("more_body", False)124125 await send(126 {127 "type": "http.response.start",128 "status": 200,129 "headers": [[b"content-type", b"text/plain"]],130 }131 )132 await send({"type": "http.response.body", "body": body})

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

lines 133–147why, one step back
133
134135async def echo_headers(scope, receive, send):136 body = {}137 for name, value in scope.get("headers", []):138 body[name.capitalize().decode()] = value.decode()139140 await send(141 {142 "type": "http.response.start",143 "status": 200,144 "headers": [[b"content-type", b"application/json"]],145 }146 )147 await send({"type": "http.response.body", "body": json.dumps(body).encode()})

Version 0.3.1Tom Christiebefore adoptionf4591f0

lines 148–149why, one step back
148
149

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

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

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

lines 151–152why, one step back
151
152

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

lines 153–155why, one step back
153@pytest.fixture(scope=SERVER_SCOPE)
154def cert_authority():155 return trustme.CA()

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

line 156why, one step back
156

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

line 157why, one step back
157

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

lines 158–161why, one step back
158@pytest.fixture(scope=SERVER_SCOPE)
159def ca_cert_pem_file(cert_authority):160 with cert_authority.cert_pem.tempfile() as tmp:161 yield tmp

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

line 162why, one step back
162

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

line 163why, one step back
163

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

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

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

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

Version 0.3.1Tom Christiebefore adoptionf4591f0

lines 167–168why, one step back
167
168

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

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

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

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

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

lines 172–174why, one step back
172 yield tmp
173174

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

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

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

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

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

lines 178–180why, one step back
178 yield tmp
179180

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

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

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

lines 182–194why, one step back
182def cert_encrypted_private_key_file(localhost_cert):
183 # Deserialize the private key and then reserialize with a password184 private_key = load_pem_private_key(185 localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()186 )187 encrypted_private_key_pem = trustme.Blob(188 private_key.private_bytes(189 Encoding.PEM,190 PrivateFormat.TraditionalOpenSSL,191 BestAvailableEncryption(password=b"password"),192 )193 )194 with encrypted_private_key_pem.tempfile() as tmp:

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

lines 195–197why, one step back
195 yield tmp
196197

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

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

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

lines 199–203why, one step back
199 @property
200 def url(self) -> URL:201 protocol = "https" if self.config.is_ssl else "http"202 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")203

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

lines 204–244why, one step back
204 def install_signal_handlers(self) -> None:
205 # Disable the default installation of handlers for signals such as SIGTERM,206 # because it can only be done in the main thread.207 pass208209 async def serve(self, sockets=None):210 self.restart_requested = asyncio.Event()211212 loop = asyncio.get_event_loop()213 tasks = {214 loop.create_task(super().serve(sockets=sockets)),215 loop.create_task(self.watch_restarts()),216 }217 await asyncio.wait(tasks)218219 async def restart(self) -> None:220 # Ensure we are in an asyncio environment.221 assert asyncio.get_event_loop() is not None222 # This may be called from a different thread than the one the server is223 # running on. For this reason, we use an event to coordinate with the server224 # instead of calling shutdown()/startup() directly.225 self.restart_requested.set()226 self.started = False227 while not self.started:228 await asyncio.sleep(0.5)229230 async def watch_restarts(self):231 while True:232 if self.should_exit:233 return234235 try:236 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)237 except asyncio.TimeoutError:238 continue239240 self.restart_requested.clear()241 await self.shutdown()242 await self.startup()243244

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

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

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

lines 246–261why, one step back
246def restart(backend):
247 """Restart the running server from an async test function.248249 This fixture deals with possible differences between the environment of the250 test function and that of the server.251 """252253 async def restart(server):254 await backend.run_in_threadpool(AsyncioBackend().run, server.restart)255256 return restart257258259def serve_in_thread(server: Server):260 thread = threading.Thread(target=server.run)261 thread.start()

Version 0.3.1Tom Christiebefore adoptionf4591f0

lines 262–263why, one step back
262 try:
263 while not server.started:

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

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

Version 0.3.1Tom Christiebefore adoptionf4591f0

lines 265–267why, one step back
265 yield server
266 finally:267 server.should_exit = True

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

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

Version 0.3.1Tom Christiebefore adoptionf4591f0

lines 269–270why, one step back
269
270

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

lines 271–279why, one step back
271@pytest.fixture(scope=SERVER_SCOPE)
272def server():273 config = Config(app=app, lifespan="off", loop="asyncio")274 server = TestServer(config=config)275 yield from serve_in_thread(server)276277278@pytest.fixture(scope=SERVER_SCOPE)279def https_server(cert_pem_file, cert_private_key_file):

Version 0.3.1Tom Christiebefore adoptionf4591f0

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

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

lines 281–284why, one step back
281 app=app,
282 lifespan="off",283 ssl_certfile=cert_pem_file,284 ssl_keyfile=cert_private_key_file,

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

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

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

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

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

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

Version 0.3.1Tom Christiebefore adoptionf4591f0

line 288why, one step back
288 )

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

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