-
-
Notifications
You must be signed in to change notification settings - Fork 1k
Closed
Description
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:
starlette/starlette/testclient.py
Line 670 in 739ea49
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
Labels
No labels