Skip to content

TestClient.__enter__ return type error for subclasses #2950

@cdeil

Description

@cdeil

In our FastAPI tests we switch between different test users that we have as fixtures a lot, and I found that sub-classing TestClient is a nice way to switch between them via client.as_user(user_42).get(...) if I do this:

class MyTestClient(TestClient):
    """Enhanced test client that can authenticate as different users via bearer tokens."""

    def as_user(self, user: User) -> Self:
        self.headers.update(create_access_token(user).headers)
        return self

@pytest.fixture
def client(db, test_user) -> Generator[MyTestClient]:
    app.dependency_overrides[get_session] = lambda: db
    with MyTestClient(app) as test_client:
        yield test_client.as_user(test_user)

    app.dependency_overrides.clear()

Unfortunately pyright gives this error incorrectly claiming that client.as_user doesn't exist:

 error: Cannot access attribute "as_user" for class "TestClient"
    Attribute "as_user" is unknown (reportAttributeAccessIssue)

The problem is that you have a hard-coded return type annotation on TestClient.__enter__ that doesn't work with sub-classes:

def __enter__(self) -> TestClient:

I gather you can't use typing.Self yet?
Is there some other way to fix that type annotation?

For now I'll do a manual typing.cast as workaround.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions