Skip to content
Myr

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

7 files+120 added−130 removed

modified:httpx/concurrency/asyncio.py+1 added-1 removed
111 unmodified lines
112 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 lines
modified:tests/client/test_client.py-33 removed
1import asyncio2import functools31import pytest23import httpx459def threadpool(func):10 """11 Our sync tests should run in separate thread to the uvicorn server.12 """1314 @functools.wraps(func)15 async def wrapped(*args, **kwargs):16 nonlocal func1718 loop = asyncio.get_event_loop()19 if kwargs:20 func = functools.partial(func, **kwargs)21 await loop.run_in_executor(None, func, *args)2223 return pytest.mark.asyncio(wrapped)242526@threadpool6def test_get(server):7 url = "http://127.0.0.1:8000/"8 with httpx.Client() as http:9 response = http.get(url)
8 unmodified lines
18 assert response.is_redirect is False19 assert repr(response) == "<Response [200 OK]>"202143@threadpool22def 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"272851@threadpool29def 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"343559@threadpool36def 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!"424368@threadpool44def 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 == 200
2 unmodified lines
50 body += chunk51 assert body == b"Hello, world!"525379@threadpool54def 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 == 200
3 unmodified lines
61 assert body == b"Hello, world!"62 response.close() # TODO: should Response be available as context managers?636491@threadpool65def 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 lines
75 else:76 assert response.raise_for_status() is None7778106@threadpool79def 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"8485114@threadpool86def 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"9192122@threadpool93def 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"9899130@threadpool100def 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"105106138@threadpool107def 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"112113146@threadpool114def 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 lines
modified:tests/dispatch/test_connection_pools.py+2 added-2 removed
132 unmodified lines
133 async with httpx.ConnectionPool(backend=backend) as http:134 response = await http.request("GET", "http://127.0.0.1:8000/")135 await response.read()136137 # shutdown the server to close the keep-alive connection137 # Shutdown the server to close the keep-alive connection138 await restart(server)139140 response = await http.request("GET", "http://127.0.0.1:8000/")141 await response.read()
11 unmodified lines
153 async with httpx.ConnectionPool(backend=backend) as http:154 response = await http.request("GET", "http://127.0.0.1:8000/")155 await response.read()156157 # shutdown the server to close the keep-alive connection157 # Shutdown the server to close the keep-alive connection158 await restart(server)159160 response = await http.request("GET", "http://127.0.0.1:8000/")161 await response.read()
18 unmodified lines
modified:tests/dispatch/test_connections.py+23 added-21 removed
1from httpx import HTTPConnection234async 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!"101112async 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 == 200181920async 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!"313233async 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
1import asyncio2import threading3import time45import pytest6import trustme7from cryptography.hazmat.primitives.serialization import (
94 unmodified lines
102 )103 )104105104@pytest.fixture106SERVER_SCOPE = "session"107108109@pytest.fixture(scope=SERVER_SCOPE)110def example_cert():111 ca = CAWithPKEncryption()112 ca.issue_cert("example.org")113 return ca114115111@pytest.fixture116@pytest.fixture(scope=SERVER_SCOPE)117def cert_pem_file(example_cert):118 with example_cert.cert_pem.tempfile() as tmp:119 yield tmp120121117@pytest.fixture122@pytest.fixture(scope=SERVER_SCOPE)123def cert_private_key_file(example_cert):124 with example_cert.private_key_pem.tempfile() as tmp:125 yield tmp126127123@pytest.fixture128@pytest.fixture(scope=SERVER_SCOPE)129def cert_encrypted_private_key_file(example_cert):130 with example_cert.encrypted_private_key_pem.tempfile() as tmp:131 yield tmp132133134class 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 pass139140 async def serve(self, sockets=None):141 self.restart_requested = asyncio.Event()142143 loop = asyncio.get_event_loop()144 tasks = {145 loop.create_task(super().serve(sockets=sockets)),146 loop.create_task(self.watch_restarts()),147 }148149 await asyncio.wait(tasks)150151 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)161162 async def watch_restarts(self):163 while True:164 if self.should_exit:165 return166167 try:168 await asyncio.wait_for(self.restart_requested.wait(), timeout=0.1)169 except asyncio.TimeoutError:170 continue171172 self.restart_requested.clear()173 await self.shutdown()174 await self.startup()175176177@pytest.fixture130async def server():131 config = Config(app=app, lifespan="off")132 server = Server(config=config)133 task = asyncio.ensure_future(server.serve())178def restart(backend):179 """Restart the running server from an async test function.180181 This fixture deals with possible differences between the environment of the182 test function and that of the server.183 """184185 async def restart(server):186 await backend.run_in_threadpool(AsyncioBackend().run, server.restart)187188 return restart189190191def 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()201202143@pytest.fixture144async def https_server(cert_pem_file, cert_private_key_file):203@pytest.fixture(scope=SERVER_SCOPE)204def server():205 config = Config(app=app, lifespan="off", loop="asyncio")206 server = TestServer(config=config)207 yield from serve_in_thread(server)208209210@pytest.fixture(scope=SERVER_SCOPE)211def 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 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 NotImplementedError220 server = TestServer(config=config)221 yield from serve_in_thread(server)
modified:tests/test_api.py-29 removed
1import asyncio2import functools31import pytest23import httpx459def threadpool(func):10 """11 Our sync tests should run in separate thread to the uvicorn server.12 """1314 @functools.wraps(func)15 async def wrapped(*args, **kwargs):16 nonlocal func1718 loop = asyncio.get_event_loop()19 if kwargs:20 func = functools.partial(func, **kwargs)21 await loop.run_in_executor(None, func, *args)2223 return pytest.mark.asyncio(wrapped)242526@threadpool6def 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"121335@threadpool14def 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"181942@threadpool20def test_post_byte_iterator(server):21 def data():22 yield b"Hello"23 yield b", "
3 unmodified lines
27 assert response.status_code == 20028 assert response.reason_phrase == "OK"293054@threadpool31def test_options(server):32 response = httpx.options("http://127.0.0.1:8000/")33 assert response.status_code == 20034 assert response.reason_phrase == "OK"353661@threadpool37def test_head(server):38 response = httpx.head("http://127.0.0.1:8000/")39 assert response.status_code == 20040 assert response.reason_phrase == "OK"414268@threadpool43def 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"474875@threadpool49def 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"535482@threadpool55def test_delete(server):56 response = httpx.delete("http://127.0.0.1:8000/")57 assert response.status_code == 20058 assert response.reason_phrase == "OK"596089@threadpool61def 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 lines
19 ctx = SSLConfig().load_ssl_context_no_verify(HTTPVersionConfig())20 timeout = TimeoutConfig(5)2122 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 None2326 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 None2728 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 None3130 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")3435 finally:36 await stream.close()