conftest.py
This file
Path
tests/conftest.py
345 lines · 9.6 KiB · Python
Last changed by
Rename `concurrency` directory to `backends` (#662)Andrés Álvarezbefore adoptione34df7a
History of this fileTake it
The walk stopped after 200 commits: lines older than 994403b point at it.
Serve test server in thread (#292)Florimond Mancabefore adoption994403b
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 typingServe test server in thread (#292)Florimond Mancabefore adoption994403b
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_backendServe test server in thread (#292)Florimond Mancabefore adoption994403b
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,Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 16–19why, one step back16)17from uvicorn.config import Config18from uvicorn.main import Server19Tighten up top-level API to only expose public API (#608)Tom Christiebefore adoptiond15dc0b
line 20why, one step back20from httpx import URLRename `concurrency` directory to `backends` (#662)Andrés Álvarezbefore adoptione34df7a
lines 21–22why, one step back21from httpx.backends.asyncio import AsyncioBackend22from httpx.backends.base import lookup_backendAdd os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
line 23why, one step back23Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
line 24why, one step back24ENVIRONMENT_VARIABLES = {Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
line 25why, one step back25 "SSL_CERT_FILE",Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
line 26why, one step back26 "SSL_CERT_DIR",Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
lines 27–31why, one step back27 "HTTP_PROXY",28 "HTTPS_PROXY",29 "ALL_PROXY",30 "NO_PROXY",31 "SSLKEYLOGFILE",Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
line 32why, one step back32}Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
lines 33–38why, one step back333435@pytest.fixture(scope="function", autouse=True)36def clean_environ() -> typing.Dict[str, typing.Any]:37 """Keeps os.environ clean for every test without having to mock os.environ"""38 original_environ = os.environ.copy()Implement HTTPProxy dispatcher (#259)Seth Michael Larsonbefore adoption57c27ca
lines 39–46why, one step back39 os.environ.clear()40 os.environ.update(41 {42 k: v43 for k, v in original_environ.items()44 if k not in ENVIRONMENT_VARIABLES and k.lower() not in ENVIRONMENT_VARIABLES45 }46 )Add os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
lines 47–49why, one step back47 yield48 os.environ.clear()49 os.environ.update(original_environ)Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 50–51why, one step back5051Don't check trio import in definition of backend fixture params (#447)Florimond Mancabefore adoptionfc3df51
lines 52–53why, one step back52@pytest.fixture(53 params=[Refactor tests in the light of backend auto-detection (#615)Florimond Mancabefore adoptionab41a5d
lines 54–60why, one step back54 # pytest uses the marks to set up the specified async environment and run55 # 'async def' test functions. The "auto" backend should then auto-detect56 # the environment it's running in.57 # Passing the backend explicitly, e.g. `backend="asyncio"`,58 # is tested separately.59 pytest.param("auto", marks=pytest.mark.asyncio),60 pytest.param("auto", marks=pytest.mark.trio),Don't check trio import in definition of backend fixture params (#447)Florimond Mancabefore adoptionfc3df51
lines 61–62why, one step back61 ]62)Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 63why, one step back63def backend(request):Refactor tests in the light of backend auto-detection (#615)Florimond Mancabefore adoptionab41a5d
line 64why, one step back64 return request.paramServe test server in thread (#292)Florimond Mancabefore adoption994403b
lines 65–68why, one step back656667async def app(scope, receive, send):68 assert scope["type"] == "http"Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117
line 69why, one step back69 if scope["path"].startswith("/slow_response"):Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 70why, one step back70 await slow_response(scope, receive, send)Handle h11.Connection.next_event() RemoteProtocolError (#524)toppkbefore adoptionf06ca87
lines 71–72why, one step back71 elif scope["path"].startswith("/premature_close"):72 await premature_close(scope, receive, send)Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 73–76why, one step back73 elif scope["path"].startswith("/status"):74 await status_code(scope, receive, send)75 elif scope["path"].startswith("/echo_body"):76 await echo_body(scope, receive, send)Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac
lines 77–78why, one step back77 elif scope["path"].startswith("/echo_headers"):78 await echo_headers(scope, receive, send)Add DEBUG logs of HTTP requests (#502)Florimond Mancabefore adoption08069e9
lines 79–80why, one step back79 elif scope["path"].startswith("/redirect_301"):80 await redirect_301(scope, receive, send)Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 81–96why, one step back81 else:82 await hello_world(scope, receive, send)838485async def hello_world(scope, receive, send):86 await send(87 {88 "type": "http.response.start",89 "status": 200,90 "headers": [[b"content-type", b"text/plain"]],91 }92 )93 await send({"type": "http.response.body", "body": b"Hello, world!"})949596async def slow_response(scope, receive, send):Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117
lines 97–102why, one step back97 delay_ms_str: str = scope["path"].replace("/slow_response/", "")98 try:99 delay_ms = float(delay_ms_str)100 except ValueError:101 delay_ms = 100102 await asyncio.sleep(delay_ms / 1000.0)Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 103–110why, one step back103 await send(104 {105 "type": "http.response.start",106 "status": 200,107 "headers": [[b"content-type", b"text/plain"]],108 }109 )110 await send({"type": "http.response.body", "body": b"Hello, world!"})Handle h11.Connection.next_event() RemoteProtocolError (#524)toppkbefore adoptionf06ca87
lines 111–120why, one step back111112113async def premature_close(scope, receive, send):114 await send(115 {116 "type": "http.response.start",117 "status": 200,118 "headers": [[b"content-type", b"text/plain"]],119 }120 )Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 121–151why, one step back121122123async def status_code(scope, receive, send):124 status_code = int(scope["path"].replace("/status/", ""))125 await send(126 {127 "type": "http.response.start",128 "status": status_code,129 "headers": [[b"content-type", b"text/plain"]],130 }131 )132 await send({"type": "http.response.body", "body": b"Hello, world!"})133134135async def echo_body(scope, receive, send):136 body = b""137 more_body = True138139 while more_body:140 message = await receive()141 body += message.get("body", b"")142 more_body = message.get("more_body", False)143144 await send(145 {146 "type": "http.response.start",147 "status": 200,148 "headers": [[b"content-type", b"text/plain"]],149 }150 )151 await send({"type": "http.response.body", "body": body})Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac
lines 152–166why, one step back152153154async def echo_headers(scope, receive, send):155 body = {}156 for name, value in scope.get("headers", []):157 body[name.capitalize().decode()] = value.decode()158159 await send(160 {161 "type": "http.response.start",162 "status": 200,163 "headers": [[b"content-type", b"application/json"]],164 }165 )166 await send({"type": "http.response.body", "body": json.dumps(body).encode()})Add DEBUG logs of HTTP requests (#502)Florimond Mancabefore adoption08069e9
lines 167–170why, one step back167168169async def redirect_301(scope, receive, send):170 await send(Drop sync (#544)Tom Christiebefore adoption206c537
line 171why, one step back171 {"type": "http.response.start", "status": 301, "headers": [[b"location", b"/"]]}Add DEBUG logs of HTTP requests (#502)Florimond Mancabefore adoption08069e9
lines 172–173why, one step back172 )173 await send({"type": "http.response.body"})Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 174–175why, one step back174175Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
line 176why, one step back176SERVER_SCOPE = "session"Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 177–178why, one step back177178Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 179–181why, one step back179@pytest.fixture(scope=SERVER_SCOPE)180def cert_authority():181 return trustme.CA()Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 182–183why, one step back182183Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 184–187why, one step back184@pytest.fixture(scope=SERVER_SCOPE)185def ca_cert_pem_file(cert_authority):186 with cert_authority.cert_pem.tempfile() as tmp:187 yield tmpServe test server in thread (#292)Florimond Mancabefore adoption994403b
line 188why, one step back188Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
line 189why, one step back189Serve 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 localhost_cert(cert_authority):192 return cert_authority.issue_cert("localhost")Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 193–195why, one step back193194195@pytest.fixture(scope=SERVER_SCOPE)Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 196–197why, one step back196def cert_pem_file(localhost_cert):197 with localhost_cert.cert_chain_pems[0].tempfile() as tmp:Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 198–201why, one step back198 yield tmp199200201@pytest.fixture(scope=SERVER_SCOPE)Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 202–203why, one step back202def cert_private_key_file(localhost_cert):203 with localhost_cert.private_key_pem.tempfile() as tmp:Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 204–207why, one step back204 yield tmp205206207@pytest.fixture(scope=SERVER_SCOPE)Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 208–220why, one step back208def cert_encrypted_private_key_file(localhost_cert):209 # Deserialize the private key and then reserialize with a password210 private_key = load_pem_private_key(211 localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()212 )213 encrypted_private_key_pem = trustme.Blob(214 private_key.private_bytes(215 Encoding.PEM,216 PrivateFormat.TraditionalOpenSSL,217 BestAvailableEncryption(password=b"password"),218 )219 )220 with encrypted_private_key_pem.tempfile() as tmp:Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 221–224why, one step back221 yield tmp222223224class TestServer(Server):Add server.url property in tests (#300)Bakhtiyor Ruzievbefore adoptione34d280
lines 225–229why, one step back225 @property226 def url(self) -> URL:227 protocol = "https" if self.config.is_ssl else "http"228 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")229Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 230–277why, one step back230 def install_signal_handlers(self) -> None:231 # Disable the default installation of handlers for signals such as SIGTERM,232 # because it can only be done in the main thread.233 pass234235 async def serve(self, sockets=None):236 self.restart_requested = asyncio.Event()237238 loop = asyncio.get_event_loop()239 tasks = {240 loop.create_task(super().serve(sockets=sockets)),241 loop.create_task(self.watch_restarts()),242 }243 await asyncio.wait(tasks)244245 async def restart(self) -> None:246 # Ensure we are in an asyncio environment.247 assert asyncio.get_event_loop() is not None248 # This may be called from a different thread than the one the server is249 # running on. For this reason, we use an event to coordinate with the server250 # instead of calling shutdown()/startup() directly.251 self.restart_requested.set()252 self.started = False253 while not self.started:254 await asyncio.sleep(0.5)255256 async def watch_restarts(self):257 while True:258 if self.should_exit:259 return260261 try:262 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)263 except asyncio.TimeoutError:264 continue265266 self.restart_requested.clear()267 await self.shutdown()268 await self.startup()269270271@pytest.fixture272def restart(backend):273 """Restart the running server from an async test function.274275 This fixture deals with possible differences between the environment of the276 test function and that of the server.277 """Refactor tests in the light of backend auto-detection (#615)Florimond Mancabefore adoptionab41a5d
lines 278–279why, one step back278 asyncio_backend = AsyncioBackend()279 backend_implementation = lookup_backend(backend)Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 280–281why, one step back280281 async def restart(server):Refactor tests in the light of backend auto-detection (#615)Florimond Mancabefore adoptionab41a5d
lines 282–284why, one step back282 await backend_implementation.run_in_threadpool(283 asyncio_backend.run, server.restart284 )Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 285–308why, one step back285286 return restart287288289def serve_in_thread(server: Server):290 thread = threading.Thread(target=server.run)291 thread.start()292 try:293 while not server.started:294 time.sleep(1e-3)295 yield server296 finally:297 server.should_exit = True298 thread.join()299300301@pytest.fixture(scope=SERVER_SCOPE)302def server():303 config = Config(app=app, lifespan="off", loop="asyncio")304 server = TestServer(config=config)305 yield from serve_in_thread(server)306307308@pytest.fixture(scope=SERVER_SCOPE)Add support for unix domain sockets (#511)Jonas Lundbergbefore adoption7a96a2c
lines 309–317why, one step back309def uds_server():310 uds = "test_server.sock"311 config = Config(app=app, lifespan="off", loop="asyncio", uds=uds)312 server = TestServer(config=config)313 yield from serve_in_thread(server)314 os.remove(uds)315316317@pytest.fixture(scope=SERVER_SCOPE)Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 318–323why, one step back318def https_server(cert_pem_file, cert_private_key_file):319 config = Config(320 app=app,321 lifespan="off",322 ssl_certfile=cert_pem_file,323 ssl_keyfile=cert_private_key_file,Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
line 324why, one step back324 host="localhost",Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 325–329why, one step back325 port=8001,326 loop="asyncio",327 )328 server = TestServer(config=config)329 yield from serve_in_thread(server)Add support for unix domain sockets (#511)Jonas Lundbergbefore adoption7a96a2c
lines 330–345why, one step back330331332@pytest.fixture(scope=SERVER_SCOPE)333def https_uds_server(cert_pem_file, cert_private_key_file):334 uds = "https_test_server.sock"335 config = Config(336 app=app,337 lifespan="off",338 ssl_certfile=cert_pem_file,339 ssl_keyfile=cert_private_key_file,340 uds=uds,341 loop="asyncio",342 )343 server = TestServer(config=config)344 yield from serve_in_thread(server)345 os.remove(uds)