conftest.py
This file
Path
tests/conftest.py
267 lines · 7.1 KiB · Python
Last changed by
Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac
History of this fileTake it
The walk stopped after 200 commits: lines older than b6c27f0 point at it.
Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
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 typingMerge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 7–8why, one step back78import pytestMerge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
line 9why, one step back9import trustmeSupport client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 10–14why, one step back10from cryptography.hazmat.primitives.serialization import (11 BestAvailableEncryption,12 Encoding,13 PrivateFormat,14)Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 15–17why, one step back15from uvicorn.config import Config16from uvicorn.main import Server17Add server.url property in tests (#300)Bakhtiyor Ruzievbefore adoptione34d280
line 18why, one step back18from httpx import URL, AsyncioBackendAdd os.environ fixture (#308)Seth Michael Larsonbefore adoptionb8c5e7a
lines 19–40why, one step back1920ENVIRONMENT_VARIABLES = (21 "SSL_CERT_FILE",22 "REQUESTS_CA_BUNDLE",23 "CURL_CA_BUNDLE",24 "HTTP_PROXY",25 "HTTPS_PROXY",26 "ALL_PROXY",27 "NO_PROXY",28 "SSLKEYLOGFILE",29)303132@pytest.fixture(scope="function", autouse=True)33def clean_environ() -> typing.Dict[str, typing.Any]:34 """Keeps os.environ clean for every test without having to mock os.environ"""35 original_environ = os.environ.copy()36 for key in ENVIRONMENT_VARIABLES:37 os.environ.pop(key, None)38 yield39 os.environ.clear()40 os.environ.update(original_environ)Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
line 41why, one step back41Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
lines 42–48why, one step back4243@pytest.fixture(params=[pytest.param(AsyncioBackend, marks=pytest.mark.asyncio)])44def backend(request):45 backend_cls = request.param46 return backend_cls()4748Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 49–54why, one step back49async def app(scope, receive, send):50 assert scope["type"] == "http"51 if scope["path"] == "/slow_response":52 await slow_response(scope, receive, send)53 elif scope["path"].startswith("/status"):54 await status_code(scope, receive, send)Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0
lines 55–56why, one step back55 elif scope["path"].startswith("/echo_body"):56 await echo_body(scope, receive, send)Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac
lines 57–58why, one step back57 elif scope["path"].startswith("/echo_headers"):58 await echo_headers(scope, receive, send)Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 59–74why, one step back59 else:60 await hello_world(scope, receive, send)616263async def hello_world(scope, receive, send):64 await send(65 {66 "type": "http.response.start",67 "status": 200,68 "headers": [[b"content-type", b"text/plain"]],69 }70 )71 await send({"type": "http.response.body", "body": b"Hello, world!"})727374async def slow_response(scope, receive, send):Version 0.6.4 (#105)Tom Christiebefore adoption5326cd1
line 75why, one step back75 await asyncio.sleep(0.1)Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 76–95why, one step back76 await send(77 {78 "type": "http.response.start",79 "status": 200,80 "headers": [[b"content-type", b"text/plain"]],81 }82 )83 await send({"type": "http.response.body", "body": b"Hello, world!"})848586async def status_code(scope, receive, send):87 status_code = int(scope["path"].replace("/status/", ""))88 await send(89 {90 "type": "http.response.start",91 "status": status_code,92 "headers": [[b"content-type", b"text/plain"]],93 }94 )95 await send({"type": "http.response.body", "body": b"Hello, world!"})Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0
lines 96–98why, one step back969798async def echo_body(scope, receive, send):Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
line 99why, one step back99 body = b""Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0
lines 100–103why, one step back100 more_body = True101102 while more_body:103 message = await receive()Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885
lines 104–105why, one step back104 body += message.get("body", b"")105 more_body = message.get("more_body", False)Add 100-continue test (#68)Tom Christiebefore adoption4fe6bc0
lines 106–114why, one step back106107 await send(108 {109 "type": "http.response.start",110 "status": 200,111 "headers": [[b"content-type", b"text/plain"]],112 }113 )114 await send({"type": "http.response.body", "body": body})Add `build_request` to `Client` (#319)Dobrovolsky Bogdanbefore adoption08edfac
lines 115–129why, one step back115116117async def echo_headers(scope, receive, send):118 body = {}119 for name, value in scope.get("headers", []):120 body[name.capitalize().decode()] = value.decode()121122 await send(123 {124 "type": "http.response.start",125 "status": 200,126 "headers": [[b"content-type", b"application/json"]],127 }128 )129 await send({"type": "http.response.body", "body": json.dumps(body).encode()})Merge pull request #58 from encode/sync-by-defaultTom Christiebefore adoptionb6c27f0
lines 130–131why, one step back130131Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 132–147why, one step back132class CAWithPKEncryption(trustme.CA):133 """Implementation of trustme.CA() that can emit134 private keys that are encrypted with a password.135 """136137 @property138 def encrypted_private_key_pem(self):139 return trustme.Blob(140 self._private_key.private_bytes(141 Encoding.PEM,142 PrivateFormat.TraditionalOpenSSL,143 BestAvailableEncryption(password=b"password"),144 )145 )146147Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 148–151why, one step back148SERVER_SCOPE = "session"149150151@pytest.fixture(scope=SERVER_SCOPE)Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 152–153why, one step back152def example_cert():153 ca = CAWithPKEncryption()Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8
line 154why, one step back154 ca.issue_cert("example.org")Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
line 155why, one step back155 return caMerge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8
lines 156–157why, one step back156157Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 158why, one step back158@pytest.fixture(scope=SERVER_SCOPE)Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 159–163why, one step back159def cert_pem_file(example_cert):160 with example_cert.cert_pem.tempfile() as tmp:161 yield tmp162163Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 164why, one step back164@pytest.fixture(scope=SERVER_SCOPE)Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 165–169why, one step back165def cert_private_key_file(example_cert):166 with example_cert.private_key_pem.tempfile() as tmp:167 yield tmp168169Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 170why, one step back170@pytest.fixture(scope=SERVER_SCOPE)Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 171–175why, one step back171def cert_encrypted_private_key_file(example_cert):172 with example_cert.encrypted_private_key_pem.tempfile() as tmp:173 yield tmp174175Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 176why, one step back176class TestServer(Server):Add server.url property in tests (#300)Bakhtiyor Ruzievbefore adoptione34d280
lines 177–181why, one step back177 @property178 def url(self) -> URL:179 protocol = "https" if self.config.is_ssl else "http"180 return URL(f"{protocol}://{self.config.host}:{self.config.port}/")181Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 182–222why, one step back182 def install_signal_handlers(self) -> None:183 # Disable the default installation of handlers for signals such as SIGTERM,184 # because it can only be done in the main thread.185 pass186187 async def serve(self, sockets=None):188 self.restart_requested = asyncio.Event()189190 loop = asyncio.get_event_loop()191 tasks = {192 loop.create_task(super().serve(sockets=sockets)),193 loop.create_task(self.watch_restarts()),194 }195 await asyncio.wait(tasks)196197 async def restart(self) -> None:198 # Ensure we are in an asyncio environment.199 assert asyncio.get_event_loop() is not None200 # This may be called from a different thread than the one the server is201 # running on. For this reason, we use an event to coordinate with the server202 # instead of calling shutdown()/startup() directly.203 self.restart_requested.set()204 self.started = False205 while not self.started:206 await asyncio.sleep(0.5)207208 async def watch_restarts(self):209 while True:210 if self.should_exit:211 return212213 try:214 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)215 except asyncio.TimeoutError:216 continue217218 self.restart_requested.clear()219 await self.shutdown()220 await self.startup()221222Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
line 223why, one step back223@pytest.fixtureServe test server in thread (#292)Florimond Mancabefore adoption994403b
lines 224–239why, one step back224def restart(backend):225 """Restart the running server from an async test function.226227 This fixture deals with possible differences between the environment of the228 test function and that of the server.229 """230231 async def restart(server):232 await backend.run_in_threadpool(AsyncioBackend().run, server.restart)233234 return restart235236237def serve_in_thread(server: Server):238 thread = threading.Thread(target=server.run)239 thread.start()Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
lines 240–241why, one step back240 try:241 while not server.started:Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 242why, one step back242 time.sleep(1e-3)Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
lines 243–245why, one step back243 yield server244 finally:245 server.should_exit = TrueServe test server in thread (#292)Florimond Mancabefore adoption994403b
line 246why, one step back246 thread.join()Merge pull request #57 from yeraydiazdiaz/test-httpsTom Christiebefore adoptionc27c635
lines 247–248why, one step back247248Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 249–257why, one step back249@pytest.fixture(scope=SERVER_SCOPE)250def server():251 config = Config(app=app, lifespan="off", loop="asyncio")252 server = TestServer(config=config)253 yield from serve_in_thread(server)254255256@pytest.fixture(scope=SERVER_SCOPE)257def https_server(cert_pem_file, cert_private_key_file):Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8
line 258why, one step back258 config = Config(Support client cert passwords, new TLS options (#118)Seth Michael Larsonbefore adoptionba83e29
lines 259–263why, one step back259 app=app,260 lifespan="off",261 ssl_certfile=cert_pem_file,262 ssl_keyfile=cert_private_key_file,263 port=8001,Serve test server in thread (#292)Florimond Mancabefore adoption994403b
line 264why, one step back264 loop="asyncio",Merge pull request #61 from yeraydiazdiaz/test-configTom Christiebefore adoptionabec2e8
line 265why, one step back265 )Serve test server in thread (#292)Florimond Mancabefore adoption994403b
lines 266–267why, one step back266 server = TestServer(config=config)267 yield from serve_in_thread(server)