Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Pytest override session dependency #153

Open
foarsitter opened this issue Jun 28, 2024 · 2 comments
Open

Pytest override session dependency #153

foarsitter opened this issue Jun 28, 2024 · 2 comments

Comments

@foarsitter
Copy link

When using the fastapi.testclient.TestClient with pytest, the app doesn't use the session fixture resulting in writes to the database.

To solve this problem, pytest needs to tell the app to use the same session as used for testing. This can be done by using dependency_overrides.

@pytest.fixture(autouse=True)
def _app_session(app, session):
    app.dependency_overrides[fastapi_sqla.sqla.default_session_dep] = lambda: session

At least, this is how I solved the problem. Is there a beter approach or should I send a PR to document this?

@arththebird
Copy link
Contributor

Hi @foarsitter! Overriding the dependency shouldn't be necessary since we patch the engine factory used to generate the sessions. Can you try updating your test so that the session fixture is before the app fixture in the test function signature, so that it's loaded before the app by pytest?

@foarsitter
Copy link
Author

My app is a session scoped fixture, changing it to function scoped and adding session as dependency raises on

with engine.connect() as connection:

with

AttributeError: 'Connection' object has no attribute 'connect'. Did you mean: 'connection'?

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Development

No branches or pull requests

2 participants