conftest.py
This file
Path
tests/conftest.py
176 lines · 4.5 KiB · Python
Last changed by
Parametrize tests with concurrency backend (#273)Florimond Mancabefore adoption3674058
History of this fileTake it
1import asyncio23import pytest4import trustme5from cryptography.hazmat.primitives.serialization import (6 BestAvailableEncryption,7 Encoding,8 PrivateFormat,9)10from uvicorn.config import Config11from uvicorn.main import Server1213from httpx import AsyncioBackend141516@pytest.fixture(params=[pytest.param(AsyncioBackend, marks=pytest.mark.asyncio)])17def backend(request):18 backend_cls = request.param19 return backend_cls()202122async def app(scope, receive, send):23 assert scope["type"] == "http"24 if scope["path"] == "/slow_response":25 await slow_response(scope, receive, send)26 elif scope["path"].startswith("/status"):27 await status_code(scope, receive, send)28 elif scope["path"].startswith("/echo_body"):29 await echo_body(scope, receive, send)30 else:31 await hello_world(scope, receive, send)323334async def hello_world(scope, receive, send):35 await send(36 {37 "type": "http.response.start",38 "status": 200,39 "headers": [[b"content-type", b"text/plain"]],40 }41 )42 await send({"type": "http.response.body", "body": b"Hello, world!"})434445async def slow_response(scope, receive, send):46 await asyncio.sleep(0.1)47 await send(48 {49 "type": "http.response.start",50 "status": 200,51 "headers": [[b"content-type", b"text/plain"]],52 }53 )54 await send({"type": "http.response.body", "body": b"Hello, world!"})555657async def status_code(scope, receive, send):58 status_code = int(scope["path"].replace("/status/", ""))59 await send(60 {61 "type": "http.response.start",62 "status": status_code,63 "headers": [[b"content-type", b"text/plain"]],64 }65 )66 await send({"type": "http.response.body", "body": b"Hello, world!"})676869async def echo_body(scope, receive, send):70 body = b""71 more_body = True7273 while more_body:74 message = await receive()75 body += message.get("body", b"")76 more_body = message.get("more_body", False)7778 await send(79 {80 "type": "http.response.start",81 "status": 200,82 "headers": [[b"content-type", b"text/plain"]],83 }84 )85 await send({"type": "http.response.body", "body": body})868788class CAWithPKEncryption(trustme.CA):89 """Implementation of trustme.CA() that can emit90 private keys that are encrypted with a password.91 """9293 @property94 def encrypted_private_key_pem(self):95 return trustme.Blob(96 self._private_key.private_bytes(97 Encoding.PEM,98 PrivateFormat.TraditionalOpenSSL,99 BestAvailableEncryption(password=b"password"),100 )101 )102103104@pytest.fixture105def example_cert():106 ca = CAWithPKEncryption()107 ca.issue_cert("example.org")108 return ca109110111@pytest.fixture112def cert_pem_file(example_cert):113 with example_cert.cert_pem.tempfile() as tmp:114 yield tmp115116117@pytest.fixture118def cert_private_key_file(example_cert):119 with example_cert.private_key_pem.tempfile() as tmp:120 yield tmp121122123@pytest.fixture124def cert_encrypted_private_key_file(example_cert):125 with example_cert.encrypted_private_key_pem.tempfile() as tmp:126 yield tmp127128129@pytest.fixture130async def server():131 config = Config(app=app, lifespan="off")132 server = Server(config=config)133 task = asyncio.ensure_future(server.serve())134 try:135 while not server.started:136 await asyncio.sleep(0.0001)137 yield server138 finally:139 server.should_exit = True140 await task141142143@pytest.fixture144async def https_server(cert_pem_file, cert_private_key_file):145 config = Config(146 app=app,147 lifespan="off",148 ssl_certfile=cert_pem_file,149 ssl_keyfile=cert_private_key_file,150 port=8001,151 )152 server = Server(config=config)153 task = asyncio.ensure_future(server.serve())154 try:155 while not server.started:156 await asyncio.sleep(0.0001)157 yield server158 finally:159 server.should_exit = True160 await task161162163@pytest.fixture164def restart(backend):165 async def asyncio_restart(server):166 await server.shutdown()167 await server.startup()168169 if isinstance(backend, AsyncioBackend):170 return asyncio_restart171172 # The uvicorn server runs under asyncio, so we will need to figure out173 # how to restart it under a different I/O library.174 # This will most likely require running `asyncio_restart` in the threadpool,175 # but that might not be sufficient.176 raise NotImplementedError