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 fileTake it
The walk stopped after 200 commits: lines older than f1b10e5 point at it.
Minor docstring tweakTom Christiebefore adoptionf1b10e5
line 1why, one step back1import asyncioAdd `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac
line 2why, one step back2import jsonAdd os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
line 3why, one step back3import osServe test server in thread (#292)Florimond Mancabefore adoption994403b
lines 4–5why, one step back4import threading5import timeAdd os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
line 6why, one step back6import typingMinor docstring tweakTom Christiebefore adoptionf1b10e5
lines 7–8why, one step back78import pytestMerge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
line 9why, one step back9import trustmeUse a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
line 10why, one step back10from cryptography.hazmat.backends import default_backendSupport client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 11–14why, one step back11from cryptography.hazmat.primitives.serialization import (12 BestAvailableEncryption,13 Encoding,14 PrivateFormat,Configure Proxy from Client (#353)Seth Michael Larsonbefore adoptionb0fa085
line 15why, one step back15 load_pem_private_key,Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
line 16why, one step back16)Minor docstring tweakTom Christiebefore adoptionf1b10e5
lines 17–19why, one step back17from uvicorn.config import Config18from uvicorn.main import Server19Add server.url property in tests (#300)Bakhtiyor Ruzievbefore adoptione34d280
line 20why, one step back20from httpx import URL, AsyncioBackendAdd os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
line 21why, one step back21Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
line 22why, one step back22ENVIRONMENT_VARIABLES = {Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
line 23why, one step back23 "SSL_CERT_FILE",Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
line 24why, one step back24 "SSL_CERT_DIR",Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
lines 25–29why, one step back25 "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 back30}Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
lines 31–36why, one step back313233@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 back37 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 back45 yield46 os.environ.clear()47 os.environ.update(original_environ)Minor docstring tweakTom Christiebefore adoptionf1b10e5
line 48why, one step back48Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 49why, one step back49Add trio concurrency backend (#276)Florimond Mancabefore adoption08355c6
lines 50–60why, one step back50backend_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 back61def backend(request):62 backend_cls = request.param63 return backend_cls()6465Minor docstring tweakTom Christiebefore adoptionf1b10e5
lines 66–67why, one step back66async 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 back68 if scope["path"].startswith("/slow_response"):Minor docstring tweakTom Christiebefore adoptionf1b10e5
lines 69–71why, one step back69 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 back72 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 back74 elif scope["path"].startswith("/echo_headers"):75 await echo_headers(scope, receive, send)Minor docstring tweakTom Christiebefore adoptionf1b10e5
lines 76–91why, one step back76 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 back92 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 back98 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 back118119120async def echo_body(scope, receive, send):Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 121why, one step back121 body = b""Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0
lines 122–125why, one step back122 more_body = True123124 while more_body:125 message = await receive()Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
lines 126–127why, one step back126 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 back128129 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 back137138139async 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 back152153Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
line 154why, one step back154SERVER_SCOPE = "session"Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 155–156why, one step back155156Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 157–159why, one step back157@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 back160Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 161why, one step back161Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 162–165why, one step back162@pytest.fixture(scope=SERVER_SCOPE)163def ca_cert_pem_file(cert_authority):164 with cert_authority.cert_pem.tempfile() as tmp:165 yield tmpServe test server in thread (#292)Florimond Mancabefore adoption994403b
line 166why, one step back166Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
line 167why, one step back167Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 168why, one step back168@pytest.fixture(scope=SERVER_SCOPE)Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 169–170why, one step back169def 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 back171172Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 173why, one step back173@pytest.fixture(scope=SERVER_SCOPE)Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 174–175why, one step back174def 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 back176 yield tmp177178Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 179why, one step back179@pytest.fixture(scope=SERVER_SCOPE)Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 180–181why, one step back180def 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 back182 yield tmp183184Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 185why, one step back185@pytest.fixture(scope=SERVER_SCOPE)Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 186–198why, one step back186def 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 back199 yield tmp200201Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 202why, one step back202class TestServer(Server):Add server.url property in tests (#300)Bakhtiyor Ruzievbefore adoptione34d280
lines 203–207why, one step back203 @property204 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}/")207Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 208–248why, one step back208 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()247248Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
line 249why, one step back249@pytest.fixtureServe test server in thread (#292)Florimond Mancabefore adoption994403b
lines 250–265why, one step back250def 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 back266 try:267 while not server.started:Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 268why, one step back268 time.sleep(1e-3)Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
lines 269–271why, one step back269 yield server270 finally:271 server.should_exit = TrueServe test server in thread (#292)Florimond Mancabefore adoption994403b
line 272why, one step back272 thread.join()Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
lines 273–274why, one step back273274Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 275–283why, one step back275@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 back284 config = Config(Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 285–288why, one step back285 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 back289 host="localhost",Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
line 290why, one step back290 port=8001,Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 291why, one step back291 loop="asyncio",Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8
line 292why, one step back292 )Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 293–294why, one step back293 server = TestServer(config=config)294 yield from serve_in_thread(server)