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
Provenance
- Commit
620b067- Tree
241269c- Author
Josep Cugat <jcugat@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
8c84210
13 files changed+254 added−108 removed
modified:docs/quickstart.md+2 added-2 removed
247 unmodified lines248 404249 >>> not_found.raise_for_status()250 Traceback (most recent call last):251 File "/Users/tomchristie/GitHub/encode/httpcore/httpx/models.py", line 776, in raise_for_status252- raise HttpError(message)253-httpx.exceptions.HttpError: 404 Not Found252+ raise HTTPError(message)253+httpx.HTTPError: 404 Not Found254 ```255 256 Any successful response codes will simply return `None` rather than raising an exception.257 196 unmodified linesmodified:httpx/_client.py-2 removed
1537 unmodified lines1538 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 lines825 return StatusCode.is_redirect(self.status_code) and "location" in self.headers826 827 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 linesmodified:scripts/coverage+1 added-1 removed
6 unmodified lines7 export SOURCE_FILES="httpx tests"8 9 set -x10 11-${PREFIX}coverage report --show-missing --skip-covered --fail-under=9711+${PREFIX}coverage report --show-missing --skip-covered --fail-under=99modified:tests/client/test_auth.py+141 added-65 removed
7 unmodified lines8 from httpx import (9 URL,10 AsyncClient,11 Auth,12+ Client,13 DigestAuth,14 Headers,15 ProtocolError,16 Request,10 unmodified lines27 return header_value.decode("ascii")28 return default29 30 30-class MockTransport(httpcore.AsyncHTTPTransport):31+class MockTransport:32 def __init__(self, auth_header: bytes = b"", status_code: int = 200) -> None:33 self.auth_header = auth_header34 self.status_code = status_code35 35- 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 lines50 response_stream = JSONStream({"auth": authorization})51 return b"HTTP/1.1", self.status_code, b"", response_headers, response_stream52 53 54+class 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)61+62+63+class 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)70+71+72 class MockDigestAuthTransport(httpcore.AsyncHTTPTransport):73 def __init__(74 self,75 algorithm: str = "SHA-256",56 unmodified lines132 ]133 return b"HTTP/1.1", 401, b"", headers, ContentStream()134 135 136+class 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+ """143+144+ requires_request_body = True145+146+ def __init__(self, repeat: int):147+ self.repeat = repeat148+149+ def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:150+ nonces = []151+152+ for index in range(self.repeat):153+ request.headers["Authorization"] = f"Repeat {index}"154+ response = yield request155+ nonces.append(response.headers["www-authenticate"])156+157+ key = ".".join(nonces)158+ request.headers["Authorization"] = f"Repeat {key}"159+ yield request160+161+162+class 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+ """168+169+ requires_response_body = True170+171+ def __init__(self, token):172+ self.token = token173+174+ 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 request180+181+182 @pytest.mark.asyncio183 async def test_basic_auth() -> None:184 url = "https://example.org/"185 auth = ("tomchristie", "password123")186 122- client = AsyncClient(transport=MockTransport())187+ client = AsyncClient(transport=AsyncMockTransport())188 response = await client.get(url, auth=auth)189 190 assert response.status_code == 200191 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}2 unmodified lines194 @pytest.mark.asyncio195 async def test_basic_auth_in_url() -> None:196 url = "https://tomchristie:password123@example.org/"197 133- client = AsyncClient(transport=MockTransport())198+ client = AsyncClient(transport=AsyncMockTransport())199 response = await client.get(url)200 201 assert response.status_code == 200202 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}3 unmodified lines206 async def test_basic_auth_on_session() -> None:207 url = "https://example.org/"208 auth = ("tomchristie", "password123")209 145- client = AsyncClient(transport=MockTransport(), auth=auth)210+ client = AsyncClient(transport=AsyncMockTransport(), auth=auth)211 response = await client.get(url)212 213 assert response.status_code == 200214 assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}6 unmodified lines221 def auth(request: Request) -> Request:222 request.headers["Authorization"] = "Token 123"223 return request224 160- client = AsyncClient(transport=MockTransport())225+ client = AsyncClient(transport=AsyncMockTransport())226 response = await client.get(url, auth=auth)227 228 assert response.status_code == 200229 assert response.json() == {"auth": "Token 123"}3 unmodified lines233 async def test_netrc_auth() -> None:234 os.environ["NETRC"] = "tests/.netrc"235 url = "http://netrcexample.org"236 172- client = AsyncClient(transport=MockTransport())237+ client = AsyncClient(transport=AsyncMockTransport())238 response = await client.get(url)239 240 assert response.status_code == 200241 assert response.json() == {5 unmodified lines247 async def test_auth_header_has_priority_over_netrc() -> None:248 os.environ["NETRC"] = "tests/.netrc"249 url = "http://netrcexample.org"250 186- client = AsyncClient(transport=MockTransport())251+ client = AsyncClient(transport=AsyncMockTransport())252 response = await client.get(url, headers={"Authorization": "Override"})253 254 assert response.status_code == 200255 assert response.json() == {"auth": "Override"}3 unmodified lines259 async def test_trust_env_auth() -> None:260 os.environ["NETRC"] = "tests/.netrc"261 url = "http://netrcexample.org"262 198- client = AsyncClient(transport=MockTransport(), trust_env=False)263+ client = AsyncClient(transport=AsyncMockTransport(), trust_env=False)264 response = await client.get(url)265 266 assert response.status_code == 200267 assert response.json() == {"auth": None}268 204- client = AsyncClient(transport=MockTransport(), trust_env=True)269+ client = AsyncClient(transport=AsyncMockTransport(), trust_env=True)270 response = await client.get(url)271 272 assert response.status_code == 200273 assert response.json() == {12 unmodified lines286 async def test_auth_hidden_header() -> None:287 url = "https://example.org/"288 auth = ("example-username", "example-password")289 225- client = AsyncClient(transport=MockTransport())290+ client = AsyncClient(transport=AsyncMockTransport())291 response = await client.get(url, auth=auth)292 293 assert "'authorization': '[secure]'" in str(response.request.headers)294 1 unmodified line296 @pytest.mark.asyncio297 async 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 lines307 async 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")310 246- client = AsyncClient(transport=MockTransport())311+ client = AsyncClient(transport=AsyncMockTransport())312 response = await client.get(url, auth=auth)313 314 assert response.status_code == 200315 assert response.json() == {"auth": None}6 unmodified lines322 auth = DigestAuth(username="tomchristie", password="password123")323 auth_header = b'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'324 325 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)329 330 assert response.status_code == 2005 unmodified lines336 async def test_digest_auth_401_response_without_digest_auth_header() -> None:337 url = "https://example.org/"338 auth = DigestAuth(username="tomchristie", password="password123")339 275- 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)342 343 assert response.status_code == 401344 assert response.json() == {"auth": None}132 unmodified lines477 b'Digest realm="httpx@example.org", qop="auth,au', # malformed fields list478 ],479 )480 @pytest.mark.asyncio416-async def test_digest_auth_raises_protocol_error_on_malformed_header(481+async 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 )489 490 with pytest.raises(ProtocolError):491 await client.get(url, auth=auth)492 493 494+@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+)504+def 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+ )512+513+ with pytest.raises(ProtocolError):514+ client.get(url, auth=auth)515+516+517 @pytest.mark.asyncio430-async def test_auth_history() -> None:518+async 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"))526 436- 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"}530 444- 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"}535 446- def __init__(self, repeat: int):447- self.repeat = repeat536+ assert len(resp2.history) == 1537+ assert resp2.history == [resp1]538 449- def auth_flow(450- self, request: Request451- ) -> typing.Generator[Request, Response, None]:452- nonces = []539+ assert len(resp1.history) == 0540 454- for index in range(self.repeat):455- request.headers["Authorization"] = f"Repeat {index}"456- response = yield request457- nonces.append(response.headers["www-authenticate"])541 459- key = ".".join(nonces)460- request.headers["Authorization"] = f"Repeat {key}"461- yield request462-542+def 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"))550 467- 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"}554 555 assert len(response.history) == 210 unmodified lines566 @pytest.mark.asyncio567 async 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())571 572 async def streaming_body():573 yield b"Example request body" # pragma: nocover574 1 unmodified line576 await client.post(url, data=streaming_body(), auth=auth)577 578 579 @pytest.mark.asyncio496-async def test_auth_reads_response_body() -> None:580+async 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())588 502- 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"}'}592 509- requires_response_body = True593 511- def __init__(self, token):512- self.token = token513-514- 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 request522-594+def 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())602 527- 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 lines83 else:84 assert transport.proxy_origin == httpx.URL(expected).raw[:3]85 86 87+@pytest.mark.asyncio88+async def test_async_proxy_close():89+ client = httpx.AsyncClient(proxies={"all": PROXY_URL})90+ await client.aclose()91+92+93+def test_sync_proxy_close():94+ client = httpx.Client(proxies={"all": PROXY_URL})95+ client.close()96+97+98 def test_unsupported_proxy_scheme():99 with pytest.raises(ValueError):100 httpx.AsyncClient(proxies="ftp://127.0.0.1")101 29 unmodified linesmodified:tests/client/test_redirects.py+61 added-29 removed
6 unmodified lines7 8 from httpx import (9 URL,10 AsyncClient,11+ Client,12 InvalidURL,13 NotRedirectResponse,14 RequestBodyUnavailable,15 TooManyRedirects,9 unmodified lines25 return header_value.decode("ascii")26 return default27 28 28-class MockTransport(httpcore.AsyncHTTPTransport):29- async def request(29+class 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 lines106 content = ByteStream(json.dumps({"headers": headers_dict}).encode())107 return b"HTTP/1.1", 200, b"OK", [], content108 109 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"")113 114 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"")118 119 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 lines153 154 return b"HTTP/1.1", 200, b"OK", [], ByteStream(b"Hello, world!")155 156 157+class 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)164+165+166+class 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)173+174+175 @pytest.mark.usefixtures("async_environment")176 async 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 line183 184 185 @pytest.mark.usefixtures("async_environment")186 async 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) == 1192 193 194 @pytest.mark.usefixtures("async_environment")195 async 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) == 1201 202 203 @pytest.mark.usefixtures("async_environment")204 async 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) == 1210 211 212 @pytest.mark.usefixtures("async_environment")213 async 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_OTHER9 unmodified lines228 229 230 @pytest.mark.usefixtures("async_environment")231 async 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) == 11 unmodified line238 239 @pytest.mark.usefixtures("async_environment")240 async 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) == 1247 248 249 @pytest.mark.usefixtures("async_environment")250 async 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) == 1256 257 258 @pytest.mark.usefixtures("async_environment")259 async 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) == 1265 266 267 @pytest.mark.usefixtures("async_environment")268 async 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) == 207 unmodified lines281 assert len(response.history[1].history) == 1282 283 284 @pytest.mark.usefixtures("async_environment")268-async def test_too_many_redirects():269- client = AsyncClient(transport=MockTransport())285+async 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")289 290 291 @pytest.mark.usefixtures("async_environment")275-async def test_too_many_redirects_calling_next():276- client = AsyncClient(transport=MockTransport())292+async 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()299 300 301+def 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")305+306+307+def 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()314+315+316 @pytest.mark.usefixtures("async_environment")317 async 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")321 322 323 @pytest.mark.usefixtures("async_environment")324 async 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 line331 332 333 @pytest.mark.usefixtures("async_environment")334 async 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 lines344 async 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 lines358 async 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 lines369 370 371 @pytest.mark.usefixtures("async_environment")372 async 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_PERMANENTLY1 unmodified line379 380 381 @pytest.mark.usefixtures("async_environment")382 async def test_cannot_redirect_streaming_body():351- client = AsyncClient(transport=MockTransport())383+ client = AsyncClient(transport=AsyncMockTransport())384 url = "https://example.org/redirect_body"385 386 async def streaming_body():355- yield b"Example request body"387+ yield b"Example request body" # pragma: nocover388 389 with pytest.raises(RequestBodyUnavailable):390 await client.post(url, data=streaming_body())391 392 393 @pytest.mark.usefixtures("async_environment")394 async 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 lines478 479 480 @pytest.mark.usefixtures("async_environment")481 async 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 lines196 origin = Origin("https://example.com:8080")197 assert str(origin) == "Origin(scheme='https' host='example.com' port=8080)"198 199 200+def 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}) == 1206+207+208 def test_url_copywith_for_authority():209 copy_with_kwargs = {210 "username": "username",211 "password": "password",8 unmodified linesmodified:tests/concurrency.py+1 added-1 removed
8 unmodified lines9 10 11 async 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 lines232 loop.create_task(self.watch_restarts()),233 }234 await asyncio.wait(tasks)235 236- 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 make2 unmodified lines243 self.restart_requested.set()244 while not self.started:245 await sleep(0.2)246 247- async def watch_restarts(self):247+ async def watch_restarts(self): # pragma: nocover248 while True:249 if self.should_exit:250 return251 42 unmodified linesmodified:tests/test_asgi.py+11 added-2 removed
1+from functools import partial2+3 import pytest4 5 import httpx6 19 unmodified lines26 more_body = message.get("more_body", False)27 await send({"type": "http.response.body", "body": body, "more_body": more_body})28 29 28-async def raise_exc(scope, receive, send):29- raise ValueError()30+async def raise_exc(scope, receive, send, exc=ValueError):31+ raise exc()32 33 34 async def raise_exc_after_response(scope, receive, send):35 status = 20028 unmodified lines64 await client.get("http://www.example.org/")65 66 67 @pytest.mark.asyncio68+async 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/")72+73+74+@pytest.mark.asyncio75 async 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 linesmodified:tests/test_utils.py+5 added
65 unmodified lines66 )67 assert netrc_info.get_credentials("netrcexample.org") == expected_credentials68 69 70+def test_get_netrc_unknown():71+ netrc_info = NetRCInfo(["tests/.netrc"])72+ assert netrc_info.get_credentials("nonexistant.org") is None73+74+75 @pytest.mark.parametrize(76 "value, expected",77 (78 (212 unmodified linesmodified:tests/test_wsgi.py+10 added-3 removed
1 import sys2+from functools import partial3 4 import pytest5 6 import httpx44 unmodified lines51 52 return output_generator(f=environ["wsgi.input"])53 54 54-def raise_exc(environ, start_response):55+def raise_exc(environ, start_response, exc=ValueError):56 status = "500 Server Error"57 output = b"Nope!"58 59 response_headers = [60 ("Content-type", "text/plain"),61 ]62 63 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)68 69 return [output]25 unmodified lines95 with pytest.raises(ValueError):96 client.get("http://www.example.org/")97 98 99+def 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/")103+104+105 def 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