Skip to content
Myr

conftest.py

This file

Path

tests/conftest.py

272 lines · 7.3 KiB · Python

Last changed by

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

History of this file

Take it

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

Merge pull request #59 from encode/use-stdlib-status-codesTom Christiebefore adoptionafc8369

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

Merge pull request #59 from encode/use-stdlib-status-codesTom Christiebefore adoptionafc8369

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

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

lines 10–14why, one step back
10from cryptography.hazmat.primitives.serialization import (
11 BestAvailableEncryption,12 Encoding,13 PrivateFormat,14)

Merge pull request #59 from encode/use-stdlib-status-codesTom Christiebefore adoptionafc8369

lines 15–17why, one step back
15from uvicorn.config import Config
16from uvicorn.main import Server17

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

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

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

line 19why, one step back
19

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

line 20why, one step back
20ENVIRONMENT_VARIABLES = {

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

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

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

line 28why, one step back
28}

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

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

Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca

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

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

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

Merge pull request #59 from encode/use-stdlib-status-codesTom Christiebefore adoptionafc8369

line 46why, one step back
46

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

lines 47–53why, one step back
47
48@pytest.fixture(params=[pytest.param(AsyncioBackend, marks=pytest.mark.asyncio)])49def backend(request):50 backend_cls = request.param51 return backend_cls()5253

Merge pull request #59 from encode/use-stdlib-status-codesTom Christiebefore adoptionafc8369

lines 54–59why, one step back
54async def app(scope, receive, send):
55 assert scope["type"] == "http"56 if scope["path"] == "/slow_response":57 await slow_response(scope, receive, send)58 elif scope["path"].startswith("/status"):59 await status_code(scope, receive, send)

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

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

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

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

Merge pull request #59 from encode/use-stdlib-status-codesTom Christiebefore adoptionafc8369

lines 64–79why, one step back
64 else:
65 await hello_world(scope, receive, send)666768async def hello_world(scope, receive, send):69 await send(70 {71 "type": "http.response.start",72 "status": 200,73 "headers": [[b"content-type", b"text/plain"]],74 }75 )76 await send({"type": "http.response.body", "body": b"Hello, world!"})777879async def slow_response(scope, receive, send):

