test_redirects.py
This file
Path
tests/client/test_redirects.py
445 lines · 17.1 KiB · Python
Last changed by
Preserve Authorization header on HTTPS redirect (#1850) (#2074)waterfountain1996before adoption4401d55
History of this fileTake it
The walk stopped after 200 commits: lines older than 0a8b44e point at it.
Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 1–115why, one step back1import 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))Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
line 116why, one step back116 response = client.post("https://example.org/redirect_301", follow_redirects=True)Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 117–123why, one step back117 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))Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
line 124why, one step back124 response = client.post("https://example.org/redirect_302", follow_redirects=True)Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 125–131why, one step back125 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))Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
line 132why, one step back132 response = client.get("https://example.org/redirect_303", follow_redirects=True)Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 133–140why, one step back133 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")Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
line 141why, one step back141 response = client.send(request, follow_redirects=False)Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 142–145why, one step back142 assert response.status_code == httpx.codes.SEE_OTHER143 assert response.url == "https://example.org/redirect_303"144 assert response.next_request is not None145Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
line 146why, one step back146 response = client.send(response.next_request, follow_redirects=False)Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 147–155why, one step back147 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")Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
line 156why, one step back156 response = await client.send(request, follow_redirects=False)Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 157–160why, one step back157 assert response.status_code == httpx.codes.SEE_OTHER158 assert response.url == "https://example.org/redirect_303"159 assert response.next_request is not None160Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
line 161why, one step back161 response = await client.send(response.next_request, follow_redirects=False)Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 162–171why, one step back162 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))Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
line 172why, one step back172 response = client.head("https://example.org/redirect_302", follow_redirects=True)Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 173–181why, one step back173 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))Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
lines 182–184why, one step back182 response = client.get(183 "https://example.org/relative_redirect", follow_redirects=True184 )Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 185–192why, one step back185 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))Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
lines 193–195why, one step back193 response = client.get(194 "http://example.org/malformed_redirect", follow_redirects=True195 )Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 196–203why, one step back196 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):Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
line 204why, one step back204 client.get("http://example.org/invalid_redirect", follow_redirects=True)Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 205–208why, one step back205206207def test_no_scheme_redirect():208 client = httpx.Client(transport=httpx.MockTransport(redirects))Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
lines 209–211why, one step back209 response = client.get(210 "https://example.org/no_scheme_redirect", follow_redirects=True211 )Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 212–218why, one step back212 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))Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
lines 219–221why, one step back219 response = client.get(220 "https://example.org/relative_redirect#fragment", follow_redirects=True221 )Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 222–228why, one step back222 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))Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
lines 229–231why, one step back229 response = client.get(230 "https://example.org/multiple_redirects?count=20", follow_redirects=True231 )Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 232–244why, one step back232 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):Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
lines 245–247why, one step back245 await client.get(246 "https://example.org/multiple_redirects?count=21", follow_redirects=True247 )Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 248–252why, one step back248249250def test_sync_too_many_redirects():251 client = httpx.Client(transport=httpx.MockTransport(redirects))252 with pytest.raises(httpx.TooManyRedirects):Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
lines 253–255why, one step back253 client.get(254 "https://example.org/multiple_redirects?count=21", follow_redirects=True255 )Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 256–260why, one step back256257258def test_redirect_loop():259 client = httpx.Client(transport=httpx.MockTransport(redirects))260 with pytest.raises(httpx.TooManyRedirects):Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
line 261why, one step back261 client.get("https://example.org/redirect_loop", follow_redirects=True)Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 262–267why, one step back262263264def 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"}Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
line 268why, one step back268 response = client.get(url, headers=headers, follow_redirects=True)Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 269–272why, one step back269 assert response.url == "https://example.org/cross_domain_target"270 assert "authorization" not in response.json()["headers"]271272Preserve Authorization header on HTTPS redirect (#1850) (#2074)waterfountain1996before adoption4401d55
lines 273–281why, one step back273def test_cross_domain_https_redirect_with_auth_header():274 client = httpx.Client(transport=httpx.MockTransport(redirects))275 url = "http://example.com/cross_domain"276 headers = {"Authorization": "abc"}277 response = client.get(url, headers=headers, follow_redirects=True)278 assert response.url == "https://example.org/cross_domain_target"279 assert "authorization" not in response.json()["headers"]280281Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 282–284why, one step back282def test_cross_domain_redirect_with_auth():283 client = httpx.Client(transport=httpx.MockTransport(redirects))284 url = "https://example.com/cross_domain"Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
line 285why, one step back285 response = client.get(url, auth=("user", "pass"), follow_redirects=True)Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 286–292why, one step back286 assert response.url == "https://example.org/cross_domain_target"287 assert "authorization" not in response.json()["headers"]288289290def test_same_domain_redirect():291 client = httpx.Client(transport=httpx.MockTransport(redirects))292 url = "https://example.org/cross_domain"Preserve Authorization header on HTTPS redirect (#1850) (#2074)waterfountain1996before adoption4401d55
lines 293–301why, one step back293 headers = {"Authorization": "abc"}294 response = client.get(url, headers=headers, follow_redirects=True)295 assert response.url == "https://example.org/cross_domain_target"296 assert response.json()["headers"]["authorization"] == "abc"297298299def test_same_domain_https_redirect_with_auth_header():300 client = httpx.Client(transport=httpx.MockTransport(redirects))301 url = "http://example.org/cross_domain"Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
line 302why, one step back302 headers = {"Authorization": "abc"}Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
line 303why, one step back303 response = client.get(url, headers=headers, follow_redirects=True)Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 304–314why, one step back304 assert response.url == "https://example.org/cross_domain_target"305 assert response.json()["headers"]["authorization"] == "abc"306307308def test_body_redirect():309 """310 A 308 redirect should preserve the request body.311 """312 client = httpx.Client(transport=httpx.MockTransport(redirects))313 url = "https://example.org/redirect_body"314 content = b"Example request body"Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
line 315why, one step back315 response = client.post(url, content=content, follow_redirects=True)Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 316–327why, one step back316 assert response.url == "https://example.org/redirect_body_target"317 assert response.json()["body"] == "Example request body"318 assert "content-length" in response.json()["headers"]319320321def test_no_body_redirect():322 """323 A 303 redirect should remove the request body.324 """325 client = httpx.Client(transport=httpx.MockTransport(redirects))326 url = "https://example.org/redirect_no_body"327 content = b"Example request body"Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
line 328why, one step back328 response = client.post(url, content=content, follow_redirects=True)Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 329–336why, one step back329 assert response.url == "https://example.org/redirect_body_target"330 assert response.json()["body"] == ""331 assert "content-length" not in response.json()["headers"]332333334def test_can_stream_if_no_redirect():335 client = httpx.Client(transport=httpx.MockTransport(redirects))336 url = "https://example.org/redirect_301"Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
line 337why, one step back337 with client.stream("GET", url, follow_redirects=False) as response:Transport API as plain `request -> response` method. (#1840)Tom Christiebefore adoptionff9813e
line 338why, one step back338 passPerform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 339–342why, one step back339 assert response.status_code == httpx.codes.MOVED_PERMANENTLY340 assert response.headers["location"] == "https://example.org/"341342Transport API as plain `request -> response` method. (#1840)Tom Christiebefore adoptionff9813e
lines 343–349why, one step back343class ConsumeBodyTransport(httpx.MockTransport):344 def handle_request(self, request: httpx.Request) -> httpx.Response:345 assert isinstance(request.stream, httpx.SyncByteStream)346 [_ for _ in request.stream]347 return self.handler(request)348349Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
line 350why, one step back350def test_cannot_redirect_streaming_body():Transport API as plain `request -> response` method. (#1840)Tom Christiebefore adoptionff9813e
line 351why, one step back351 client = httpx.Client(transport=ConsumeBodyTransport(redirects))Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 352–357why, one step back352 url = "https://example.org/redirect_body"353354 def streaming_body():355 yield b"Example request body" # pragma: nocover356357 with pytest.raises(httpx.StreamConsumed):Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
line 358why, one step back358 client.post(url, content=streaming_body(), follow_redirects=True)Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 359–363why, one step back359360361def test_cross_subdomain_redirect():362 client = httpx.Client(transport=httpx.MockTransport(redirects))363 url = "https://example.com/cross_subdomain"Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
line 364why, one step back364 response = client.get(url, follow_redirects=True)Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 365–401why, one step back365 assert response.url == "https://www.example.org/cross_subdomain"366367368def cookie_sessions(request: httpx.Request) -> httpx.Response:369 if request.url.path == "/":370 cookie = request.headers.get("Cookie")371 if cookie is not None:372 content = b"Logged in"373 else:374 content = b"Not logged in"375 return httpx.Response(200, content=content)376377 elif request.url.path == "/login":378 status_code = httpx.codes.SEE_OTHER379 headers = {380 "location": "/",381 "set-cookie": (382 "session=eyJ1c2VybmFtZSI6ICJ0b21; path=/; Max-Age=1209600; "383 "httponly; samesite=lax"384 ),385 }386 return httpx.Response(status_code, headers=headers)387388 else:389 assert request.url.path == "/logout"390 status_code = httpx.codes.SEE_OTHER391 headers = {392 "location": "/",393 "set-cookie": (394 "session=null; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; "395 "httponly; samesite=lax"396 ),397 }398 return httpx.Response(status_code, headers=headers)399400401def test_redirect_cookie_behavior():Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
lines 402–404why, one step back402 client = httpx.Client(403 transport=httpx.MockTransport(cookie_sessions), follow_redirects=True404 )Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 405–434why, one step back405406 # 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"410411 # Login redirects to the homepage, setting a session cookie.412 response = client.post("https://example.com/login")413 assert response.url == "https://example.com/"414 assert response.text == "Logged in"415416 # The client is logged in.417 response = client.get("https://example.com/")418 assert response.url == "https://example.com/"419 assert response.text == "Logged in"420421 # Logout redirects to the homepage, expiring the session cookie.422 response = client.post("https://example.com/logout")423 assert response.url == "https://example.com/"424 assert response.text == "Not logged in"425426 # The client is not logged in.427 response = client.get("https://example.com/")428 assert response.url == "https://example.com/"429 assert response.text == "Not logged in"430431432def test_redirect_custom_scheme():433 client = httpx.Client(transport=httpx.MockTransport(redirects))434 with pytest.raises(httpx.UnsupportedProtocol) as e:Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
line 435why, one step back435 client.post("https://example.org/redirect_custom_scheme", follow_redirects=True)Perform port normalization for http, https, ws, wss, and ftp schemes (#1603)Tom Christiebefore adoption0a8b44e
lines 436–442why, one step back436 assert str(e.value) == "Scheme 'market' not supported."437438439@pytest.mark.usefixtures("async_environment")440async def test_async_invalid_redirect():441 async with httpx.AsyncClient(transport=httpx.MockTransport(redirects)) as client:442 with pytest.raises(httpx.RemoteProtocolError):Switch follow redirects default (#1808)Tom Christiebefore adoption47266d7
lines 443–445why, one step back443 await client.get(444 "http://example.org/invalid_redirect", follow_redirects=True445 )