diff --git a/starlette/testclient.py b/starlette/testclient.py index 7d4f3e396..099edc3ff 100644 --- a/starlette/testclient.py +++ b/starlette/testclient.py @@ -382,6 +382,7 @@ def __init__( backend_options: typing.Optional[typing.Dict[str, typing.Any]] = None, cookies: httpx._client.CookieTypes = None, headers: typing.Dict[str, str] = None, + follow_redirects: bool = True, ) -> None: self.async_backend = _AsyncBackend( backend=backend, backend_options=backend_options or {} @@ -409,7 +410,7 @@ def __init__( base_url=base_url, headers=headers, transport=transport, - follow_redirects=True, + follow_redirects=follow_redirects, cookies=cookies, ) diff --git a/tests/test_testclient.py b/tests/test_testclient.py index 1bf9692a6..0f36d4dcc 100644 --- a/tests/test_testclient.py +++ b/tests/test_testclient.py @@ -10,7 +10,7 @@ from starlette.applications import Starlette from starlette.middleware import Middleware -from starlette.responses import JSONResponse, Response +from starlette.responses import JSONResponse, RedirectResponse, Response from starlette.routing import Route from starlette.testclient import TestClient from starlette.websockets import WebSocket, WebSocketDisconnect @@ -319,3 +319,26 @@ async def app(scope, receive, send): response = client.get("/") cookie_set = len(response.cookies) == 1 assert cookie_set == ok + + +def test_forward_follow_redirects(test_client_factory): + async def app(scope, receive, send): + if "/ok" in scope["path"]: + response = Response("ok") + else: + response = RedirectResponse("/ok") + await response(scope, receive, send) + + client = test_client_factory(app, follow_redirects=True) + response = client.get("/") + assert response.status_code == 200 + + +def test_forward_nofollow_redirects(test_client_factory): + async def app(scope, receive, send): + response = RedirectResponse("/ok") + await response(scope, receive, send) + + client = test_client_factory(app, follow_redirects=False) + response = client.get("/") + assert response.status_code == 307