Version 0.6.4 (#105)Tom Christiebefore adoption5326cd1

line 80why, one step back
80 await asyncio.sleep(0.1)

Merge pull request #59 from encode/use-stdlib-status-codesTom Christiebefore adoptionafc8369

lines 81–100why, one step back
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 status_code(scope, receive, send):92 status_code = int(scope["path"].replace("/status/", ""))93 await send(94 {95 "type": "http.response.start",96 "status": status_code,97 "headers": [[b"content-type", b"text/plain"]],98 }99 )100 await send({"type": "http.response.body", "body": b"Hello, world!"})

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

lines 101–103why, one step back
101
102103async def echo_body(scope, receive, send):

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

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

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

lines 105–108why, one step back
105 more_body = True
106107 while more_body:108 message = await receive()

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

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

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

lines 111–119why, one step back
111
112 await send(113 {114 "type": "http.response.start",115 "status": 200,116 "headers": [[b"content-type", b"text/plain"]],117 }118 )119 await send({"type": "http.response.body", "body": body})

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

lines 120–134why, one step back
120
121122async def echo_headers(scope, receive, send):123 body = {}124 for name, value in scope.get("headers", []):125 body[name.capitalize().decode()] = value.decode()126127 await send(128 {129 "type": "http.response.start",130 "status": 200,131 "headers": [[b"content-type", b"application/json"]],132 }133 )134 await send({"type": "http.response.body", "body": json.dumps(body).encode()})

Merge pull request #59 from encode/use-stdlib-status-codesTom Christiebefore adoptionafc8369

lines 135–136why, one step back
135
136

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

lines 137–152why, one step back
137class CAWithPKEncryption(trustme.CA):
138 """Implementation of trustme.CA() that can emit139 private keys that are encrypted with a password.140 """141142 @property143 def encrypted_private_key_pem(self):144 return trustme.Blob(145 self._private_key.private_bytes(146 Encoding.PEM,147 PrivateFormat.TraditionalOpenSSL,148 BestAvailableEncryption(password=b"password"),149 )150 )151152

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

lines 153–156why, one step back
153SERVER_SCOPE = "session"
154155156@pytest.fixture(scope=SERVER_SCOPE)

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

lines 157–158why, one step back
157def example_cert():
158 ca = CAWithPKEncryption()

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

line 159why, one step back
159 ca.issue_cert("example.org")

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

line 160why, one step back
160 return ca

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

lines 161–162why, one step back
161
162

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

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

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

lines 164–168why, one step back
164def cert_pem_file(example_cert):
165 with example_cert.cert_pem.tempfile() as tmp:166 yield tmp167168

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

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

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

lines 170–174why, one step back
170def cert_private_key_file(example_cert):
171 with example_cert.private_key_pem.tempfile() as tmp:172 yield tmp173174

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

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

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

lines 176–180why, one step back
176def cert_encrypted_private_key_file(example_cert):
177 with example_cert.encrypted_private_key_pem.tempfile() as tmp:178 yield tmp179180

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

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

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

lines 182–186why, one step back
182 @property
183 def url(self) -> URL:184 protocol = "https" if self.config.is_ssl else "http"185 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")186

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

lines 187–227why, one step back
187 def install_signal_handlers(self) -> None:
188 # Disable the default installation of handlers for signals such as SIGTERM,189 # because it can only be done in the main thread.190 pass191192 async def serve(self, sockets=None):193 self.restart_requested = asyncio.Event()194195 loop = asyncio.get_event_loop()196 tasks = {197 loop.create_task(super().serve(sockets=sockets)),198 loop.create_task(self.watch_restarts()),199 }200 await asyncio.wait(tasks)201202 async def restart(self) -> None:203 # Ensure we are in an asyncio environment.204 assert asyncio.get_event_loop() is not None205 # This may be called from a different thread than the one the server is206 # running on. For this reason, we use an event to coordinate with the server207 # instead of calling shutdown()/startup() directly.208 self.restart_requested.set()209 self.started = False210 while not self.started:211 await asyncio.sleep(0.5)212213 async def watch_restarts(self):214 while True:215 if self.should_exit:216 return217218 try:219 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)220 except asyncio.TimeoutError:221 continue222223 self.restart_requested.clear()224 await self.shutdown()225 await self.startup()226227

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

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

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

lines 229–244why, one step back
229def restart(backend):
230 """Restart the running server from an async test function.231232 This fixture deals with possible differences between the environment of the233 test function and that of the server.234 """235236 async def restart(server):237 await backend.run_in_threadpool(AsyncioBackend().run, server.restart)238239 return restart240241242def serve_in_thread(server: Server):243 thread = threading.Thread(target=server.run)244 thread.start()

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

lines 245–246why, one step back
245 try:
246 while not server.started:

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

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

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

lines 248–250why, one step back
248 yield server
249 finally:250 server.should_exit = True

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

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

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

lines 252–253why, one step back
252
253

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

lines 254–262why, one step back
254@pytest.fixture(scope=SERVER_SCOPE)
255def server():256 config = Config(app=app, lifespan="off", loop="asyncio")257 server = TestServer(config=config)258 yield from serve_in_thread(server)259260261@pytest.fixture(scope=SERVER_SCOPE)262def https_server(cert_pem_file, cert_private_key_file):

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

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

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

lines 264–268why, one step back
264 app=app,
265 lifespan="off",266 ssl_certfile=cert_pem_file,267 ssl_keyfile=cert_private_key_file,268 port=8001,

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

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

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

line 270why, one step back
270 )

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

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