conftest.py
This file
Path
tests/conftest.py
336 lines · 9.2 KiB · Python
Last changed by
Drop sync (#544)Tom Christiebefore adoption206c537
History of this fileTake it
The walk stopped after 200 commits: lines older than fe1f9ed point at it.
Minor tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed
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 tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed
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)Minor tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed
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)Minor tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed
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()6061Minor tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed
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"):Minor tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed
line 65why, one step back65 await slow_response(scope, receive, send)Handle h11.Connection.next_event() RemoteProtocolError (#524)toppkbefore adoptionf06ca87
lines 66–67why, one step back66 elif scope["path"].startswith("/premature_close"):67 await premature_close(scope, receive, send)Minor tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed
lines 68–71why, one step back68 elif scope["path"].startswith("/status"):69 await status_code(scope, receive, send)70 elif scope["path"].startswith("/echo_body"):71 await echo_body(scope, receive, send)Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac
lines 72–73why, one step back72 elif scope["path"].startswith("/echo_headers"):73 await echo_headers(scope, receive, send)Add DEBUG logs of HTTP requests (#502)Florimond Mancabefore adoption08069e9
lines 74–75why, one step back74 elif scope["path"].startswith("/redirect_301"):75 await redirect_301(scope, receive, send)Minor tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed
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 tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed
lines 98–105why, 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!"})Handle h11.Connection.next_event() RemoteProtocolError (#524)toppkbefore adoptionf06ca87
lines 106–115why, one step back106107108async def premature_close(scope, receive, send):109 await send(110 {111 "type": "http.response.start",112 "status": 200,113 "headers": [[b"content-type", b"text/plain"]],114 }115 )Minor tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed
lines 116–146why, one step back116117118async def status_code(scope, receive, send):119 status_code = int(scope["path"].replace("/status/", ""))120 await send(121 {122 "type": "http.response.start",123 "status": status_code,124 "headers": [[b"content-type", b"text/plain"]],125 }126 )127 await send({"type": "http.response.body", "body": b"Hello, world!"})128129130async def echo_body(scope, receive, send):131 body = b""132 more_body = True133134 while more_body:135 message = await receive()136 body += message.get("body", b"")137 more_body = message.get("more_body", False)138139 await send(140 {141 "type": "http.response.start",142 "status": 200,143 "headers": [[b"content-type", b"text/plain"]],144 }145 )146 await send({"type": "http.response.body", "body": body})Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac
lines 147–161why, one step back147148149async def echo_headers(scope, receive, send):150 body = {}151 for name, value in scope.get("headers", []):152 body[name.capitalize().decode()] = value.decode()153154 await send(155 {156 "type": "http.response.start",157 "status": 200,158 "headers": [[b"content-type", b"application/json"]],159 }160 )161 await send({"type": "http.response.body", "body": json.dumps(body).encode()})Add DEBUG logs of HTTP requests (#502)Florimond Mancabefore adoption08069e9
lines 162–165why, one step back162163164async def redirect_301(scope, receive, send):165 await send(Drop sync (#544)Tom Christiebefore adoption206c537
line 166why, one step back166 {"type": "http.response.start", "status": 301, "headers": [[b"location", b"/"]]}Add DEBUG logs of HTTP requests (#502)Florimond Mancabefore adoption08069e9
lines 167–168why, one step back167 )168 await send({"type": "http.response.body"})Minor tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed
lines 169–170why, one step back169170Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
line 171why, one step back171SERVER_SCOPE = "session"Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 172–173why, one step back172173Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 174–176why, one step back174@pytest.fixture(scope=SERVER_SCOPE)175def cert_authority():176 return trustme.CA()Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
line 177why, one step back177Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 178why, one step back178Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 179–182why, one step back179@pytest.fixture(scope=SERVER_SCOPE)180def ca_cert_pem_file(cert_authority):181 with cert_authority.cert_pem.tempfile() as tmp:182 yield tmpServe test server in thread (#292)Florimond Mancabefore adoption994403b
line 183why, one step back183Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
line 184why, one step back184Serve 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–187why, one step back186def localhost_cert(cert_authority):187 return cert_authority.issue_cert("localhost")Minor tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed
lines 188–189why, one step back188189Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 190why, one step back190@pytest.fixture(scope=SERVER_SCOPE)Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 191–192why, one step back191def cert_pem_file(localhost_cert):192 with localhost_cert.cert_chain_pems[0].tempfile() as tmp:Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 193–195why, one step back193 yield tmp194195Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 196why, one step back196@pytest.fixture(scope=SERVER_SCOPE)Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 197–198why, one step back197def cert_private_key_file(localhost_cert):198 with localhost_cert.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 back202@pytest.fixture(scope=SERVER_SCOPE)Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 203–215why, one step back203def cert_encrypted_private_key_file(localhost_cert):204 # Deserialize the private key and then reserialize with a password205 private_key = load_pem_private_key(206 localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()207 )208 encrypted_private_key_pem = trustme.Blob(209 private_key.private_bytes(210 Encoding.PEM,211 PrivateFormat.TraditionalOpenSSL,212 BestAvailableEncryption(password=b"password"),213 )214 )215 with encrypted_private_key_pem.tempfile() as tmp:Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 216–218why, one step back216 yield tmp217218Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 219why, one step back219class TestServer(Server):Add server.url property in tests (#300)Bakhtiyor Ruzievbefore adoptione34d280
lines 220–224why, one step back220 @property221 def url(self) -> URL:222 protocol = "https" if self.config.is_ssl else "http"223 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")224Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 225–265why, one step back225 def install_signal_handlers(self) -> None:226 # Disable the default installation of handlers for signals such as SIGTERM,227 # because it can only be done in the main thread.228 pass229230 async def serve(self, sockets=None):231 self.restart_requested = asyncio.Event()232233 loop = asyncio.get_event_loop()234 tasks = {235 loop.create_task(super().serve(sockets=sockets)),236 loop.create_task(self.watch_restarts()),237 }238 await asyncio.wait(tasks)239240 async def restart(self) -> None:241 # Ensure we are in an asyncio environment.242 assert asyncio.get_event_loop() is not None243 # This may be called from a different thread than the one the server is244 # running on. For this reason, we use an event to coordinate with the server245 # instead of calling shutdown()/startup() directly.246 self.restart_requested.set()247 self.started = False248 while not self.started:249 await asyncio.sleep(0.5)250251 async def watch_restarts(self):252 while True:253 if self.should_exit:254 return255256 try:257 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)258 except asyncio.TimeoutError:259 continue260261 self.restart_requested.clear()262 await self.shutdown()263 await self.startup()264265Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
line 266why, one step back266@pytest.fixtureServe test server in thread (#292)Florimond Mancabefore adoption994403b
lines 267–282why, one step back267def restart(backend):268 """Restart the running server from an async test function.269270 This fixture deals with possible differences between the environment of the271 test function and that of the server.272 """273274 async def restart(server):275 await backend.run_in_threadpool(AsyncioBackend().run, server.restart)276277 return restart278279280def serve_in_thread(server: Server):281 thread = threading.Thread(target=server.run)282 thread.start()Minor tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed
lines 283–284why, one step back283 try:284 while not server.started:Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 285why, one step back285 time.sleep(1e-3)Minor tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed
lines 286–288why, one step back286 yield server287 finally:288 server.should_exit = TrueServe test server in thread (#292)Florimond Mancabefore adoption994403b
line 289why, one step back289 thread.join()Minor tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed
lines 290–291why, one step back290291Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 292–299why, one step back292@pytest.fixture(scope=SERVER_SCOPE)293def server():294 config = Config(app=app, lifespan="off", loop="asyncio")295 server = TestServer(config=config)296 yield from serve_in_thread(server)297298299@pytest.fixture(scope=SERVER_SCOPE)Add support for unix domain sockets (#511)Jonas Lundbergbefore adoption7a96a2c
lines 300–308why, one step back300def uds_server():301 uds = "test_server.sock"302 config = Config(app=app, lifespan="off", loop="asyncio", uds=uds)303 server = TestServer(config=config)304 yield from serve_in_thread(server)305 os.remove(uds)306307308@pytest.fixture(scope=SERVER_SCOPE)Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 309why, one step back309def https_server(cert_pem_file, cert_private_key_file):Minor tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed
line 310why, one step back310 config = Config(Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 311–314why, one step back311 app=app,312 lifespan="off",313 ssl_certfile=cert_pem_file,314 ssl_keyfile=cert_private_key_file,Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
line 315why, one step back315 host="localhost",Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
line 316why, one step back316 port=8001,Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 317why, one step back317 loop="asyncio",Minor tweaks in line with requests behavior (#110)Tom Christiebefore adoptionfe1f9ed
line 318why, one step back318 )Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 319–320why, one step back319 server = TestServer(config=config)320 yield from serve_in_thread(server)Add support for unix domain sockets (#511)Jonas Lundbergbefore adoption7a96a2c
lines 321–336why, one step back321322323@pytest.fixture(scope=SERVER_SCOPE)324def https_uds_server(cert_pem_file, cert_private_key_file):325 uds = "https_test_server.sock"326 config = Config(327 app=app,328 lifespan="off",329 ssl_certfile=cert_pem_file,330 ssl_keyfile=cert_private_key_file,331 uds=uds,332 loop="asyncio",333 )334 server = TestServer(config=config)335 yield from serve_in_thread(server)336 os.remove(uds)