Skip to content
Myr

Increase test coverage - take 2 (#1012)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Fix HttpError -> HTTPError typo * Increased test coverage * Increase coverage threshold * Reuse sync/async transport code in test_auth.py * Removed close_client check inside StreamContextManager It's never set as True when used in async * Reuse sync/async transport code in test_redirects.py

authored by Josep Cugat · committed by GitHub · parent 8c84210 · Browse files · 13 files+254 added−108 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

13 files+254 added−108 removed

  • tests:+250 added−102 removed
  • other:+4 added−6 removed

13 files+254 added−108 removed

modified:docs/quickstart.md+2 added-2 removed
247 unmodified lines
248404249>>> not_found.raise_for_status()250Traceback (most recent call last):251 File "/Users/tomchristie/GitHub/encode/httpcore/httpx/models.py", line 776, in raise_for_status252 raise HttpError(message)253httpx.exceptions.HttpError: 404 Not Found252 raise HTTPError(message)253httpx.HTTPError: 404 Not Found254```255256Any successful response codes will simply return `None` rather than raising an exception.257
196 unmodified lines
modified:httpx/_client.py-2 removed
1537 unmodified lines
1538 traceback: TracebackType = None,1539 ) -> None:1540 assert isinstance(self.client, AsyncClient)1541 await self.response.aclose()1542 if self.close_client:1543 await self.client.aclose()
modified:httpx/_models.py+1 added-1 removed
824 unmodified lines
825 return StatusCode.is_redirect(self.status_code) and "location" in self.headers826827 def raise_for_status(self) -> None:828 """829 Raise the `HttpError` if one occurred.829 Raise the `HTTPError` if one occurred.830 """831 message = (832 "{0.status_code} {error_type}: {0.reason_phrase} for url: {0.url}\n"833 "For more information check: https://httpstatuses.com/{0.status_code}"
369 unmodified lines
modified:scripts/coverage+1 added-1 removed
6 unmodified lines
7export SOURCE_FILES="httpx tests"89set -x1011${PREFIX}coverage report --show-missing --skip-covered --fail-under=9711${PREFIX}coverage report --show-missing --skip-covered --fail-under=99
modified:tests/client/test_auth.py+141 added-65 removed
7 unmodified lines
8from httpx import (9 URL,10 AsyncClient,11 Auth,12 Client,13 DigestAuth,14 Headers,15 ProtocolError,16 Request,
10 unmodified lines
27 return header_value.decode("ascii")28 return default293030class MockTransport(httpcore.AsyncHTTPTransport):31class MockTransport:32 def __init__(self, auth_header: bytes = b"", status_code: int = 200) -> None:33 self.auth_header = auth_header34 self.status_code = status_code3535 async def request(36 def _request(37 self,38 method: bytes,39 url: typing.Tuple[bytes, bytes, int, bytes],40 headers: typing.List[typing.Tuple[bytes, bytes]],
9 unmodified lines
50 response_stream = JSONStream({"auth": authorization})51 return b"HTTP/1.1", self.status_code, b"", response_headers, response_stream525354class AsyncMockTransport(MockTransport, httpcore.AsyncHTTPTransport):55 async def request(56 self, *args, **kwargs57 ) -> typing.Tuple[58 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream59 ]:60 return self._request(*args, **kwargs)616263class SyncMockTransport(MockTransport, httpcore.SyncHTTPTransport):64 def request(65 self, *args, **kwargs66 ) -> typing.Tuple[67 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream68 ]:69 return self._request(*args, **kwargs)707172class MockDigestAuthTransport(httpcore.AsyncHTTPTransport):73 def __init__(74 self,75 algorithm: str = "SHA-256",
56 unmodified lines
132 ]133 return b"HTTP/1.1", 401, b"", headers, ContentStream()134135136class RepeatAuth(Auth):137 """138 A mock authentication scheme that requires clients to send139 the request a fixed number of times, and then send a last request containing140 an aggregation of nonces that the server sent in 'WWW-Authenticate' headers141 of intermediate responses.142 """143144 requires_request_body = True145146 def __init__(self, repeat: int):147 self.repeat = repeat148149 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:150 nonces = []151152 for index in range(self.repeat):153 request.headers["Authorization"] = f"Repeat {index}"154 response = yield request155 nonces.append(response.headers["www-authenticate"])156157 key = ".".join(nonces)158 request.headers["Authorization"] = f"Repeat {key}"159 yield request160161162class ResponseBodyAuth(Auth):163 """164 A mock authentication scheme that requires clients to send an 'Authorization'165 header, then send back the contents of the response in the 'Authorization'166 header.167 """168169 requires_response_body = True170171 def __init__(self, token):172 self.token = token173174 def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:175 request.headers["Authorization"] = self.token176 response = yield request177 data = response.text178 request.headers["Authorization"] = data179 yield request180181182@pytest.mark.asyncio183async def test_basic_auth() -> None:184 url = "https://example.org/"185 auth = ("tomchristie", "password123")186122 client = AsyncClient(transport=MockTransport())187 client = AsyncClient(transport=AsyncMockTransport())188 response = await client.get(url, auth=auth)189190 assert response.status_code == 200191 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}
2 unmodified lines
194@pytest.mark.asyncio195async def test_basic_auth_in_url() -> None:196 url = "https://tomchristie:password123@example.org/"197133 client = AsyncClient(transport=MockTransport())198 client = AsyncClient(transport=AsyncMockTransport())199 response = await client.get(url)200201 assert response.status_code == 200202 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}
3 unmodified lines
206async def test_basic_auth_on_session() -> None:207 url = "https://example.org/"208 auth = ("tomchristie", "password123")209145 client = AsyncClient(transport=MockTransport(), auth=auth)210 client = AsyncClient(transport=AsyncMockTransport(), auth=auth)211 response = await client.get(url)212213 assert response.status_code == 200214 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}
6 unmodified lines
221 def auth(request: Request) -> Request:222 request.headers["Authorization"] = "Token 123"223 return request224160 client = AsyncClient(transport=MockTransport())225 client = AsyncClient(transport=AsyncMockTransport())226 response = await client.get(url, auth=auth)227228 assert response.status_code == 200229 assert response.json() == {"auth": "Token 123"}
3 unmodified lines
233async def test_netrc_auth() -> None:234 os.environ["NETRC"] = "tests/.netrc"235 url = "http://netrcexample.org"236172 client = AsyncClient(transport=MockTransport())237 client = AsyncClient(transport=AsyncMockTransport())238 response = await client.get(url)239240 assert response.status_code == 200241 assert response.json() == {
5 unmodified lines
247async def test_auth_header_has_priority_over_netrc() -> None:248 os.environ["NETRC"] = "tests/.netrc"249 url = "http://netrcexample.org"250186 client = AsyncClient(transport=MockTransport())251 client = AsyncClient(transport=AsyncMockTransport())252 response = await client.get(url, headers={"Authorization": "Override"})253254 assert response.status_code == 200255 assert response.json() == {"auth": "Override"}
3 unmodified lines
259async def test_trust_env_auth() -> None:260 os.environ["NETRC"] = "tests/.netrc"261 url = "http://netrcexample.org"262198 client = AsyncClient(transport=MockTransport(), trust_env=False)263 client = AsyncClient(transport=AsyncMockTransport(), trust_env=False)264 response = await client.get(url)265266 assert response.status_code == 200267 assert response.json() == {"auth": None}268204 client = AsyncClient(transport=MockTransport(), trust_env=True)269 client = AsyncClient(transport=AsyncMockTransport(), trust_env=True)270 response = await client.get(url)271272 assert response.status_code == 200273 assert response.json() == {
12 unmodified lines
286async def test_auth_hidden_header() -> None:287 url = "https://example.org/"288 auth = ("example-username", "example-password")289225 client = AsyncClient(transport=MockTransport())290 client = AsyncClient(transport=AsyncMockTransport())291 response = await client.get(url, auth=auth)292293 assert "'authorization': '[secure]'" in str(response.request.headers)294
1 unmodified line
296@pytest.mark.asyncio297async def test_auth_invalid_type() -> None:298 url = "https://example.org/"299 client = AsyncClient(235 transport=MockTransport(), auth="not a tuple, not a callable", # type: ignore300 transport=AsyncMockTransport(), auth="not a tuple, not a callable",301 )302 with pytest.raises(TypeError):303 await client.get(url)304
2 unmodified lines
307async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:308 url = "https://example.org/"309 auth = DigestAuth(username="tomchristie", password="password123")310246 client = AsyncClient(transport=MockTransport())311 client = AsyncClient(transport=AsyncMockTransport())312 response = await client.get(url, auth=auth)313314 assert response.status_code == 200315 assert response.json() == {"auth": None}
6 unmodified lines
322 auth = DigestAuth(username="tomchristie", password="password123")323 auth_header = b'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'324325 client = AsyncClient(261 transport=MockTransport(auth_header=auth_header, status_code=200)326 transport=AsyncMockTransport(auth_header=auth_header, status_code=200)327 )328 response = await client.get(url, auth=auth)329330 assert response.status_code == 200
5 unmodified lines
336async def test_digest_auth_401_response_without_digest_auth_header() -> None:337 url = "https://example.org/"338 auth = DigestAuth(username="tomchristie", password="password123")339275 client = AsyncClient(transport=MockTransport(auth_header=b"", status_code=401))340 client = AsyncClient(transport=AsyncMockTransport(auth_header=b"", status_code=401))341 response = await client.get(url, auth=auth)342343 assert response.status_code == 401344 assert response.json() == {"auth": None}
132 unmodified lines
477 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list478 ],479)480@pytest.mark.asyncio416async def test_digest_auth_raises_protocol_error_on_malformed_header(481async def test_async_digest_auth_raises_protocol_error_on_malformed_header(482 auth_header: bytes,483) -> None:484 url = "https://example.org/"485 auth = DigestAuth(username="tomchristie", password="password123")486 client = AsyncClient(422 transport=MockTransport(auth_header=auth_header, status_code=401)487 transport=AsyncMockTransport(auth_header=auth_header, status_code=401)488 )489490 with pytest.raises(ProtocolError):491 await client.get(url, auth=auth)492493494@pytest.mark.parametrize(495 "auth_header",496 [497 b'Digest realm="httpx@example.org", qop="auth"', # missing fields498 b'realm="httpx@example.org", qop="auth"', # not starting with Digest499 b'DigestZ realm="httpx@example.org", qop="auth"'500 b'qop="auth,auth-int",nonce="abc",opaque="xyz"',501 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list502 ],503)504def test_sync_digest_auth_raises_protocol_error_on_malformed_header(505 auth_header: bytes,506) -> None:507 url = "https://example.org/"508 auth = DigestAuth(username="tomchristie", password="password123")509 client = Client(510 transport=SyncMockTransport(auth_header=auth_header, status_code=401)511 )512513 with pytest.raises(ProtocolError):514 client.get(url, auth=auth)515516517@pytest.mark.asyncio430async def test_auth_history() -> None:518async def test_async_auth_history() -> None:519 """520 Test that intermediate requests sent as part of an authentication flow521 are recorded in the response history.522 """523 url = "https://example.org/"524 auth = RepeatAuth(repeat=2)525 client = AsyncClient(transport=AsyncMockTransport(auth_header=b"abc"))526436 class RepeatAuth(Auth):437 """438 A mock authentication scheme that requires clients to send439 the request a fixed number of times, and then send a last request containing440 an aggregation of nonces that the server sent in 'WWW-Authenticate' headers441 of intermediate responses.442 """527 response = await client.get(url, auth=auth)528 assert response.status_code == 200529 assert response.json() == {"auth": "Repeat abc.abc"}530444 requires_request_body = True531 assert len(response.history) == 2532 resp1, resp2 = response.history533 assert resp1.json() == {"auth": "Repeat 0"}534 assert resp2.json() == {"auth": "Repeat 1"}535446 def __init__(self, repeat: int):447 self.repeat = repeat536 assert len(resp2.history) == 1537 assert resp2.history == [resp1]538449 def auth_flow(450 self, request: Request451 ) -> typing.Generator[Request, Response, None]:452 nonces = []539 assert len(resp1.history) == 0540454 for index in range(self.repeat):455 request.headers["Authorization"] = f"Repeat {index}"456 response = yield request457 nonces.append(response.headers["www-authenticate"])541459 key = ".".join(nonces)460 request.headers["Authorization"] = f"Repeat {key}"461 yield request462542def test_sync_auth_history() -> None:543 """544 Test that intermediate requests sent as part of an authentication flow545 are recorded in the response history.546 """547 url = "https://example.org/"548 auth = RepeatAuth(repeat=2)465 client = AsyncClient(transport=MockTransport(auth_header=b"abc"))549 client = Client(transport=SyncMockTransport(auth_header=b"abc"))550467 response = await client.get(url, auth=auth)551 response = client.get(url, auth=auth)552 assert response.status_code == 200553 assert response.json() == {"auth": "Repeat abc.abc"}554555 assert len(response.history) == 2
10 unmodified lines
566@pytest.mark.asyncio567async def test_digest_auth_unavailable_streaming_body():568 url = "https://example.org/"569 auth = DigestAuth(username="tomchristie", password="password123")486 client = AsyncClient(transport=MockTransport())570 client = AsyncClient(transport=AsyncMockTransport())571572 async def streaming_body():573 yield b"Example request body" # pragma: nocover574
1 unmodified line
576 await client.post(url, data=streaming_body(), auth=auth)577578579@pytest.mark.asyncio496async def test_auth_reads_response_body() -> None:580async def test_async_auth_reads_response_body() -> None:581 """582 Test that we can read the response body in an auth flow if `requires_response_body`583 is set.584 """585 url = "https://example.org/"586 auth = ResponseBodyAuth("xyz")587 client = AsyncClient(transport=AsyncMockTransport())588502 class ResponseBodyAuth(Auth):503 """504 A mock authentication scheme that requires clients to send an 'Authorization'505 header, then send back the contents of the response in the 'Authorization'506 header.507 """589 response = await client.get(url, auth=auth)590 assert response.status_code == 200591 assert response.json() == {"auth": '{"auth": "xyz"}'}592509 requires_response_body = True593511 def __init__(self, token):512 self.token = token513514 def auth_flow(515 self, request: Request516 ) -> typing.Generator[Request, Response, None]:517 request.headers["Authorization"] = self.token518 response = yield request519 data = response.text520 request.headers["Authorization"] = data521 yield request522594def test_sync_auth_reads_response_body() -> None:595 """596 Test that we can read the response body in an auth flow if `requires_response_body`597 is set.598 """599 url = "https://example.org/"600 auth = ResponseBodyAuth("xyz")525 client = AsyncClient(transport=MockTransport())601 client = Client(transport=SyncMockTransport())602527 response = await client.get(url, auth=auth)603 response = client.get(url, auth=auth)604 assert response.status_code == 200605 assert response.json() == {"auth": '{"auth": "xyz"}'}
modified:tests/client/test_proxies.py+11 added
82 unmodified lines
83 else:84 assert transport.proxy_origin == httpx.URL(expected).raw[:3]858687@pytest.mark.asyncio88async def test_async_proxy_close():89 client = httpx.AsyncClient(proxies={"all": PROXY_URL})90 await client.aclose()919293def test_sync_proxy_close():94 client = httpx.Client(proxies={"all": PROXY_URL})95 client.close()969798def test_unsupported_proxy_scheme():99 with pytest.raises(ValueError):100 httpx.AsyncClient(proxies="ftp://127.0.0.1")101
29 unmodified lines
modified:tests/client/test_redirects.py+61 added-29 removed
6 unmodified lines
78from httpx import (9 URL,10 AsyncClient,11 Client,12 InvalidURL,13 NotRedirectResponse,14 RequestBodyUnavailable,15 TooManyRedirects,
9 unmodified lines
25 return header_value.decode("ascii")26 return default272828class MockTransport(httpcore.AsyncHTTPTransport):29 async def request(29class MockTransport:30 def _request(31 self,32 method: bytes,33 url: typing.Tuple[bytes, bytes, int, bytes],34 headers: typing.List[typing.Tuple[bytes, bytes]],
71 unmodified lines
106 content = ByteStream(json.dumps({"headers": headers_dict}).encode())107 return b"HTTP/1.1", 200, b"OK", [], content108109 elif path == b"/redirect_body":109 _ = b"".join([part async for part in stream])110 code = codes.PERMANENT_REDIRECT111 headers = [(b"location", b"/redirect_body_target")]112 return b"HTTP/1.1", code, b"Permanent Redirect", headers, ByteStream(b"")113114 elif path == b"/redirect_no_body":115 _ = b"".join([part async for part in stream])115 code = codes.SEE_OTHER116 headers = [(b"location", b"/redirect_body_target")]117 return b"HTTP/1.1", code, b"See Other", headers, ByteStream(b"")118119 elif path == b"/redirect_body_target":121 content = b"".join([part async for part in stream])120 content = b"".join(stream)121 headers_dict = dict(122 [(key.decode("ascii"), value.decode("ascii")) for key, value in headers]123 )124 body = ByteStream(
28 unmodified lines
153154 return b"HTTP/1.1", 200, b"OK", [], ByteStream(b"Hello, world!")155156157class AsyncMockTransport(MockTransport, httpcore.AsyncHTTPTransport):158 async def request(159 self, *args, **kwargs160 ) -> typing.Tuple[161 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream162 ]:163 return self._request(*args, **kwargs)164165166class SyncMockTransport(MockTransport, httpcore.SyncHTTPTransport):167 def request(168 self, *args, **kwargs169 ) -> typing.Tuple[170 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream171 ]:172 return self._request(*args, **kwargs)173174175@pytest.mark.usefixtures("async_environment")176async def test_no_redirect():160 client = AsyncClient(transport=MockTransport())177 client = AsyncClient(transport=AsyncMockTransport())178 url = "https://example.com/no_redirect"179 response = await client.get(url)180 assert response.status_code == 200181 with pytest.raises(NotRedirectResponse):
1 unmodified line
183184185@pytest.mark.usefixtures("async_environment")186async def test_redirect_301():170 client = AsyncClient(transport=MockTransport())187 client = AsyncClient(transport=AsyncMockTransport())188 response = await client.post("https://example.org/redirect_301")189 assert response.status_code == codes.OK190 assert response.url == URL("https://example.org/")191 assert len(response.history) == 1192193194@pytest.mark.usefixtures("async_environment")195async def test_redirect_302():179 client = AsyncClient(transport=MockTransport())196 client = AsyncClient(transport=AsyncMockTransport())197 response = await client.post("https://example.org/redirect_302")198 assert response.status_code == codes.OK199 assert response.url == URL("https://example.org/")200 assert len(response.history) == 1201202203@pytest.mark.usefixtures("async_environment")204async def test_redirect_303():188 client = AsyncClient(transport=MockTransport())205 client = AsyncClient(transport=AsyncMockTransport())206 response = await client.get("https://example.org/redirect_303")207 assert response.status_code == codes.OK208 assert response.url == URL("https://example.org/")209 assert len(response.history) == 1210211212@pytest.mark.usefixtures("async_environment")213async def test_disallow_redirects():197 client = AsyncClient(transport=MockTransport())214 client = AsyncClient(transport=AsyncMockTransport())215 response = await client.post(216 "https://example.org/redirect_303", allow_redirects=False217 )218 assert response.status_code == codes.SEE_OTHER
9 unmodified lines
228229230@pytest.mark.usefixtures("async_environment")231async def test_relative_redirect():215 client = AsyncClient(transport=MockTransport())232 client = AsyncClient(transport=AsyncMockTransport())233 response = await client.get("https://example.org/relative_redirect")234 assert response.status_code == codes.OK235 assert response.url == URL("https://example.org/")236 assert len(response.history) == 1
1 unmodified line
238239@pytest.mark.usefixtures("async_environment")240async def test_malformed_redirect():241 # https://github.com/encode/httpx/issues/771225 client = AsyncClient(transport=MockTransport())242 client = AsyncClient(transport=AsyncMockTransport())243 response = await client.get("http://example.org/malformed_redirect")244 assert response.status_code == codes.OK245 assert response.url == URL("https://example.org/")246 assert len(response.history) == 1247248249@pytest.mark.usefixtures("async_environment")250async def test_no_scheme_redirect():234 client = AsyncClient(transport=MockTransport())251 client = AsyncClient(transport=AsyncMockTransport())252 response = await client.get("https://example.org/no_scheme_redirect")253 assert response.status_code == codes.OK254 assert response.url == URL("https://example.org/")255 assert len(response.history) == 1256257258@pytest.mark.usefixtures("async_environment")259async def test_fragment_redirect():243 client = AsyncClient(transport=MockTransport())260 client = AsyncClient(transport=AsyncMockTransport())261 response = await client.get("https://example.org/relative_redirect#fragment")262 assert response.status_code == codes.OK263 assert response.url == URL("https://example.org/#fragment")264 assert len(response.history) == 1265266267@pytest.mark.usefixtures("async_environment")268async def test_multiple_redirects():252 client = AsyncClient(transport=MockTransport())269 client = AsyncClient(transport=AsyncMockTransport())270 response = await client.get("https://example.org/multiple_redirects?count=20")271 assert response.status_code == codes.OK272 assert response.url == URL("https://example.org/multiple_redirects")273 assert len(response.history) == 20
7 unmodified lines
281 assert len(response.history[1].history) == 1282283284@pytest.mark.usefixtures("async_environment")268async def test_too_many_redirects():269 client = AsyncClient(transport=MockTransport())285async def test_async_too_many_redirects():286 client = AsyncClient(transport=AsyncMockTransport())287 with pytest.raises(TooManyRedirects):288 await client.get("https://example.org/multiple_redirects?count=21")289290291@pytest.mark.usefixtures("async_environment")275async def test_too_many_redirects_calling_next():276 client = AsyncClient(transport=MockTransport())292async def test_async_too_many_redirects_calling_next():293 client = AsyncClient(transport=AsyncMockTransport())294 url = "https://example.org/multiple_redirects?count=21"295 response = await client.get(url, allow_redirects=False)296 with pytest.raises(TooManyRedirects):297 while response.is_redirect:298 response = await response.anext()299300301def test_sync_too_many_redirects():302 client = Client(transport=SyncMockTransport())303 with pytest.raises(TooManyRedirects):304 client.get("https://example.org/multiple_redirects?count=21")305306307def test_sync_too_many_redirects_calling_next():308 client = Client(transport=SyncMockTransport())309 url = "https://example.org/multiple_redirects?count=21"310 response = client.get(url, allow_redirects=False)311 with pytest.raises(TooManyRedirects):312 while response.is_redirect:313 response = response.call_next()314315316@pytest.mark.usefixtures("async_environment")317async def test_redirect_loop():286 client = AsyncClient(transport=MockTransport())318 client = AsyncClient(transport=AsyncMockTransport())319 with pytest.raises(TooManyRedirects):320 await client.get("https://example.org/redirect_loop")321322323@pytest.mark.usefixtures("async_environment")324async def test_cross_domain_redirect():293 client = AsyncClient(transport=MockTransport())325 client = AsyncClient(transport=AsyncMockTransport())326 url = "https://example.com/cross_domain"327 headers = {"Authorization": "abc"}328 response = await client.get(url, headers=headers)329 assert response.url == URL("https://example.org/cross_domain_target")
1 unmodified line
331332333@pytest.mark.usefixtures("async_environment")334async def test_same_domain_redirect():303 client = AsyncClient(transport=MockTransport())335 client = AsyncClient(transport=AsyncMockTransport())336 url = "https://example.org/cross_domain"337 headers = {"Authorization": "abc"}338 response = await client.get(url, headers=headers)339 assert response.url == URL("https://example.org/cross_domain_target")
4 unmodified lines
344async def test_body_redirect():345 """346 A 308 redirect should preserve the request body.347 """316 client = AsyncClient(transport=MockTransport())348 client = AsyncClient(transport=AsyncMockTransport())349 url = "https://example.org/redirect_body"350 data = b"Example request body"351 response = await client.post(url, data=data)352 assert response.url == URL("https://example.org/redirect_body_target")
5 unmodified lines
358async def test_no_body_redirect():359 """360 A 303 redirect should remove the request body.361 """330 client = AsyncClient(transport=MockTransport())362 client = AsyncClient(transport=AsyncMockTransport())363 url = "https://example.org/redirect_no_body"364 data = b"Example request body"365 response = await client.post(url, data=data)366 assert response.url == URL("https://example.org/redirect_body_target")
2 unmodified lines
369370371@pytest.mark.usefixtures("async_environment")372async def test_can_stream_if_no_redirect():341 client = AsyncClient(transport=MockTransport())373 client = AsyncClient(transport=AsyncMockTransport())374 url = "https://example.org/redirect_301"375 async with client.stream("GET", url, allow_redirects=False) as response:376 assert not response.is_closed377 assert response.status_code == codes.MOVED_PERMANENTLY
1 unmodified line
379380381@pytest.mark.usefixtures("async_environment")382async def test_cannot_redirect_streaming_body():351 client = AsyncClient(transport=MockTransport())383 client = AsyncClient(transport=AsyncMockTransport())384 url = "https://example.org/redirect_body"385386 async def streaming_body():355 yield b"Example request body"387 yield b"Example request body" # pragma: nocover388389 with pytest.raises(RequestBodyUnavailable):390 await client.post(url, data=streaming_body())391392393@pytest.mark.usefixtures("async_environment")394async def test_cross_subdomain_redirect():363 client = AsyncClient(transport=MockTransport())395 client = AsyncClient(transport=AsyncMockTransport())396 url = "https://example.com/cross_subdomain"397 response = await client.get(url)398 assert response.url == URL("https://www.example.org/cross_subdomain")399
78 unmodified lines
478479480@pytest.mark.usefixtures("async_environment")481async def test_redirect_custom_scheme():450 client = AsyncClient(transport=MockTransport())482 client = AsyncClient(transport=AsyncMockTransport())483 with pytest.raises(InvalidURL) as e:484 await client.post("https://example.org/redirect_custom_scheme")485 assert str(e.value) == 'Scheme "market" not supported.'
modified:tests/models/test_url.py+8 added
195 unmodified lines
196 origin = Origin("https://example.com:8080")197 assert str(origin) == "Origin(scheme='https' host='example.com' port=8080)"198199200def test_origin_equal():201 origin1 = Origin("https://example.com")202 origin2 = Origin("https://example.com")203 assert origin1 is not origin2204 assert origin1 == origin2205 assert len({origin1, origin2}) == 1206207208def test_url_copywith_for_authority():209 copy_with_kwargs = {210 "username": "username",211 "password": "password",
8 unmodified lines
modified:tests/concurrency.py+1 added-1 removed
8 unmodified lines
91011async def sleep(seconds: float) -> None:12 if sniffio.current_async_library() == "trio":13 await trio.sleep(seconds)13 await trio.sleep(seconds) # pragma: nocover14 else:15 await asyncio.sleep(seconds)
modified:tests/conftest.py+2 added-2 removed
231 unmodified lines
232 loop.create_task(self.watch_restarts()),233 }234 await asyncio.wait(tasks)235236 async def restart(self) -> None:236 async def restart(self) -> None: # pragma: nocover237 # This coroutine may be called from a different thread than the one the238 # server is running on, and from an async environment that's not asyncio.239 # For this reason, we use an event to coordinate with the server240 # instead of calling shutdown()/startup() directly, and should not make
2 unmodified lines
243 self.restart_requested.set()244 while not self.started:245 await sleep(0.2)246247 async def watch_restarts(self):247 async def watch_restarts(self): # pragma: nocover248 while True:249 if self.should_exit:250 return251
42 unmodified lines
modified:tests/test_asgi.py+11 added-2 removed
1from functools import partial23import pytest45import httpx6
19 unmodified lines
26 more_body = message.get("more_body", False)27 await send({"type": "http.response.body", "body": body, "more_body": more_body})282928async def raise_exc(scope, receive, send):29 raise ValueError()30async def raise_exc(scope, receive, send, exc=ValueError):31 raise exc()323334async def raise_exc_after_response(scope, receive, send):35 status = 200
28 unmodified lines
64 await client.get("http://www.example.org/")656667@pytest.mark.asyncio68async def test_asgi_http_error():69 client = httpx.AsyncClient(app=partial(raise_exc, exc=httpx.HTTPError))70 with pytest.raises(httpx.HTTPError):71 await client.get("http://www.example.org/")727374@pytest.mark.asyncio75async def test_asgi_exc_after_response():76 client = httpx.AsyncClient(app=raise_exc_after_response)77 with pytest.raises(ValueError):78 await client.get("http://www.example.org/")
32 unmodified lines
modified:tests/test_utils.py+5 added
65 unmodified lines
66 )67 assert netrc_info.get_credentials("netrcexample.org") == expected_credentials686970def test_get_netrc_unknown():71 netrc_info = NetRCInfo(["tests/.netrc"])72 assert netrc_info.get_credentials("nonexistant.org") is None737475@pytest.mark.parametrize(76 "value, expected",77 (78 (
212 unmodified lines
modified:tests/test_wsgi.py+10 added-3 removed
1import sys2from functools import partial34import pytest56import httpx
44 unmodified lines
5152 return output_generator(f=environ["wsgi.input"])535454def raise_exc(environ, start_response):55def raise_exc(environ, start_response, exc=ValueError):56 status = "500 Server Error"57 output = b"Nope!"5859 response_headers = [60 ("Content-type", "text/plain"),61 ]6263 try:63 raise ValueError()64 except ValueError:64 raise exc()65 except exc:66 exc_info = sys.exc_info()67 start_response(status, response_headers, exc_info=exc_info)6869 return [output]
25 unmodified lines
95 with pytest.raises(ValueError):96 client.get("http://www.example.org/")979899def test_wsgi_http_error():100 client = httpx.Client(app=partial(raise_exc, exc=httpx.HTTPError))101 with pytest.raises(httpx.HTTPError):102 client.get("http://www.example.org/")103104105def test_wsgi_generator():106 output = [b"", b"", b"Some content", b" and more content"]107 client = httpx.Client(app=application_factory(output))108 response = client.get("http://www.example.org/")
10 unmodified lines