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 fileTake 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 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 typingUse urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8
lines 7–9why, one step back78import pytest9import 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)Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8
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, AsyncioBackendDon't check trio import in definition of backend fixture params (#447)Florimond Mancabefore adoptionfc3df51
line 21why, one step back21from httpx.concurrency.trio import TrioBackendAdd os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
line 22why, one step back22Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
line 23why, one step back23ENVIRONMENT_VARIABLES = {Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
line 24why, one step back24 "SSL_CERT_FILE",Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
line 25why, one step back25 "SSL_CERT_DIR",Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
lines 26–30why, one step back26 "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 back31}Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
lines 32–37why, one step back323334@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 back38 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 back46 yield47 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 back49Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 50why, one step back50Don't check trio import in definition of backend fixture params (#447)Florimond Mancabefore adoptionfc3df51
lines 51–56why, one step back51@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 back57def backend(request):58 backend_cls = request.param59 return backend_cls()6061Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8
lines 62–63why, one step back62async 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 back64 if scope["path"].startswith("/slow_response"):Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8
lines 65–69why, one step back65 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 back70 elif scope["path"].startswith("/echo_headers"):71 await echo_headers(scope, receive, send)Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8
lines 72–87why, one step back72 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 back88 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)Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8
lines 94–132why, one step back94 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 back133134135async 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()})Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8
lines 148–149why, one step back148149Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
line 150why, one step back150SERVER_SCOPE = "session"Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 151–152why, one step back151152Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 153–155why, one step back153@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 back156Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 157why, one step back157Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 158–161why, one step back158@pytest.fixture(scope=SERVER_SCOPE)159def ca_cert_pem_file(cert_authority):160 with cert_authority.cert_pem.tempfile() as tmp:161 yield tmpServe test server in thread (#292)Florimond Mancabefore adoption994403b
line 162why, one step back162Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
line 163why, one step back163Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 164why, one step back164@pytest.fixture(scope=SERVER_SCOPE)Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 165–166why, one step back165def localhost_cert(cert_authority):166 return cert_authority.issue_cert("localhost")Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8
lines 167–168why, one step back167168Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 169why, one step back169@pytest.fixture(scope=SERVER_SCOPE)Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 170–171why, one step back170def 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 back172 yield tmp173174Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 175why, one step back175@pytest.fixture(scope=SERVER_SCOPE)Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 176–177why, one step back176def 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 back178 yield tmp179180Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 181why, one step back181@pytest.fixture(scope=SERVER_SCOPE)Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 182–194why, one step back182def 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 back195 yield tmp196197Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 198why, one step back198class TestServer(Server):Add server.url property in tests (#300)Bakhtiyor Ruzievbefore adoptione34d280
lines 199–203why, one step back199 @property200 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}/")203Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 204–244why, one step back204 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()243244Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
line 245why, one step back245@pytest.fixtureServe test server in thread (#292)Florimond Mancabefore adoption994403b
lines 246–261why, one step back246def 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()Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8
lines 262–263why, one step back262 try:263 while not server.started:Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 264why, one step back264 time.sleep(1e-3)Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8
lines 265–267why, one step back265 yield server266 finally:267 server.should_exit = TrueServe test server in thread (#292)Florimond Mancabefore adoption994403b
line 268why, one step back268 thread.join()Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8
lines 269–270why, one step back269270Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 271–279why, one step back271@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):Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8
line 280why, one step back280 config = Config(Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 281–284why, one step back281 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 back285 host="localhost",Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
line 286why, one step back286 port=8001,Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 287why, one step back287 loop="asyncio",Use urllib3's DEFAULT_CIPHERS for ssl config (#100)Tom Christiebefore adoption9930de8
line 288why, one step back288 )Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 289–290why, one step back289 server = TestServer(config=config)290 yield from serve_in_thread(server)