test_redirects.py
This file
Path
tests/client/test_redirects.py
427 lines · 16.3 KiB · Python
Last changed by
Transport API as plain `request -> response` method. (#1840)Tom Christiebefore adoptionff9813e
History of this fileTake it
1import pytest23import httpx456def redirects(request: httpx.Request) -> httpx.Response:7 if request.url.scheme not in ("http", "https"):8 raise httpx.UnsupportedProtocol(f"Scheme {request.url.scheme!r} not supported.")910 if request.url.path == "/redirect_301":11 status_code = httpx.codes.MOVED_PERMANENTLY12 content = b"<a href='https://example.org/'>here</a>"13 headers = {"location": "https://example.org/"}14 return httpx.Response(status_code, headers=headers, content=content)1516 elif request.url.path == "/redirect_302":17 status_code = httpx.codes.FOUND18 headers = {"location": "https://example.org/"}19 return httpx.Response(status_code, headers=headers)2021 elif request.url.path == "/redirect_303":22 status_code = httpx.codes.SEE_OTHER23 headers = {"location": "https://example.org/"}24 return httpx.Response(status_code, headers=headers)2526 elif request.url.path == "/relative_redirect":27 status_code = httpx.codes.SEE_OTHER28 headers = {"location": "/"}29 return httpx.Response(status_code, headers=headers)3031 elif request.url.path == "/malformed_redirect":32 status_code = httpx.codes.SEE_OTHER33 headers = {"location": "https://:443/"}34 return httpx.Response(status_code, headers=headers)3536 elif request.url.path == "/invalid_redirect":37 status_code = httpx.codes.SEE_OTHER38 raw_headers = [(b"location", "https://😇/".encode("utf-8"))]39 return httpx.Response(status_code, headers=raw_headers)4041 elif request.url.path == "/no_scheme_redirect":42 status_code = httpx.codes.SEE_OTHER43 headers = {"location": "//example.org/"}44 return httpx.Response(status_code, headers=headers)4546 elif request.url.path == "/multiple_redirects":47 params = httpx.QueryParams(request.url.query)48 count = int(params.get("count", "0"))49 redirect_count = count - 150 status_code = httpx.codes.SEE_OTHER if count else httpx.codes.OK51 if count:52 location = "/multiple_redirects"53 if redirect_count:54 location += f"?count={redirect_count}"55 headers = {"location": location}56 else:57 headers = {}58 return httpx.Response(status_code, headers=headers)5960 if request.url.path == "/redirect_loop":61 status_code = httpx.codes.SEE_OTHER62 headers = {"location": "/redirect_loop"}63 return httpx.Response(status_code, headers=headers)6465 elif request.url.path == "/cross_domain":66 status_code = httpx.codes.SEE_OTHER67 headers = {"location": "https://example.org/cross_domain_target"}68 return httpx.Response(status_code, headers=headers)6970 elif request.url.path == "/cross_domain_target":71 status_code = httpx.codes.OK72 data = {73 "body": request.content.decode("ascii"),74 "headers": dict(request.headers),75 }76 return httpx.Response(status_code, json=data)7778 elif request.url.path == "/redirect_body":79 status_code = httpx.codes.PERMANENT_REDIRECT80 headers = {"location": "/redirect_body_target"}81 return httpx.Response(status_code, headers=headers)8283 elif request.url.path == "/redirect_no_body":84 status_code = httpx.codes.SEE_OTHER85 headers = {"location": "/redirect_body_target"}86 return httpx.Response(status_code, headers=headers)8788 elif request.url.path == "/redirect_body_target":89 data = {90 "body": request.content.decode("ascii"),91 "headers": dict(request.headers),92 }93 return httpx.Response(200, json=data)9495 elif request.url.path == "/cross_subdomain":96 if request.headers["Host"] != "www.example.org":97 status_code = httpx.codes.PERMANENT_REDIRECT98 headers = {"location": "https://www.example.org/cross_subdomain"}99 return httpx.Response(status_code, headers=headers)100 else:101 return httpx.Response(200, text="Hello, world!")102103 elif request.url.path == "/redirect_custom_scheme":104 status_code = httpx.codes.MOVED_PERMANENTLY105 headers = {"location": "market://details?id=42"}106 return httpx.Response(status_code, headers=headers)107108 if request.method == "HEAD":109 return httpx.Response(200)110111 return httpx.Response(200, html="<html><body>Hello, world!</body></html>")112113114def test_redirect_301():115 client = httpx.Client(transport=httpx.MockTransport(redirects))116 response = client.post("https://example.org/redirect_301", follow_redirects=True)117 assert response.status_code == httpx.codes.OK118 assert response.url == "https://example.org/"119 assert len(response.history) == 1120121122def test_redirect_302():123 client = httpx.Client(transport=httpx.MockTransport(redirects))124 response = client.post("https://example.org/redirect_302", follow_redirects=True)125 assert response.status_code == httpx.codes.OK126 assert response.url == "https://example.org/"127 assert len(response.history) == 1128129130def test_redirect_303():131 client = httpx.Client(transport=httpx.MockTransport(redirects))132 response = client.get("https://example.org/redirect_303", follow_redirects=True)133 assert response.status_code == httpx.codes.OK134 assert response.url == "https://example.org/"135 assert len(response.history) == 1136137138def test_next_request():139 client = httpx.Client(transport=httpx.MockTransport(redirects))140 request = client.build_request("POST", "https://example.org/redirect_303")141 response = client.send(request, follow_redirects=False)142 assert response.status_code == httpx.codes.SEE_OTHER143 assert response.url == "https://example.org/redirect_303"144 assert response.next_request is not None145146 response = client.send(response.next_request, follow_redirects=False)147 assert response.status_code == httpx.codes.OK148 assert response.url == "https://example.org/"149 assert response.next_request is None150151152@pytest.mark.usefixtures("async_environment")153async def test_async_next_request():154 async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client:155 request = client.build_request("POST", "https://example.org/redirect_303")156 response = await client.send(request, follow_redirects=False)157 assert response.status_code == httpx.codes.SEE_OTHER158 assert response.url == "https://example.org/redirect_303"159 assert response.next_request is not None160161 response = await client.send(response.next_request, follow_redirects=False)162 assert response.status_code == httpx.codes.OK163 assert response.url == "https://example.org/"164 assert response.next_request is None165166167def test_head_redirect():168 """169 Contrary to Requests, redirects remain enabled by default for HEAD requests.170 """171 client = httpx.Client(transport=httpx.MockTransport(redirects))172 response = client.head("https://example.org/redirect_302", follow_redirects=True)173 assert response.status_code == httpx.codes.OK174 assert response.url == "https://example.org/"175 assert response.request.method == "HEAD"176 assert len(response.history) == 1177 assert response.text == ""178179180def test_relative_redirect():181 client = httpx.Client(transport=httpx.MockTransport(redirects))182 response = client.get(183 "https://example.org/relative_redirect", follow_redirects=True184 )185 assert response.status_code == httpx.codes.OK186 assert response.url == "https://example.org/"187 assert len(response.history) == 1188189190def test_malformed_redirect():191 # https://github.com/encode/httpx/issues/771192 client = httpx.Client(transport=httpx.MockTransport(redirects))193 response = client.get(194 "http://example.org/malformed_redirect", follow_redirects=True195 )196 assert response.status_code == httpx.codes.OK197 assert response.url == "https://example.org:443/"198 assert len(response.history) == 1199200201def test_invalid_redirect():202 client = httpx.Client(transport=httpx.MockTransport(redirects))203 with pytest.raises(httpx.RemoteProtocolError):204 client.get("http://example.org/invalid_redirect", follow_redirects=True)205206207def test_no_scheme_redirect():208 client = httpx.Client(transport=httpx.MockTransport(redirects))209 response = client.get(210 "https://example.org/no_scheme_redirect", follow_redirects=True211 )212 assert response.status_code == httpx.codes.OK213 assert response.url == "https://example.org/"214 assert len(response.history) == 1215216217def test_fragment_redirect():218 client = httpx.Client(transport=httpx.MockTransport(redirects))219 response = client.get(220 "https://example.org/relative_redirect#fragment", follow_redirects=True221 )222 assert response.status_code == httpx.codes.OK223 assert response.url == "https://example.org/#fragment"224 assert len(response.history) == 1225226227def test_multiple_redirects():228 client = httpx.Client(transport=httpx.MockTransport(redirects))229 response = client.get(230 "https://example.org/multiple_redirects?count=20", follow_redirects=True231 )232 assert response.status_code == httpx.codes.OK233 assert response.url == "https://example.org/multiple_redirects"234 assert len(response.history) == 20235 assert response.history[0].url == "https://example.org/multiple_redirects?count=20"236 assert response.history[1].url == "https://example.org/multiple_redirects?count=19"237 assert len(response.history[0].history) == 0238 assert len(response.history[1].history) == 1239240241@pytest.mark.usefixtures("async_environment")242async def test_async_too_many_redirects():243 async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client:244 with pytest.raises(httpx.TooManyRedirects):245 await client.get(246 "https://example.org/multiple_redirects?count=21", follow_redirects=True247 )248249250def test_sync_too_many_redirects():251 client = httpx.Client(transport=httpx.MockTransport(redirects))252 with pytest.raises(httpx.TooManyRedirects):253 client.get(254 "https://example.org/multiple_redirects?count=21", follow_redirects=True255 )256257258def test_redirect_loop():259 client = httpx.Client(transport=httpx.MockTransport(redirects))260 with pytest.raises(httpx.TooManyRedirects):261 client.get("https://example.org/redirect_loop", follow_redirects=True)262263264def test_cross_domain_redirect_with_auth_header():265 client = httpx.Client(transport=httpx.MockTransport(redirects))266 url = "https://example.com/cross_domain"267 headers = {"Authorization": "abc"}268 response = client.get(url, headers=headers, follow_redirects=True)269 assert response.url == "https://example.org/cross_domain_target"270 assert "authorization" not in response.json()["headers"]271272273def test_cross_domain_redirect_with_auth():274 client = httpx.Client(transport=httpx.MockTransport(redirects))275 url = "https://example.com/cross_domain"276 response = client.get(url, auth=("user", "pass"), follow_redirects=True)277 assert response.url == "https://example.org/cross_domain_target"278 assert "authorization" not in response.json()["headers"]279280281def test_same_domain_redirect():282 client = httpx.Client(transport=httpx.MockTransport(redirects))283 url = "https://example.org/cross_domain"284 headers = {"Authorization": "abc"}285 response = client.get(url, headers=headers, follow_redirects=True)286 assert response.url == "https://example.org/cross_domain_target"287 assert response.json()["headers"]["authorization"] == "abc"288289290def test_body_redirect():291 """292 A 308 redirect should preserve the request body.293 """294 client = httpx.Client(transport=httpx.MockTransport(redirects))295 url = "https://example.org/redirect_body"296 content = b"Example request body"297 response = client.post(url, content=content, follow_redirects=True)298 assert response.url == "https://example.org/redirect_body_target"299 assert response.json()["body"] == "Example request body"300 assert "content-length" in response.json()["headers"]301302303def test_no_body_redirect():304 """305 A 303 redirect should remove the request body.306 """307 client = httpx.Client(transport=httpx.MockTransport(redirects))308 url = "https://example.org/redirect_no_body"309 content = b"Example request body"310 response = client.post(url, content=content, follow_redirects=True)311 assert response.url == "https://example.org/redirect_body_target"312 assert response.json()["body"] == ""313 assert "content-length" not in response.json()["headers"]314315316def test_can_stream_if_no_redirect():317 client = httpx.Client(transport=httpx.MockTransport(redirects))318 url = "https://example.org/redirect_301"319 with client.stream("GET", url, follow_redirects=False) as response:320 pass321 assert response.status_code == httpx.codes.MOVED_PERMANENTLY322 assert response.headers["location"] == "https://example.org/"323324325class ConsumeBodyTransport(httpx.MockTransport):326 def handle_request(self, request: httpx.Request) -> httpx.Response:327 assert isinstance(request.stream, httpx.SyncByteStream)328 [_ for _ in request.stream]329 return self.handler(request)330331332def test_cannot_redirect_streaming_body():333 client = httpx.Client(transport=ConsumeBodyTransport(redirects))334 url = "https://example.org/redirect_body"335336 def streaming_body():337 yield b"Example request body" # pragma: nocover338339 with pytest.raises(httpx.StreamConsumed):340 client.post(url, content=streaming_body(), follow_redirects=True)341342343def test_cross_subdomain_redirect():344 client = httpx.Client(transport=httpx.MockTransport(redirects))345 url = "https://example.com/cross_subdomain"346 response = client.get(url, follow_redirects=True)347 assert response.url == "https://www.example.org/cross_subdomain"348349350def cookie_sessions(request: httpx.Request) -> httpx.Response:351 if request.url.path == "/":352 cookie = request.headers.get("Cookie")353 if cookie is not None:354 content = b"Logged in"355 else:356 content = b"Not logged in"357 return httpx.Response(200, content=content)358359 elif request.url.path == "/login":360 status_code = httpx.codes.SEE_OTHER361 headers = {362 "location": "/",363 "set-cookie": (364 "session=eyJ1c2VybmFtZSI6ICJ0b21; path=/; Max-Age=1209600; "365 "httponly; samesite=lax"366 ),367 }368 return httpx.Response(status_code, headers=headers)369370 else:371 assert request.url.path == "/logout"372 status_code = httpx.codes.SEE_OTHER373 headers = {374 "location": "/",375 "set-cookie": (376 "session=null; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; "377 "httponly; samesite=lax"378 ),379 }380 return httpx.Response(status_code, headers=headers)381382383def test_redirect_cookie_behavior():384 client = httpx.Client(385 transport=httpx.MockTransport(cookie_sessions), follow_redirects=True386 )387388 # The client is not logged in.389 response = client.get("https://example.com/")390 assert response.url == "https://example.com/"391 assert response.text == "Not logged in"392393 # Login redirects to the homepage, setting a session cookie.394 response = client.post("https://example.com/login")395 assert response.url == "https://example.com/"396 assert response.text == "Logged in"397398 # The client is logged in.399 response = client.get("https://example.com/")400 assert response.url == "https://example.com/"401 assert response.text == "Logged in"402403 # Logout redirects to the homepage, expiring the session cookie.404 response = client.post("https://example.com/logout")405 assert response.url == "https://example.com/"406 assert response.text == "Not logged in"407408 # The client is not logged in.409 response = client.get("https://example.com/")410 assert response.url == "https://example.com/"411 assert response.text == "Not logged in"412413414def test_redirect_custom_scheme():415 client = httpx.Client(transport=httpx.MockTransport(redirects))416 with pytest.raises(httpx.UnsupportedProtocol) as e:417 client.post("https://example.org/redirect_custom_scheme", follow_redirects=True)418 assert str(e.value) == "Scheme 'market' not supported."419420421@pytest.mark.usefixtures("async_environment")422async def test_async_invalid_redirect():423 async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client:424 with pytest.raises(httpx.RemoteProtocolError):425 await client.get(426 "http://example.org/invalid_redirect", follow_redirects=True427 )