test_redirects.py
This file
Path
tests/client/test_redirects.py
374 lines · 13.9 KiB · Python
Last changed by
Dispatcher -> AsyncDispatcher (#725)Tom Christiebefore adoptione19bd9b
History of this fileTake it
1import json2from urllib.parse import parse_qs34import pytest56from httpx import (7 URL,8 AsyncClient,9 NotRedirectResponse,10 RedirectLoop,11 Request,12 RequestBodyUnavailable,13 Response,14 TooManyRedirects,15 codes,16)17from httpx.config import CertTypes, TimeoutTypes, VerifyTypes18from httpx.dispatch.base import AsyncDispatcher192021class MockDispatch(AsyncDispatcher):22 async def send(23 self,24 request: Request,25 verify: VerifyTypes = None,26 cert: CertTypes = None,27 timeout: TimeoutTypes = None,28 ) -> Response:29 if request.url.path == "/no_redirect":30 return Response(codes.OK, request=request)3132 elif request.url.path == "/redirect_301":33 status_code = codes.MOVED_PERMANENTLY34 headers = {"location": "https://example.org/"}35 return Response(status_code, headers=headers, request=request)3637 elif request.url.path == "/redirect_302":38 status_code = codes.FOUND39 headers = {"location": "https://example.org/"}40 return Response(status_code, headers=headers, request=request)4142 elif request.url.path == "/redirect_303":43 status_code = codes.SEE_OTHER44 headers = {"location": "https://example.org/"}45 return Response(status_code, headers=headers, request=request)4647 elif request.url.path == "/relative_redirect":48 headers = {"location": "/"}49 return Response(codes.SEE_OTHER, headers=headers, request=request)5051 elif request.url.path == "/no_scheme_redirect":52 headers = {"location": "//example.org/"}53 return Response(codes.SEE_OTHER, headers=headers, request=request)5455 elif request.url.path == "/multiple_redirects":56 params = parse_qs(request.url.query)57 count = int(params.get("count", "0")[0])58 redirect_count = count - 159 code = codes.SEE_OTHER if count else codes.OK60 location = "/multiple_redirects"61 if redirect_count:62 location += "?count=" + str(redirect_count)63 headers = {"location": location} if count else {}64 return Response(code, headers=headers, request=request)6566 if request.url.path == "/redirect_loop":67 headers = {"location": "/redirect_loop"}68 return Response(codes.SEE_OTHER, headers=headers, request=request)6970 elif request.url.path == "/cross_domain":71 headers = {"location": "https://example.org/cross_domain_target"}72 return Response(codes.SEE_OTHER, headers=headers, request=request)7374 elif request.url.path == "/cross_domain_target":75 headers = dict(request.headers.items())76 content = json.dumps({"headers": headers}).encode()77 return Response(codes.OK, content=content, request=request)7879 elif request.url.path == "/redirect_body":80 body = b"".join([part async for part in request.stream])81 headers = {"location": "/redirect_body_target"}82 return Response(codes.PERMANENT_REDIRECT, headers=headers, request=request)8384 elif request.url.path == "/redirect_no_body":85 content = b"".join([part async for part in request.stream])86 headers = {"location": "/redirect_body_target"}87 return Response(codes.SEE_OTHER, headers=headers, request=request)8889 elif request.url.path == "/redirect_body_target":90 content = b"".join([part async for part in request.stream])91 headers = dict(request.headers.items())92 body = json.dumps({"body": content.decode(), "headers": headers}).encode()93 return Response(codes.OK, content=body, request=request)9495 elif request.url.path == "/cross_subdomain":96 if request.headers["host"] != "www.example.org":97 headers = {"location": "https://www.example.org/cross_subdomain"}98 return Response(99 codes.PERMANENT_REDIRECT, headers=headers, request=request100 )101 else:102 return Response(codes.OK, content=b"Hello, world!", request=request)103104 return Response(codes.OK, content=b"Hello, world!", request=request)105106107@pytest.mark.usefixtures("async_environment")108async def test_no_redirect():109 client = AsyncClient(dispatch=MockDispatch())110 url = "https://example.com/no_redirect"111 response = await client.get(url)112 assert response.status_code == 200113 with pytest.raises(NotRedirectResponse):114 await response.anext()115116117@pytest.mark.usefixtures("async_environment")118async def test_redirect_301():119 client = AsyncClient(dispatch=MockDispatch())120 response = await client.post("https://example.org/redirect_301")121 assert response.status_code == codes.OK122 assert response.url == URL("https://example.org/")123 assert len(response.history) == 1124125126@pytest.mark.usefixtures("async_environment")127async def test_redirect_302():128 client = AsyncClient(dispatch=MockDispatch())129 response = await client.post("https://example.org/redirect_302")130 assert response.status_code == codes.OK131 assert response.url == URL("https://example.org/")132 assert len(response.history) == 1133134135@pytest.mark.usefixtures("async_environment")136async def test_redirect_303():137 client = AsyncClient(dispatch=MockDispatch())138 response = await client.get("https://example.org/redirect_303")139 assert response.status_code == codes.OK140 assert response.url == URL("https://example.org/")141 assert len(response.history) == 1142143144@pytest.mark.usefixtures("async_environment")145async def test_disallow_redirects():146 client = AsyncClient(dispatch=MockDispatch())147 response = await client.post(148 "https://example.org/redirect_303", allow_redirects=False149 )150 assert response.status_code == codes.SEE_OTHER151 assert response.url == URL("https://example.org/redirect_303")152 assert response.is_redirect is True153 assert len(response.history) == 0154155 response = await response.anext()156 assert response.status_code == codes.OK157 assert response.url == URL("https://example.org/")158 assert response.is_redirect is False159 assert len(response.history) == 1160161162@pytest.mark.usefixtures("async_environment")163async def test_relative_redirect():164 client = AsyncClient(dispatch=MockDispatch())165 response = await client.get("https://example.org/relative_redirect")166 assert response.status_code == codes.OK167 assert response.url == URL("https://example.org/")168 assert len(response.history) == 1169170171@pytest.mark.usefixtures("async_environment")172async def test_no_scheme_redirect():173 client = AsyncClient(dispatch=MockDispatch())174 response = await client.get("https://example.org/no_scheme_redirect")175 assert response.status_code == codes.OK176 assert response.url == URL("https://example.org/")177 assert len(response.history) == 1178179180@pytest.mark.usefixtures("async_environment")181async def test_fragment_redirect():182 client = AsyncClient(dispatch=MockDispatch())183 response = await client.get("https://example.org/relative_redirect#fragment")184 assert response.status_code == codes.OK185 assert response.url == URL("https://example.org/#fragment")186 assert len(response.history) == 1187188189@pytest.mark.usefixtures("async_environment")190async def test_multiple_redirects():191 client = AsyncClient(dispatch=MockDispatch())192 response = await client.get("https://example.org/multiple_redirects?count=20")193 assert response.status_code == codes.OK194 assert response.url == URL("https://example.org/multiple_redirects")195 assert len(response.history) == 20196 assert response.history[0].url == URL(197 "https://example.org/multiple_redirects?count=20"198 )199 assert response.history[1].url == URL(200 "https://example.org/multiple_redirects?count=19"201 )202 assert len(response.history[0].history) == 0203 assert len(response.history[1].history) == 1204205206@pytest.mark.usefixtures("async_environment")207async def test_too_many_redirects():208 client = AsyncClient(dispatch=MockDispatch())209 with pytest.raises(TooManyRedirects):210 await client.get("https://example.org/multiple_redirects?count=21")211212213@pytest.mark.usefixtures("async_environment")214async def test_too_many_redirects_calling_next():215 client = AsyncClient(dispatch=MockDispatch())216 url = "https://example.org/multiple_redirects?count=21"217 response = await client.get(url, allow_redirects=False)218 with pytest.raises(TooManyRedirects):219 while response.is_redirect:220 response = await response.anext()221222223@pytest.mark.usefixtures("async_environment")224async def test_redirect_loop():225 client = AsyncClient(dispatch=MockDispatch())226 with pytest.raises(RedirectLoop):227 await client.get("https://example.org/redirect_loop")228229230@pytest.mark.usefixtures("async_environment")231async def test_redirect_loop_calling_next():232 client = AsyncClient(dispatch=MockDispatch())233 url = "https://example.org/redirect_loop"234 response = await client.get(url, allow_redirects=False)235 with pytest.raises(RedirectLoop):236 while response.is_redirect:237 response = await response.anext()238239240@pytest.mark.usefixtures("async_environment")241async def test_cross_domain_redirect():242 client = AsyncClient(dispatch=MockDispatch())243 url = "https://example.com/cross_domain"244 headers = {"Authorization": "abc"}245 response = await client.get(url, headers=headers)246 assert response.url == URL("https://example.org/cross_domain_target")247 assert "authorization" not in response.json()["headers"]248249250@pytest.mark.usefixtures("async_environment")251async def test_same_domain_redirect():252 client = AsyncClient(dispatch=MockDispatch())253 url = "https://example.org/cross_domain"254 headers = {"Authorization": "abc"}255 response = await client.get(url, headers=headers)256 assert response.url == URL("https://example.org/cross_domain_target")257 assert response.json()["headers"]["authorization"] == "abc"258259260@pytest.mark.usefixtures("async_environment")261async def test_body_redirect():262 """263 A 308 redirect should preserve the request body.264 """265 client = AsyncClient(dispatch=MockDispatch())266 url = "https://example.org/redirect_body"267 data = b"Example request body"268 response = await client.post(url, data=data)269 assert response.url == URL("https://example.org/redirect_body_target")270 assert response.json()["body"] == "Example request body"271 assert "content-length" in response.json()["headers"]272273274@pytest.mark.usefixtures("async_environment")275async def test_no_body_redirect():276 """277 A 303 redirect should remove the request body.278 """279 client = AsyncClient(dispatch=MockDispatch())280 url = "https://example.org/redirect_no_body"281 data = b"Example request body"282 response = await client.post(url, data=data)283 assert response.url == URL("https://example.org/redirect_body_target")284 assert response.json()["body"] == ""285 assert "content-length" not in response.json()["headers"]286287288@pytest.mark.usefixtures("async_environment")289async def test_cannot_redirect_streaming_body():290 client = AsyncClient(dispatch=MockDispatch())291 url = "https://example.org/redirect_body"292293 async def streaming_body():294 yield b"Example request body"295296 with pytest.raises(RequestBodyUnavailable):297 await client.post(url, data=streaming_body())298299300@pytest.mark.usefixtures("async_environment")301async def test_cross_subdomain_redirect():302 client = AsyncClient(dispatch=MockDispatch())303 url = "https://example.com/cross_subdomain"304 response = await client.get(url)305 assert response.url == URL("https://www.example.org/cross_subdomain")306307308class MockCookieDispatch(AsyncDispatcher):309 async def send(310 self,311 request: Request,312 verify: VerifyTypes = None,313 cert: CertTypes = None,314 timeout: TimeoutTypes = None,315 ) -> Response:316 if request.url.path == "/":317 if "cookie" in request.headers:318 content = b"Logged in"319 else:320 content = b"Not logged in"321 return Response(codes.OK, content=content, request=request)322323 elif request.url.path == "/login":324 status_code = codes.SEE_OTHER325 headers = {326 "location": "/",327 "set-cookie": (328 "session=eyJ1c2VybmFtZSI6ICJ0b21; path=/; Max-Age=1209600; "329 "httponly; samesite=lax"330 ),331 }332333 return Response(status_code, headers=headers, request=request)334335 elif request.url.path == "/logout":336 status_code = codes.SEE_OTHER337 headers = {338 "location": "/",339 "set-cookie": (340 "session=null; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; "341 "httponly; samesite=lax"342 ),343 }344 return Response(status_code, headers=headers, request=request)345346347@pytest.mark.usefixtures("async_environment")348async def test_redirect_cookie_behavior():349 client = AsyncClient(dispatch=MockCookieDispatch())350351 # The client is not logged in.352 response = await client.get("https://example.com/")353 assert response.url == "https://example.com/"354 assert response.text == "Not logged in"355356 # Login redirects to the homepage, setting a session cookie.357 response = await client.post("https://example.com/login")358 assert response.url == "https://example.com/"359 assert response.text == "Logged in"360361 # The client is logged in.362 response = await client.get("https://example.com/")363 assert response.url == "https://example.com/"364 assert response.text == "Logged in"365366 # Logout redirects to the homepage, expiring the session cookie.367 response = await client.post("https://example.com/logout")368 assert response.url == "https://example.com/"369 assert response.text == "Not logged in"370371 # The client is not logged in.372 response = await client.get("https://example.com/")373 assert response.url == "https://example.com/"374 assert response.text == "Not logged in"