Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

294 lines · 8.0 KiB · Python

Last changed by

Add trio concurrency backend (#276)Florimond Mancabefore adoption08355c6

History of this file

Take it

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

Minor docstring tweakTom Christiebefore adoptionf1b10e5

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

Minor docstring tweakTom Christiebefore adoptionf1b10e5

lines 7–8why, one step back
7
8import pytest

Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635

line 9why, one step back
9import 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)

Minor docstring tweakTom Christiebefore adoptionf1b10e5

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

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

line 21why, one step back
21

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

line 22why, one step back
22ENVIRONMENT_VARIABLES = {

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

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

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

line 30why, one step back
30}

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

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

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

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

Minor docstring tweakTom Christiebefore adoptionf1b10e5

line 48why, one step back
48

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

line 49why, one step back
49

Add trio concurrency backend (#276)Florimond Mancabefore adoption08355c6

lines 50–60why, one step back
50backend_params = [pytest.param(AsyncioBackend, marks=pytest.mark.asyncio)]
5152try:53 from httpx.concurrency.trio import TrioBackend54except ImportError: # pragma: no cover55 pass56else:57 backend_params.append(pytest.param(TrioBackend, marks=pytest.mark.trio))585960@pytest.fixture(params=backend_params)

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

lines 61–65why, one step back
61def backend(request):
62 backend_cls = request.param63 return backend_cls()6465

Minor docstring tweakTom Christiebefore adoptionf1b10e5

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

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

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

Minor docstring tweakTom Christiebefore adoptionf1b10e5

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

Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0

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

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

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

Minor docstring tweakTom Christiebefore adoptionf1b10e5

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

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

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

Minor docstring tweakTom Christiebefore adoptionf1b10e5

lines 98–117why, one step back
98 await send(
99 {100 "type": "http.response.start",101 "status": 200,102 "headers": [[b"content-type", b"text/plain"]],103 }104 )105 await send({"type": "http.response.body", "body": b"Hello, world!"})106107108async def status_code(scope, receive, send):109 status_code = int(scope["path"].replace("/status/", ""))110 await send(111 {112 "type": "http.response.start",113 "status": status_code,114 "headers": [[b"content-type", b"text/plain"]],115 }116 )117 await send({"type": "http.response.body", "body": b"Hello, world!"})

Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0

lines 118–120why, one step back
118
119120async def echo_body(scope, receive, send):

Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885

line 121why, one step back
121 body = b""

Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0

lines 122–125why, one step back
122 more_body = True
123124 while more_body:125 message = await receive()

Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885

lines 126–127why, one step back
126 body += message.get("body", b"")
127 more_body = message.get("more_body", False)

Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0

lines 128–136why, one step back
128
129 await send(130 {131 "type": "http.response.start",132 "status": 200,133 "headers": [[b"content-type", b"text/plain"]],134 }135 )136 await send({"type": "http.response.body", "body": body})

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

lines 137–151why, one step back
137
138139async def echo_headers(scope, receive, send):140 body = {}141 for name, value in scope.get("headers", []):142 body[name.capitalize().decode()] = value.decode()143144 await send(145 {146 "type": "http.response.start",147 "status": 200,148 "headers": [[b"content-type", b"application/json"]],149 }150 )151 await send({"type": "http.response.body", "body": json.dumps(body).encode()})

Minor docstring tweakTom Christiebefore adoptionf1b10e5

lines 152–153why, one step back
152
153

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

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

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

lines 155–156why, one step back
155
156

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

lines 157–159why, one step back
157@pytest.fixture(scope=SERVER_SCOPE)
158def cert_authority():159 return trustme.CA()

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

line 160why, one step back
160

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

line 161why, one step back
161

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

lines 162–165why, one step back
162@pytest.fixture(scope=SERVER_SCOPE)
163def ca_cert_pem_file(cert_authority):164 with cert_authority.cert_pem.tempfile() as tmp:165 yield tmp

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

line 166why, one step back
166

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

line 167why, one step back
167

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

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

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

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

Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8

lines 171–172why, one step back
171
172

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

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

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

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

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

lines 176–178why, one step back
176 yield tmp
177178

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

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

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

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

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

lines 182–184why, one step back
182 yield tmp
183184

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

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

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

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

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

lines 199–201why, one step back
199 yield tmp
200201

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

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

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

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

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

lines 208–248why, one step back
208 def install_signal_handlers(self) -> None:
209 # Disable the default installation of handlers for signals such as SIGTERM,210 # because it can only be done in the main thread.211 pass212213 async def serve(self, sockets=None):214 self.restart_requested = asyncio.Event()215216 loop = asyncio.get_event_loop()217 tasks = {218 loop.create_task(super().serve(sockets=sockets)),219 loop.create_task(self.watch_restarts()),220 }221 await asyncio.wait(tasks)222223 async def restart(self) -> None:224 # Ensure we are in an asyncio environment.225 assert asyncio.get_event_loop() is not None226 # This may be called from a different thread than the one the server is227 # running on. For this reason, we use an event to coordinate with the server228 # instead of calling shutdown()/startup() directly.229 self.restart_requested.set()230 self.started = False231 while not self.started:232 await asyncio.sleep(0.5)233234 async def watch_restarts(self):235 while True:236 if self.should_exit:237 return238239 try:240 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)241 except asyncio.TimeoutError:242 continue243244 self.restart_requested.clear()245 await self.shutdown()246 await self.startup()247248

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

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

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

lines 250–265why, one step back
250def restart(backend):
251 """Restart the running server from an async test function.252253 This fixture deals with possible differences between the environment of the254 test function and that of the server.255 """256257 async def restart(server):258 await backend.run_in_threadpool(AsyncioBackend().run, server.restart)259260 return restart261262263def serve_in_thread(server: Server):264 thread = threading.Thread(target=server.run)265 thread.start()

Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635

lines 266–267why, one step back
266 try:
267 while not server.started:

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

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

Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635

lines 269–271why, one step back
269 yield server
270 finally:271 server.should_exit = True

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

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

Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635

lines 273–274why, one step back
273
274

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

lines 275–283why, one step back
275@pytest.fixture(scope=SERVER_SCOPE)
276def server():277 config = Config(app=app, lifespan="off", loop="asyncio")278 server = TestServer(config=config)279 yield from serve_in_thread(server)280281282@pytest.fixture(scope=SERVER_SCOPE)283def https_server(cert_pem_file, cert_private_key_file):

Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8

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

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

lines 285–288why, one step back
285 app=app,
286 lifespan="off",287 ssl_certfile=cert_pem_file,288 ssl_keyfile=cert_private_key_file,

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

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

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

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

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

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

Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8

line 292why, one step back
292 )

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

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