test_responses.py
This file
Path
tests/test_responses.py
114 lines · 2.8 KiB · Python
Last changed by
Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
History of this fileTake it
1import pytest23import httpcore456class MockHTTP(httpcore.ConnectionPool):7 async def request(8 self, method, url, *, headers=(), body=b"", stream=False9 ) -> httpcore.Response:10 if stream:1112 async def streaming_body():13 yield b"Hello, "14 yield b"world!"1516 return httpcore.Response(200, body=streaming_body())17 return httpcore.Response(200, body=b"Hello, world!")181920http = MockHTTP()212223@pytest.mark.asyncio24async def test_request():25 response = await http.request("GET", "http://example.com")26 assert response.status_code == 20027 assert response.body == b"Hello, world!"28 assert response.is_closed293031@pytest.mark.asyncio32async def test_read_response():33 response = await http.request("GET", "http://example.com")3435 assert response.status_code == 20036 assert response.body == b"Hello, world!"37 assert response.is_closed3839 body = await response.read()4041 assert body == b"Hello, world!"42 assert response.body == b"Hello, world!"43 assert response.is_closed444546@pytest.mark.asyncio47async def test_stream_response():48 response = await http.request("GET", "http://example.com")4950 assert response.status_code == 20051 assert response.body == b"Hello, world!"52 assert response.is_closed5354 body = b""55 async for part in response.stream():56 body += part5758 assert body == b"Hello, world!"59 assert response.body == b"Hello, world!"60 assert response.is_closed616263@pytest.mark.asyncio64async def test_read_streaming_response():65 response = await http.request("GET", "http://example.com", stream=True)6667 assert response.status_code == 20068 assert not hasattr(response, "body")69 assert not response.is_closed7071 body = await response.read()7273 assert body == b"Hello, world!"74 assert response.body == b"Hello, world!"75 assert response.is_closed767778@pytest.mark.asyncio79async def test_stream_streaming_response():80 response = await http.request("GET", "http://example.com", stream=True)8182 assert response.status_code == 20083 assert not hasattr(response, "body")84 assert not response.is_closed8586 body = b""87 async for part in response.stream():88 body += part8990 assert body == b"Hello, world!"91 assert not hasattr(response, "body")92 assert response.is_closed939495@pytest.mark.asyncio96async def test_cannot_read_after_stream_consumed():97 response = await http.request("GET", "http://example.com", stream=True)9899 body = b""100 async for part in response.stream():101 body += part102103 with pytest.raises(httpcore.StreamConsumed):104 await response.read()105106107@pytest.mark.asyncio108async def test_cannot_read_after_response_closed():109 response = await http.request("GET", "http://example.com", stream=True)110111 await response.close()112113 with pytest.raises(httpcore.ResponseClosed):114 await response.read()