test_redirects.py
This file
Path
tests/client/test_redirects.py
485 lines · 17.9 KiB · Python
Last changed by
Increase test coverage - take 2 (#1012)Josep Cugatbefore adoption620b067
History of this fileTake it
1import json2import typing3from urllib.parse import parse_qs45import httpcore6import pytest78from httpx import (9 URL,10 AsyncClient,11 Client,12 InvalidURL,13 NotRedirectResponse,14 RequestBodyUnavailable,15 TooManyRedirects,16 codes,17)18from httpx._content_streams import AsyncIteratorStream, ByteStream, ContentStream192021def get_header_value(headers, key, default=None):22 lookup = key.encode("ascii").lower()23 for header_key, header_value in headers:24 if header_key.lower() == lookup:25 return header_value.decode("ascii")26 return default272829class 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]],35 stream: ContentStream,36 timeout: typing.Dict[str, typing.Optional[float]] = None,37 ) -> typing.Tuple[38 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream39 ]:40 scheme, host, port, path = url41 path, _, query = path.partition(b"?")42 if path == b"/no_redirect":43 return b"HTTP/1.1", codes.OK, b"OK", [], ByteStream(b"")4445 elif path == b"/redirect_301":4647 async def body():48 yield b"<a href='https://example.org/'>here</a>"4950 status_code = codes.MOVED_PERMANENTLY51 headers = [(b"location", b"https://example.org/")]52 stream = AsyncIteratorStream(aiterator=body())53 return b"HTTP/1.1", status_code, b"Moved Permanently", headers, stream5455 elif path == b"/redirect_302":56 status_code = codes.FOUND57 headers = [(b"location", b"https://example.org/")]58 return b"HTTP/1.1", status_code, b"Found", headers, ByteStream(b"")5960 elif path == b"/redirect_303":61 status_code = codes.SEE_OTHER62 headers = [(b"location", b"https://example.org/")]63 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")6465 elif path == b"/relative_redirect":66 status_code = codes.SEE_OTHER67 headers = [(b"location", b"/")]68 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")6970 elif path == b"/malformed_redirect":71 status_code = codes.SEE_OTHER72 headers = [(b"location", b"https://:443/")]73 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")7475 elif path == b"/no_scheme_redirect":76 status_code = codes.SEE_OTHER77 headers = [(b"location", b"//example.org/")]78 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")7980 elif path == b"/multiple_redirects":81 params = parse_qs(query.decode("ascii"))82 count = int(params.get("count", "0")[0])83 redirect_count = count - 184 code = codes.SEE_OTHER if count else codes.OK85 phrase = b"See Other" if count else b"OK"86 location = b"/multiple_redirects"87 if redirect_count:88 location += b"?count=" + str(redirect_count).encode("ascii")89 headers = [(b"location", location)] if count else []90 return b"HTTP/1.1", code, phrase, headers, ByteStream(b"")9192 if path == b"/redirect_loop":93 code = codes.SEE_OTHER94 headers = [(b"location", b"/redirect_loop")]95 return b"HTTP/1.1", code, b"See Other", headers, ByteStream(b"")9697 elif path == b"/cross_domain":98 code = codes.SEE_OTHER99 headers = [(b"location", b"https://example.org/cross_domain_target")]100 return b"HTTP/1.1", code, b"See Other", headers, ByteStream(b"")101102 elif path == b"/cross_domain_target":103 headers_dict = dict(104 [(key.decode("ascii"), value.decode("ascii")) for key, value in headers]105 )106 content = ByteStream(json.dumps({"headers": headers_dict}).encode())107 return b"HTTP/1.1", 200, b"OK", [], content108109 elif path == b"/redirect_body":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 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":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(125 json.dumps({"body": content.decode(), "headers": headers_dict}).encode()126 )127 return b"HTTP/1.1", 200, b"OK", [], body128129 elif path == b"/cross_subdomain":130 host = get_header_value(headers, "host")131 if host != "www.example.org":132 headers = [(b"location", b"https://www.example.org/cross_subdomain")]133 return (134 b"HTTP/1.1",135 codes.PERMANENT_REDIRECT,136 b"Permanent Redirect",137 headers,138 ByteStream(b""),139 )140 else:141 return b"HTTP/1.1", 200, b"OK", [], ByteStream(b"Hello, world!")142143 elif path == b"/redirect_custom_scheme":144 status_code = codes.MOVED_PERMANENTLY145 headers = [(b"location", b"market://details?id=42")]146 return (147 b"HTTP/1.1",148 status_code,149 b"Moved Permanently",150 headers,151 ByteStream(b""),152 )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():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):182 await response.anext()183184185@pytest.mark.usefixtures("async_environment")186async def test_redirect_301():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():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():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():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_OTHER219 assert response.url == URL("https://example.org/redirect_303")220 assert response.is_redirect is True221 assert len(response.history) == 0222223 response = await response.anext()224 assert response.status_code == codes.OK225 assert response.url == URL("https://example.org/")226 assert response.is_redirect is False227 assert len(response.history) == 1228229230@pytest.mark.usefixtures("async_environment")231async def test_relative_redirect():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) == 1237238239@pytest.mark.usefixtures("async_environment")240async def test_malformed_redirect():241 # https://github.com/encode/httpx/issues/771242 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():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():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():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) == 20274 assert response.history[0].url == URL(275 "https://example.org/multiple_redirects?count=20"276 )277 assert response.history[1].url == URL(278 "https://example.org/multiple_redirects?count=19"279 )280 assert len(response.history[0].history) == 0281 assert len(response.history[1].history) == 1282283284@pytest.mark.usefixtures("async_environment")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")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():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():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")330 assert "authorization" not in response.json()["headers"]331332333@pytest.mark.usefixtures("async_environment")334async def test_same_domain_redirect():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")340 assert response.json()["headers"]["authorization"] == "abc"341342343@pytest.mark.usefixtures("async_environment")344async def test_body_redirect():345 """346 A 308 redirect should preserve the request body.347 """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")353 assert response.json()["body"] == "Example request body"354 assert "content-length" in response.json()["headers"]355356357@pytest.mark.usefixtures("async_environment")358async def test_no_body_redirect():359 """360 A 303 redirect should remove the request body.361 """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")367 assert response.json()["body"] == ""368 assert "content-length" not in response.json()["headers"]369370371@pytest.mark.usefixtures("async_environment")372async def test_can_stream_if_no_redirect():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_PERMANENTLY378 assert response.headers["location"] == "https://example.org/"379380381@pytest.mark.usefixtures("async_environment")382async def test_cannot_redirect_streaming_body():383 client = AsyncClient(transport=AsyncMockTransport())384 url = "https://example.org/redirect_body"385386 async def streaming_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():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")399400401class MockCookieTransport(httpcore.AsyncHTTPTransport):402 async def request(403 self,404 method: bytes,405 url: typing.Tuple[bytes, bytes, int, bytes],406 headers: typing.List[typing.Tuple[bytes, bytes]],407 stream: ContentStream,408 timeout: typing.Dict[str, typing.Optional[float]] = None,409 ) -> typing.Tuple[410 bytes, int, bytes, typing.List[typing.Tuple[bytes, bytes]], ContentStream411 ]:412 scheme, host, port, path = url413 if path == b"/":414 cookie = get_header_value(headers, "Cookie")415 if cookie is not None:416 content = b"Logged in"417 else:418 content = b"Not logged in"419 return b"HTTP/1.1", 200, b"OK", [], ByteStream(content)420421 elif path == b"/login":422 status_code = codes.SEE_OTHER423 headers = [424 (b"location", b"/"),425 (426 b"set-cookie",427 (428 b"session=eyJ1c2VybmFtZSI6ICJ0b21; path=/; Max-Age=1209600; "429 b"httponly; samesite=lax"430 ),431 ),432 ]433 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")434435 elif path == b"/logout":436 status_code = codes.SEE_OTHER437 headers = [438 (b"location", b"/"),439 (440 b"set-cookie",441 (442 b"session=null; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; "443 b"httponly; samesite=lax"444 ),445 ),446 ]447 return b"HTTP/1.1", status_code, b"See Other", headers, ByteStream(b"")448449450@pytest.mark.usefixtures("async_environment")451async def test_redirect_cookie_behavior():452 client = AsyncClient(transport=MockCookieTransport())453454 # The client is not logged in.455 response = await client.get("https://example.com/")456 assert response.url == "https://example.com/"457 assert response.text == "Not logged in"458459 # Login redirects to the homepage, setting a session cookie.460 response = await client.post("https://example.com/login")461 assert response.url == "https://example.com/"462 assert response.text == "Logged in"463464 # The client is logged in.465 response = await client.get("https://example.com/")466 assert response.url == "https://example.com/"467 assert response.text == "Logged in"468469 # Logout redirects to the homepage, expiring the session cookie.470 response = await client.post("https://example.com/logout")471 assert response.url == "https://example.com/"472 assert response.text == "Not logged in"473474 # The client is not logged in.475 response = await client.get("https://example.com/")476 assert response.url == "https://example.com/"477 assert response.text == "Not logged in"478479480@pytest.mark.usefixtures("async_environment")481async def test_redirect_custom_scheme():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.'