conftest.py
This file
Path
tests/conftest.py
337 lines · 9.2 KiB · Python
Last changed by
Tighten up top-level API to only expose public API (#608)Tom Christiebefore adoptiond15dc0b
History of this fileTake it
The walk stopped after 200 commits: lines older than a960a2a point at it.
Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
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 typingRelease semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
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_backendRelease semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
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,Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
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
lines 20–21why, one step back20from httpx import URL21from httpx.concurrency.asyncio import AsyncioBackendDon't check trio import in definition of backend fixture params (#447)Florimond Mancabefore adoptionfc3df51
line 22why, one step back22from httpx.concurrency.trio import TrioBackendAdd 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)Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
line 50why, one step back50Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
line 51why, one step back51Don't check trio import in definition of backend fixture params (#447)Florimond Mancabefore adoptionfc3df51
lines 52–57why, one step back52@pytest.fixture(53 params=[54 pytest.param(AsyncioBackend, marks=pytest.mark.asyncio),55 pytest.param(TrioBackend, marks=pytest.mark.trio),56 ]57)Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
lines 58–62why, one step back58def backend(request):59 backend_cls = request.param60 return backend_cls()6162Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
lines 63–64why, one step back63async def app(scope, receive, send):64 assert scope["type"] == "http"Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117
line 65why, one step back65 if scope["path"].startswith("/slow_response"):Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
line 66why, one step back66 await slow_response(scope, receive, send)Handle h11.Connection.next_event() RemoteProtocolError (#524)toppkbefore adoptionf06ca87
lines 67–68why, one step back67 elif scope["path"].startswith("/premature_close"):68 await premature_close(scope, receive, send)Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
lines 69–72why, one step back69 elif scope["path"].startswith("/status"):70 await status_code(scope, receive, send)71 elif scope["path"].startswith("/echo_body"):72 await echo_body(scope, receive, send)Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac
lines 73–74why, one step back73 elif scope["path"].startswith("/echo_headers"):74 await echo_headers(scope, receive, send)Add DEBUG logs of HTTP requests (#502)Florimond Mancabefore adoption08069e9
lines 75–76why, one step back75 elif scope["path"].startswith("/redirect_301"):76 await redirect_301(scope, receive, send)Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
lines 77–92why, one step back77 else:78 await hello_world(scope, receive, send)798081async def hello_world(scope, receive, send):82 await send(83 {84 "type": "http.response.start",85 "status": 200,86 "headers": [[b"content-type", b"text/plain"]],87 }88 )89 await send({"type": "http.response.body", "body": b"Hello, world!"})909192async def slow_response(scope, receive, send):Add `.elapsed` onto Response objects tracking how long a request took. (#351)Roy Williamsbefore adoption05ac117
lines 93–98why, one step back93 delay_ms_str: str = scope["path"].replace("/slow_response/", "")94 try:95 delay_ms = float(delay_ms_str)96 except ValueError:97 delay_ms = 10098 await asyncio.sleep(delay_ms / 1000.0)Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
lines 99–106why, one step back99 await send(100 {101 "type": "http.response.start",102 "status": 200,103 "headers": [[b"content-type", b"text/plain"]],104 }105 )106 await send({"type": "http.response.body", "body": b"Hello, world!"})Handle h11.Connection.next_event() RemoteProtocolError (#524)toppkbefore adoptionf06ca87
lines 107–116why, one step back107108109async def premature_close(scope, receive, send):110 await send(111 {112 "type": "http.response.start",113 "status": 200,114 "headers": [[b"content-type", b"text/plain"]],115 }116 )Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
lines 117–147why, one step back117118119async def status_code(scope, receive, send):120 status_code = int(scope["path"].replace("/status/", ""))121 await send(122 {123 "type": "http.response.start",124 "status": status_code,125 "headers": [[b"content-type", b"text/plain"]],126 }127 )128 await send({"type": "http.response.body", "body": b"Hello, world!"})129130131async def echo_body(scope, receive, send):132 body = b""133 more_body = True134135 while more_body:136 message = await receive()137 body += message.get("body", b"")138 more_body = message.get("more_body", False)139140 await send(141 {142 "type": "http.response.start",143 "status": 200,144 "headers": [[b"content-type", b"text/plain"]],145 }146 )147 await send({"type": "http.response.body", "body": body})Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac
lines 148–162why, one step back148149150async def echo_headers(scope, receive, send):151 body = {}152 for name, value in scope.get("headers", []):153 body[name.capitalize().decode()] = value.decode()154155 await send(156 {157 "type": "http.response.start",158 "status": 200,159 "headers": [[b"content-type", b"application/json"]],160 }161 )162 await send({"type": "http.response.body", "body": json.dumps(body).encode()})Add DEBUG logs of HTTP requests (#502)Florimond Mancabefore adoption08069e9
lines 163–166why, one step back163164165async def redirect_301(scope, receive, send):166 await send(Drop sync (#544)Tom Christiebefore adoption206c537
line 167why, one step back167 {"type": "http.response.start", "status": 301, "headers": [[b"location", b"/"]]}Add DEBUG logs of HTTP requests (#502)Florimond Mancabefore adoption08069e9
lines 168–169why, one step back168 )169 await send({"type": "http.response.body"})Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
lines 170–171why, one step back170171Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
line 172why, one step back172SERVER_SCOPE = "session"Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
lines 173–174why, one step back173174Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 175–177why, one step back175@pytest.fixture(scope=SERVER_SCOPE)176def cert_authority():177 return trustme.CA()Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
line 178why, one step back178Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 179why, one step back179Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 180–183why, one step back180@pytest.fixture(scope=SERVER_SCOPE)181def ca_cert_pem_file(cert_authority):182 with cert_authority.cert_pem.tempfile() as tmp:183 yield tmpServe test server in thread (#292)Florimond Mancabefore adoption994403b
line 184why, one step back184Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
line 185why, one step back185Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 186why, one step back186@pytest.fixture(scope=SERVER_SCOPE)Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 187–188why, one step back187def localhost_cert(cert_authority):188 return cert_authority.issue_cert("localhost")Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
lines 189–190why, one step back189190Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 191why, one step back191@pytest.fixture(scope=SERVER_SCOPE)Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 192–193why, one step back192def cert_pem_file(localhost_cert):193 with localhost_cert.cert_chain_pems[0].tempfile() as tmp:Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
lines 194–196why, one step back194 yield tmp195196Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 197why, one step back197@pytest.fixture(scope=SERVER_SCOPE)Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 198–199why, one step back198def cert_private_key_file(localhost_cert):199 with localhost_cert.private_key_pem.tempfile() as tmp:Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
lines 200–202why, one step back200 yield tmp201202Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 203why, one step back203@pytest.fixture(scope=SERVER_SCOPE)Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
lines 204–216why, one step back204def cert_encrypted_private_key_file(localhost_cert):205 # Deserialize the private key and then reserialize with a password206 private_key = load_pem_private_key(207 localhost_cert.private_key_pem.bytes(), password=None, backend=default_backend()208 )209 encrypted_private_key_pem = trustme.Blob(210 private_key.private_bytes(211 Encoding.PEM,212 PrivateFormat.TraditionalOpenSSL,213 BestAvailableEncryption(password=b"password"),214 )215 )216 with encrypted_private_key_pem.tempfile() as tmp:Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
lines 217–219why, one step back217 yield tmp218219Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 220why, one step back220class TestServer(Server):Add server.url property in tests (#300)Bakhtiyor Ruzievbefore adoptione34d280
lines 221–225why, one step back221 @property222 def url(self) -> URL:223 protocol = "https" if self.config.is_ssl else "http"224 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")225Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 226–266why, one step back226 def install_signal_handlers(self) -> None:227 # Disable the default installation of handlers for signals such as SIGTERM,228 # because it can only be done in the main thread.229 pass230231 async def serve(self, sockets=None):232 self.restart_requested = asyncio.Event()233234 loop = asyncio.get_event_loop()235 tasks = {236 loop.create_task(super().serve(sockets=sockets)),237 loop.create_task(self.watch_restarts()),238 }239 await asyncio.wait(tasks)240241 async def restart(self) -> None:242 # Ensure we are in an asyncio environment.243 assert asyncio.get_event_loop() is not None244 # This may be called from a different thread than the one the server is245 # running on. For this reason, we use an event to coordinate with the server246 # instead of calling shutdown()/startup() directly.247 self.restart_requested.set()248 self.started = False249 while not self.started:250 await asyncio.sleep(0.5)251252 async def watch_restarts(self):253 while True:254 if self.should_exit:255 return256257 try:258 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)259 except asyncio.TimeoutError:260 continue261262 self.restart_requested.clear()263 await self.shutdown()264 await self.startup()265266Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
line 267why, one step back267@pytest.fixtureServe test server in thread (#292)Florimond Mancabefore adoption994403b
lines 268–283why, one step back268def restart(backend):269 """Restart the running server from an async test function.270271 This fixture deals with possible differences between the environment of the272 test function and that of the server.273 """274275 async def restart(server):276 await backend.run_in_threadpool(AsyncioBackend().run, server.restart)277278 return restart279280281def serve_in_thread(server: Server):282 thread = threading.Thread(target=server.run)283 thread.start()Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
lines 284–285why, one step back284 try:285 while not server.started:Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 286why, one step back286 time.sleep(1e-3)Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
lines 287–289why, one step back287 yield server288 finally:289 server.should_exit = TrueServe test server in thread (#292)Florimond Mancabefore adoption994403b
line 290why, one step back290 thread.join()Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
lines 291–292why, one step back291292Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 293–300why, one step back293@pytest.fixture(scope=SERVER_SCOPE)294def server():295 config = Config(app=app, lifespan="off", loop="asyncio")296 server = TestServer(config=config)297 yield from serve_in_thread(server)298299300@pytest.fixture(scope=SERVER_SCOPE)Add support for unix domain sockets (#511)Jonas Lundbergbefore adoption7a96a2c
lines 301–309why, one step back301def uds_server():302 uds = "test_server.sock"303 config = Config(app=app, lifespan="off", loop="asyncio", uds=uds)304 server = TestServer(config=config)305 yield from serve_in_thread(server)306 os.remove(uds)307308309@pytest.fixture(scope=SERVER_SCOPE)Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 310why, one step back310def https_server(cert_pem_file, cert_private_key_file):Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
lines 311–315why, one step back311 config = Config(312 app=app,313 lifespan="off",314 ssl_certfile=cert_pem_file,315 ssl_keyfile=cert_private_key_file,Use a certificate issued from the trustme CA in tests (#357)Jamie Hewlandbefore adoption338a360
line 316why, one step back316 host="localhost",Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
line 317why, one step back317 port=8001,Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 318why, one step back318 loop="asyncio",Release semaphore if connection is dropped (#230)Ordanis Sanchezbefore adoptiona960a2a
line 319why, one step back319 )Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 320–321why, one step back320 server = TestServer(config=config)321 yield from serve_in_thread(server)Add support for unix domain sockets (#511)Jonas Lundbergbefore adoption7a96a2c
lines 322–337why, one step back322323324@pytest.fixture(scope=SERVER_SCOPE)325def https_uds_server(cert_pem_file, cert_private_key_file):326 uds = "https_test_server.sock"327 config = Config(328 app=app,329 lifespan="off",330 ssl_certfile=cert_pem_file,331 ssl_keyfile=cert_private_key_file,332 uds=uds,333 loop="asyncio",334 )335 server = TestServer(config=config)336 yield from serve_in_thread(server)337 os.remove(uds)