test_redirects.py
This file
Path
tests/client/test_redirects.py
416 lines · 15.4 KiB · Python
Last changed by
Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9
History of this fileTake it
1import httpcore2import pytest34import httpx5from tests.utils import MockTransport678def redirects(request: httpx.Request) -> httpx.Response:9 if request.url.scheme not in ("http", "https"):10 raise httpcore.UnsupportedProtocol(11 f"Scheme {request.url.scheme!r} not supported."12 )1314 if request.url.path == "/no_redirect":15 return httpx.Response(200)1617 elif request.url.path == "/redirect_301":18 status_code = httpx.codes.MOVED_PERMANENTLY19 content = b"<a href='https://example.org/'>here</a>"20 headers = {"location": "https://example.org/"}21 return httpx.Response(status_code, headers=headers, content=content)2223 elif request.url.path == "/redirect_302":24 status_code = httpx.codes.FOUND25 headers = {"location": "https://example.org/"}26 return httpx.Response(status_code, headers=headers)2728 elif request.url.path == "/redirect_303":29 status_code = httpx.codes.SEE_OTHER30 headers = {"location": "https://example.org/"}31 return httpx.Response(status_code, headers=headers)3233 elif request.url.path == "/relative_redirect":34 status_code = httpx.codes.SEE_OTHER35 headers = {"location": "/"}36 return httpx.Response(status_code, headers=headers)3738 elif request.url.path == "/malformed_redirect":39 status_code = httpx.codes.SEE_OTHER40 headers = {"location": "https://:443/"}41 return httpx.Response(status_code, headers=headers)4243 elif request.url.path == "/invalid_redirect":44 status_code = httpx.codes.SEE_OTHER45 raw_headers = [(b"location", "https://😇/".encode("utf-8"))]46 return httpx.Response(status_code, headers=raw_headers)4748 elif request.url.path == "/no_scheme_redirect":49 status_code = httpx.codes.SEE_OTHER50 headers = {"location": "//example.org/"}51 return httpx.Response(status_code, headers=headers)5253 elif request.url.path == "/multiple_redirects":54 params = httpx.QueryParams(request.url.query)55 count = int(params.get("count", "0"))56 redirect_count = count - 157 status_code = httpx.codes.SEE_OTHER if count else httpx.codes.OK58 if count:59 location = "/multiple_redirects"60 if redirect_count:61 location += f"?count={redirect_count}"62 headers = {"location": location}63 else:64 headers = {}65 return httpx.Response(status_code, headers=headers)6667 if request.url.path == "/redirect_loop":68 status_code = httpx.codes.SEE_OTHER69 headers = {"location": "/redirect_loop"}70 return httpx.Response(status_code, headers=headers)7172 elif request.url.path == "/cross_domain":73 status_code = httpx.codes.SEE_OTHER74 headers = {"location": "https://example.org/cross_domain_target"}75 return httpx.Response(status_code, headers=headers)7677 elif request.url.path == "/cross_domain_target":78 status_code = httpx.codes.OK79 data = {80 "body": request.content.decode("ascii"),81 "headers": dict(request.headers),82 }83 return httpx.Response(status_code, json=data)8485 elif request.url.path == "/redirect_body":86 status_code = httpx.codes.PERMANENT_REDIRECT87 headers = {"location": "/redirect_body_target"}88 return httpx.Response(status_code, headers=headers)8990 elif request.url.path == "/redirect_no_body":91 status_code = httpx.codes.SEE_OTHER92 headers = {"location": "/redirect_body_target"}93 return httpx.Response(status_code, headers=headers)9495 elif request.url.path == "/redirect_body_target":96 data = {97 "body": request.content.decode("ascii"),98 "headers": dict(request.headers),99 }100 return httpx.Response(200, json=data)101102 elif request.url.path == "/cross_subdomain":103 if request.headers["Host"] != "www.example.org":104 status_code = httpx.codes.PERMANENT_REDIRECT105 headers = {"location": "https://www.example.org/cross_subdomain"}106 return httpx.Response(status_code, headers=headers)107 else:108 return httpx.Response(200, text="Hello, world!")109110 elif request.url.path == "/redirect_custom_scheme":111 status_code = httpx.codes.MOVED_PERMANENTLY112 headers = {"location": "market://details?id=42"}113 return httpx.Response(status_code, headers=headers)114115 if request.method == "HEAD":116 return httpx.Response(200)117118 return httpx.Response(200, html="<html><body>Hello, world!</body></html>")119120121def test_no_redirect():122 client = httpx.Client(transport=MockTransport(redirects))123 url = "https://example.com/no_redirect"124 response = client.get(url)125 assert response.status_code == 200126 with pytest.raises(httpx.NotRedirectResponse):127 response.next()128129130def test_redirect_301():131 client = httpx.Client(transport=MockTransport(redirects))132 response = client.post("https://example.org/redirect_301")133 assert response.status_code == httpx.codes.OK134 assert response.url == "https://example.org/"135 assert len(response.history) == 1136137138def test_redirect_302():139 client = httpx.Client(transport=MockTransport(redirects))140 response = client.post("https://example.org/redirect_302")141 assert response.status_code == httpx.codes.OK142 assert response.url == "https://example.org/"143 assert len(response.history) == 1144145146def test_redirect_303():147 client = httpx.Client(transport=MockTransport(redirects))148 response = client.get("https://example.org/redirect_303")149 assert response.status_code == httpx.codes.OK150 assert response.url == "https://example.org/"151 assert len(response.history) == 1152153154def test_disallow_redirects():155 client = httpx.Client(transport=MockTransport(redirects))156 response = client.post("https://example.org/redirect_303", allow_redirects=False)157 assert response.status_code == httpx.codes.SEE_OTHER158 assert response.url == "https://example.org/redirect_303"159 assert response.is_redirect is True160 assert len(response.history) == 0161162 response = response.next()163 assert response.status_code == httpx.codes.OK164 assert response.url == "https://example.org/"165 assert response.is_redirect is False166 assert len(response.history) == 1167168169def test_head_redirect():170 """171 Contrary to Requests, redirects remain enabled by default for HEAD requests.172 """173 client = httpx.Client(transport=MockTransport(redirects))174 response = client.head("https://example.org/redirect_302")175 assert response.status_code == httpx.codes.OK176 assert response.url == "https://example.org/"177 assert response.request.method == "HEAD"178 assert len(response.history) == 1179 assert response.text == ""180181182def test_relative_redirect():183 client = httpx.Client(transport=MockTransport(redirects))184 response = client.get("https://example.org/relative_redirect")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=MockTransport(redirects))193 response = client.get("http://example.org/malformed_redirect")194 assert response.status_code == httpx.codes.OK195 assert response.url == "https://example.org:443/"196 assert len(response.history) == 1197198199def test_invalid_redirect():200 client = httpx.Client(transport=MockTransport(redirects))201 with pytest.raises(httpx.RemoteProtocolError):202 client.get("http://example.org/invalid_redirect")203204205def test_no_scheme_redirect():206 client = httpx.Client(transport=MockTransport(redirects))207 response = client.get("https://example.org/no_scheme_redirect")208 assert response.status_code == httpx.codes.OK209 assert response.url == "https://example.org/"210 assert len(response.history) == 1211212213def test_fragment_redirect():214 client = httpx.Client(transport=MockTransport(redirects))215 response = client.get("https://example.org/relative_redirect#fragment")216 assert response.status_code == httpx.codes.OK217 assert response.url == "https://example.org/#fragment"218 assert len(response.history) == 1219220221def test_multiple_redirects():222 client = httpx.Client(transport=MockTransport(redirects))223 response = client.get("https://example.org/multiple_redirects?count=20")224 assert response.status_code == httpx.codes.OK225 assert response.url == "https://example.org/multiple_redirects"226 assert len(response.history) == 20227 assert response.history[0].url == "https://example.org/multiple_redirects?count=20"228 assert response.history[1].url == "https://example.org/multiple_redirects?count=19"229 assert len(response.history[0].history) == 0230 assert len(response.history[1].history) == 1231232233@pytest.mark.usefixtures("async_environment")234async def test_async_too_many_redirects():235 async with httpx.AsyncClient(transport=MockTransport(redirects)) as client:236 with pytest.raises(httpx.TooManyRedirects):237 await client.get("https://example.org/multiple_redirects?count=21")238239240@pytest.mark.usefixtures("async_environment")241async def test_async_too_many_redirects_calling_next():242 async with httpx.AsyncClient(transport=MockTransport(redirects)) as client:243 url = "https://example.org/multiple_redirects?count=21"244 response = await client.get(url, allow_redirects=False)245 with pytest.raises(httpx.TooManyRedirects):246 while response.is_redirect:247 response = await response.anext()248249250def test_sync_too_many_redirects():251 client = httpx.Client(transport=MockTransport(redirects))252 with pytest.raises(httpx.TooManyRedirects):253 client.get("https://example.org/multiple_redirects?count=21")254255256def test_sync_too_many_redirects_calling_next():257 client = httpx.Client(transport=MockTransport(redirects))258 url = "https://example.org/multiple_redirects?count=21"259 response = client.get(url, allow_redirects=False)260 with pytest.raises(httpx.TooManyRedirects):261 while response.is_redirect:262 response = response.next()263264265def test_redirect_loop():266 client = httpx.Client(transport=MockTransport(redirects))267 with pytest.raises(httpx.TooManyRedirects):268 client.get("https://example.org/redirect_loop")269270271def test_cross_domain_redirect_with_auth_header():272 client = httpx.Client(transport=MockTransport(redirects))273 url = "https://example.com/cross_domain"274 headers = {"Authorization": "abc"}275 response = client.get(url, headers=headers)276 assert response.url == "https://example.org/cross_domain_target"277 assert "authorization" not in response.json()["headers"]278279280def test_cross_domain_redirect_with_auth():281 client = httpx.Client(transport=MockTransport(redirects))282 url = "https://example.com/cross_domain"283 response = client.get(url, auth=("user", "pass"))284 assert response.url == "https://example.org/cross_domain_target"285 assert "authorization" not in response.json()["headers"]286287288def test_same_domain_redirect():289 client = httpx.Client(transport=MockTransport(redirects))290 url = "https://example.org/cross_domain"291 headers = {"Authorization": "abc"}292 response = client.get(url, headers=headers)293 assert response.url == "https://example.org/cross_domain_target"294 assert response.json()["headers"]["authorization"] == "abc"295296297def test_body_redirect():298 """299 A 308 redirect should preserve the request body.300 """301 client = httpx.Client(transport=MockTransport(redirects))302 url = "https://example.org/redirect_body"303 content = b"Example request body"304 response = client.post(url, content=content)305 assert response.url == "https://example.org/redirect_body_target"306 assert response.json()["body"] == "Example request body"307 assert "content-length" in response.json()["headers"]308309310def test_no_body_redirect():311 """312 A 303 redirect should remove the request body.313 """314 client = httpx.Client(transport=MockTransport(redirects))315 url = "https://example.org/redirect_no_body"316 content = b"Example request body"317 response = client.post(url, content=content)318 assert response.url == "https://example.org/redirect_body_target"319 assert response.json()["body"] == ""320 assert "content-length" not in response.json()["headers"]321322323def test_can_stream_if_no_redirect():324 client = httpx.Client(transport=MockTransport(redirects))325 url = "https://example.org/redirect_301"326 with client.stream("GET", url, allow_redirects=False) as response:327 assert not response.is_closed328 assert response.status_code == httpx.codes.MOVED_PERMANENTLY329 assert response.headers["location"] == "https://example.org/"330331332def test_cannot_redirect_streaming_body():333 client = httpx.Client(transport=MockTransport(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())341342343def test_cross_subdomain_redirect():344 client = httpx.Client(transport=MockTransport(redirects))345 url = "https://example.com/cross_subdomain"346 response = client.get(url)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(transport=MockTransport(cookie_sessions))385386 # The client is not logged in.387 response = client.get("https://example.com/")388 assert response.url == "https://example.com/"389 assert response.text == "Not logged in"390391 # Login redirects to the homepage, setting a session cookie.392 response = client.post("https://example.com/login")393 assert response.url == "https://example.com/"394 assert response.text == "Logged in"395396 # The client is logged in.397 response = client.get("https://example.com/")398 assert response.url == "https://example.com/"399 assert response.text == "Logged in"400401 # Logout redirects to the homepage, expiring the session cookie.402 response = client.post("https://example.com/logout")403 assert response.url == "https://example.com/"404 assert response.text == "Not logged in"405406 # The client is not logged in.407 response = client.get("https://example.com/")408 assert response.url == "https://example.com/"409 assert response.text == "Not logged in"410411412def test_redirect_custom_scheme():413 client = httpx.Client(transport=MockTransport(redirects))414 with pytest.raises(httpx.UnsupportedProtocol) as e:415 client.post("https://example.org/redirect_custom_scheme")416 assert str(e.value) == "Scheme 'market' not supported."