I am trying to write test on some endpoint in fastAPI that has a auth dependency:
router = APIRouter(dependencies=[Security(auth.AccountAuth())])
In the conftest.py. I have a class to override that dependency (I checked the formatted payload as well from jwt when calling the api):
class AccountAuthTest:
def __init__(self):
pass
async def __call__(
self
) -> FormattedPayload:
return FormattedPayload(email="myemail",
accounts={},
id="someid",
scopes=None,
permissions=[],
m2m=False)
I create a fixture like this one:
@pytest.fixture()
def fastapi_authenticated_app(
dbsession: AsyncSession,
) -> FastAPI:
"""
Fixture for creating FastAPI app.
:return: fastapi app with mocked dependencies.
"""
application, sub_app = get_app()
sub_app.dependency_overrides[get_db_session] = lambda: dbsession
sub_app.dependency_overrides[auth.AccountAuth()] = lambda: AccountAuthTest()
return application
I expect the test will run correctly but it showed me 403. I don't know why this goes wrong here
I ran into the same issue, and found this solution on Github: https://github.com/tiangolo/fastapi/issues/2795#issuecomment-778031303.
In your case, this would mean:
from dataclasses import dataclass
@dataclass(frozen=True)
class AccountAuthTest:
async def __call__(self) -> FormattedPayload:
...