Skip to content

RedirectResponse returns 404 for external url's with TestClient #790

@chbndrhnns

Description

@chbndrhnns

Describe the bug

When trying to test a RedirectResponse with TestClient, it returns a 404 on any external url.

It seems related to this issue but there is an important difference: While in pure starlette, redirects work for urls in the form https://domain.tld/ and fail for https://domain.tld or any path or query parameters, with FastAPI, they fail for ANY external domain (see below).

Feel free to close this issue if it has nothing to do with FastAPI. I assume it has something to do with FastAPI as the behavior is different for FastAPI and pure starlette.

To Reproduce

  1. Create a file with:
from fastapi import FastAPI
from starlette.responses import RedirectResponse
from starlette.testclient import TestClient


def test_redirect():
    app = FastAPI()

    @app.get('/home')
    def home():
        return {}

    @app.get('/redirect_home')
    def redirect():
        return RedirectResponse(url='/home')

    @app.get('/redirect')
    def redirect():
        return RedirectResponse(url='https://www.github.com/')

    with TestClient(app) as client:
        response = client.get('/redirect_home')
        assert response.status_code == 200

        response = client.get('/redirect', allow_redirects=False)
        assert response.status_code == 307

        response = client.get('/redirect')
        assert response.status_code == 200
  1. Run the test with pytest.

The error I get:

            response = client.get('/redirect')
>           assert response.status_code == 200
E           assert 404 == 200

test_bug.py:29: AssertionError

Expected behavior

TestClient returns the correct status code for external urls.

Screenshots

If applicable, add screenshots to help explain your problem.

Environment

  • OS: macOS
  • FastAPI Version: 0.45.0
  • Python version:

Additional context

Add any other context about the problem here.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions