Serve test server in thread (#292)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Florimond Manca · committed by GitHub · parent e9b2099 · Browse files · 7 files·+120 added−130 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+120 added−130 removed
- tests:+119 added−129 removed
- other:+1 added−1 removed
Provenance
- Commit
994403b- Tree
65d1051- Author
Florimond Manca <florimond.manca@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
e9b2099
7 files changed+120 added−130 removed
modified:httpx/concurrency/asyncio.py+1 added-1 removed
111 unmodified lines112 self.stream_writer.drain(), timeout.write_timeout113 )114 break115 except asyncio.TimeoutError:116- # We check our flag at the possible moment, in order to116+ # We check our flag at the first possible moment, in order to117 # allow us to suppress write timeouts, if we've since118 # switched over to read-timeout mode.119 should_raise = flag is None or flag.raise_on_write_timeout120 if should_raise:167 unmodified linesmodified:tests/client/test_client.py-33 removed
1-import asyncio2-import functools3-1 import pytest2 3 import httpx4 5 9-def threadpool(func):10- """11- Our sync tests should run in separate thread to the uvicorn server.12- """13-14- @functools.wraps(func)15- async def wrapped(*args, **kwargs):16- nonlocal func17-18- loop = asyncio.get_event_loop()19- if kwargs:20- func = functools.partial(func, **kwargs)21- await loop.run_in_executor(None, func, *args)22-23- return pytest.mark.asyncio(wrapped)24-25-26-@threadpool6 def test_get(server):7 url = "http://127.0.0.1:8000/"8 with httpx.Client() as http:9 response = http.get(url)8 unmodified lines18 assert response.is_redirect is False19 assert repr(response) == "<Response [200 OK]>"20 21 43-@threadpool22 def test_post(server):23 with httpx.Client() as http:24 response = http.post("http://127.0.0.1:8000/", data=b"Hello, world!")25 assert response.status_code == 20026 assert response.reason_phrase == "OK"27 28 51-@threadpool29 def test_post_json(server):30 with httpx.Client() as http:31 response = http.post("http://127.0.0.1:8000/", json={"text": "Hello, world!"})32 assert response.status_code == 20033 assert response.reason_phrase == "OK"34 35 59-@threadpool36 def test_stream_response(server):37 with httpx.Client() as http:38 response = http.get("http://127.0.0.1:8000/", stream=True)39 assert response.status_code == 20040 content = response.read()41 assert content == b"Hello, world!"42 43 68-@threadpool44 def test_stream_iterator(server):45 with httpx.Client() as http:46 response = http.get("http://127.0.0.1:8000/", stream=True)47 assert response.status_code == 2002 unmodified lines50 body += chunk51 assert body == b"Hello, world!"52 53 79-@threadpool54 def test_raw_iterator(server):55 with httpx.Client() as http:56 response = http.get("http://127.0.0.1:8000/", stream=True)57 assert response.status_code == 2003 unmodified lines61 assert body == b"Hello, world!"62 response.close() # TODO: should Response be available as context managers?63 64 91-@threadpool65 def test_raise_for_status(server):66 with httpx.Client() as client:67 for status_code in (200, 400, 404, 500, 505):68 response = client.request(6 unmodified lines75 else:76 assert response.raise_for_status() is None77 78 106-@threadpool79 def test_options(server):80 with httpx.Client() as http:81 response = http.options("http://127.0.0.1:8000/")82 assert response.status_code == 20083 assert response.reason_phrase == "OK"84 85 114-@threadpool86 def test_head(server):87 with httpx.Client() as http:88 response = http.head("http://127.0.0.1:8000/")89 assert response.status_code == 20090 assert response.reason_phrase == "OK"91 92 122-@threadpool93 def test_put(server):94 with httpx.Client() as http:95 response = http.put("http://127.0.0.1:8000/", data=b"Hello, world!")96 assert response.status_code == 20097 assert response.reason_phrase == "OK"98 99 130-@threadpool100 def test_patch(server):101 with httpx.Client() as http:102 response = http.patch("http://127.0.0.1:8000/", data=b"Hello, world!")103 assert response.status_code == 200104 assert response.reason_phrase == "OK"105 106 138-@threadpool107 def test_delete(server):108 with httpx.Client() as http:109 response = http.delete("http://127.0.0.1:8000/")110 assert response.status_code == 200111 assert response.reason_phrase == "OK"112 113 146-@threadpool114 def test_base_url(server):115 base_url = "http://127.0.0.1:8000/"116 with httpx.Client(base_url=base_url) as http:117 response = http.get("/")26 unmodified linesmodified:tests/dispatch/test_connection_pools.py+2 added-2 removed
132 unmodified lines133 async with httpx.ConnectionPool(backend=backend) as http:134 response = await http.request("GET", "http://127.0.0.1:8000/")135 await response.read()136 137- # shutdown the server to close the keep-alive connection137+ # Shutdown the server to close the keep-alive connection138 await restart(server)139 140 response = await http.request("GET", "http://127.0.0.1:8000/")141 await response.read()11 unmodified lines153 async with httpx.ConnectionPool(backend=backend) as http:154 response = await http.request("GET", "http://127.0.0.1:8000/")155 await response.read()156 157- # shutdown the server to close the keep-alive connection157+ # Shutdown the server to close the keep-alive connection158 await restart(server)159 160 response = await http.request("GET", "http://127.0.0.1:8000/")161 await response.read()18 unmodified linesmodified:tests/dispatch/test_connections.py+23 added-21 removed
1 from httpx import HTTPConnection2 3 4 async def test_get(server, backend):5- conn = HTTPConnection(origin="http://127.0.0.1:8000/", backend=backend)6- response = await conn.request("GET", "http://127.0.0.1:8000/")7- await response.read()8- assert response.status_code == 2009- assert response.content == b"Hello, world!"5+ async with HTTPConnection(origin="http://127.0.0.1:8000/", backend=backend) as conn:6+ response = await conn.request("GET", "http://127.0.0.1:8000/")7+ await response.read()8+ assert response.status_code == 2009+ assert response.content == b"Hello, world!"10 11 12 async def test_post(server, backend):13- conn = HTTPConnection(origin="http://127.0.0.1:8000/", backend=backend)14- response = await conn.request(15- "GET", "http://127.0.0.1:8000/", data=b"Hello, world!"16- )17- assert response.status_code == 20013+ async with HTTPConnection(origin="http://127.0.0.1:8000/", backend=backend) as conn:14+ response = await conn.request(15+ "GET", "http://127.0.0.1:8000/", data=b"Hello, world!"16+ )17+ assert response.status_code == 20018 19 20 async def test_https_get_with_ssl_defaults(https_server, backend):21 """22 An HTTPS request, with default SSL configuration set on the client.23 """24- conn = HTTPConnection(24+ async with HTTPConnection(25 origin="https://127.0.0.1:8001/", verify=False, backend=backend26- )27- response = await conn.request("GET", "https://127.0.0.1:8001/")28- await response.read()29- assert response.status_code == 20030- assert response.content == b"Hello, world!"26+ ) as conn:27+ response = await conn.request("GET", "https://127.0.0.1:8001/")28+ await response.read()29+ assert response.status_code == 20030+ assert response.content == b"Hello, world!"31 32 33 async def test_https_get_with_sll_overrides(https_server, backend):34 """35 An HTTPS request, with SSL configuration set on the request.36 """37+ async with HTTPConnection(38+ origin="https://127.0.0.1:8001/", backend=backend37- conn = HTTPConnection(origin="https://127.0.0.1:8001/", backend=backend)38- response = await conn.request("GET", "https://127.0.0.1:8001/", verify=False)39- await response.read()40- assert response.status_code == 20041- assert response.content == b"Hello, world!"39+ ) as conn:40+ response = await conn.request("GET", "https://127.0.0.1:8001/", verify=False)41+ await response.read()42+ assert response.status_code == 20043+ assert response.content == b"Hello, world!"modified:tests/conftest.py+82 added-37 removed
1 import asyncio2+import threading3+import time4 5 import pytest6 import trustme7 from cryptography.hazmat.primitives.serialization import (94 unmodified lines102 )103 )104 105 104-@pytest.fixture106+SERVER_SCOPE = "session"107+108+109+@pytest.fixture(scope=SERVER_SCOPE)110 def example_cert():111 ca = CAWithPKEncryption()112 ca.issue_cert("example.org")113 return ca114 115 111-@pytest.fixture116+@pytest.fixture(scope=SERVER_SCOPE)117 def cert_pem_file(example_cert):118 with example_cert.cert_pem.tempfile() as tmp:119 yield tmp120 121 117-@pytest.fixture122+@pytest.fixture(scope=SERVER_SCOPE)123 def cert_private_key_file(example_cert):124 with example_cert.private_key_pem.tempfile() as tmp:125 yield tmp126 127 123-@pytest.fixture128+@pytest.fixture(scope=SERVER_SCOPE)129 def cert_encrypted_private_key_file(example_cert):130 with example_cert.encrypted_private_key_pem.tempfile() as tmp:131 yield tmp132 133 134+class TestServer(Server):135+ def install_signal_handlers(self) -> None:136+ # Disable the default installation of handlers for signals such as SIGTERM,137+ # because it can only be done in the main thread.138+ pass139+140+ async def serve(self, sockets=None):141+ self.restart_requested = asyncio.Event()142+143+ loop = asyncio.get_event_loop()144+ tasks = {145+ loop.create_task(super().serve(sockets=sockets)),146+ loop.create_task(self.watch_restarts()),147+ }148+149+ await asyncio.wait(tasks)150+151+ async def restart(self) -> None:152+ # Ensure we are in an asyncio environment.153+ assert asyncio.get_event_loop() is not None154+ # This may be called from a different thread than the one the server is155+ # running on. For this reason, we use an event to coordinate with the server156+ # instead of calling shutdown()/startup() directly.157+ self.restart_requested.set()158+ self.started = False159+ while not self.started:160+ await asyncio.sleep(0.5)161+162+ async def watch_restarts(self):163+ while True:164+ if self.should_exit:165+ return166+167+ try:168+ await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)169+ except asyncio.TimeoutError:170+ continue171+172+ self.restart_requested.clear()173+ await self.shutdown()174+ await self.startup()175+176+177 @pytest.fixture130-async def server():131- config = Config(app=app, lifespan="off")132- server = Server(config=config)133- task = asyncio.ensure_future(server.serve())178+def restart(backend):179+ """Restart the running server from an async test function.180+181+ This fixture deals with possible differences between the environment of the182+ test function and that of the server.183+ """184+185+ async def restart(server):186+ await backend.run_in_threadpool(AsyncioBackend().run, server.restart)187+188+ return restart189+190+191+def serve_in_thread(server: Server):192+ thread = threading.Thread(target=server.run)193+ thread.start()194 try:195 while not server.started:136- await asyncio.sleep(0.0001)196+ time.sleep(1e-3)197 yield server198 finally:199 server.should_exit = True140- await task200+ thread.join()201 202 143-@pytest.fixture144-async def https_server(cert_pem_file, cert_private_key_file):203+@pytest.fixture(scope=SERVER_SCOPE)204+def server():205+ config = Config(app=app, lifespan="off", loop="asyncio")206+ server = TestServer(config=config)207+ yield from serve_in_thread(server)208+209+210+@pytest.fixture(scope=SERVER_SCOPE)211+def https_server(cert_pem_file, cert_private_key_file):212 config = Config(213 app=app,214 lifespan="off",215 ssl_certfile=cert_pem_file,216 ssl_keyfile=cert_private_key_file,217 port=8001,218+ loop="asyncio",219 )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 task161-162-163-@pytest.fixture164-def restart(backend):165- async def asyncio_restart(server):166- await server.shutdown()167- await server.startup()168-169- if isinstance(backend, AsyncioBackend):170- return asyncio_restart171-172- # 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 NotImplementedError220+ server = TestServer(config=config)221+ yield from serve_in_thread(server)modified:tests/test_api.py-29 removed
1-import asyncio2-import functools3-1 import pytest2 3 import httpx4 5 9-def threadpool(func):10- """11- Our sync tests should run in separate thread to the uvicorn server.12- """13-14- @functools.wraps(func)15- async def wrapped(*args, **kwargs):16- nonlocal func17-18- loop = asyncio.get_event_loop()19- if kwargs:20- func = functools.partial(func, **kwargs)21- await loop.run_in_executor(None, func, *args)22-23- return pytest.mark.asyncio(wrapped)24-25-26-@threadpool6 def test_get(server):7 response = httpx.get("http://127.0.0.1:8000/")8 assert response.status_code == 2009 assert response.reason_phrase == "OK"10 assert response.text == "Hello, world!"11 assert response.http_version == "HTTP/1.1"12 13 35-@threadpool14 def test_post(server):15 response = httpx.post("http://127.0.0.1:8000/", data=b"Hello, world!")16 assert response.status_code == 20017 assert response.reason_phrase == "OK"18 19 42-@threadpool20 def test_post_byte_iterator(server):21 def data():22 yield b"Hello"23 yield b", "3 unmodified lines27 assert response.status_code == 20028 assert response.reason_phrase == "OK"29 30 54-@threadpool31 def test_options(server):32 response = httpx.options("http://127.0.0.1:8000/")33 assert response.status_code == 20034 assert response.reason_phrase == "OK"35 36 61-@threadpool37 def test_head(server):38 response = httpx.head("http://127.0.0.1:8000/")39 assert response.status_code == 20040 assert response.reason_phrase == "OK"41 42 68-@threadpool43 def test_put(server):44 response = httpx.put("http://127.0.0.1:8000/", data=b"Hello, world!")45 assert response.status_code == 20046 assert response.reason_phrase == "OK"47 48 75-@threadpool49 def test_patch(server):50 response = httpx.patch("http://127.0.0.1:8000/", data=b"Hello, world!")51 assert response.status_code == 20052 assert response.reason_phrase == "OK"53 54 82-@threadpool55 def test_delete(server):56 response = httpx.delete("http://127.0.0.1:8000/")57 assert response.status_code == 20058 assert response.reason_phrase == "OK"59 60 89-@threadpool61 def test_get_invalid_url(server):62 with pytest.raises(httpx.InvalidURL):63 httpx.get("invalid://example.org")modified:tests/test_concurrency.py+12 added-7 removed
18 unmodified lines19 ctx = SSLConfig().load_ssl_context_no_verify(HTTPVersionConfig())20 timeout = TimeoutConfig(5)21 22 stream = await backend.connect("127.0.0.1", 8001, None, timeout)23- assert stream.is_connection_dropped() is False24- assert stream.stream_writer.get_extra_info("cipher", default=None) is None23 26- stream = await backend.start_tls(stream, "127.0.0.1", ctx, timeout)27- assert stream.is_connection_dropped() is False28- assert stream.stream_writer.get_extra_info("cipher", default=None) is not None24+ try:25+ assert stream.is_connection_dropped() is False26+ assert stream.stream_writer.get_extra_info("cipher", default=None) is None27 28+ stream = await backend.start_tls(stream, "127.0.0.1", ctx, timeout)29+ assert stream.is_connection_dropped() is False30+ assert stream.stream_writer.get_extra_info("cipher", default=None) is not None31+30- await stream.write(b"GET / HTTP/1.1\r\n\r\n")31- assert (await stream.read(8192, timeout)).startswith(b"HTTP/1.1 200 OK\r\n")32+ await stream.write(b"GET / HTTP/1.1\r\n\r\n")33+ assert (await stream.read(8192, timeout)).startswith(b"HTTP/1.1 200 OK\r\n")34+35+ finally:36+ await stream.close()