I have set up 2 databases in my project. One is primary which I would use for day to day use and the other is just for testing. The problem is that my Strawberry fields all use primary database and I don't know how can I properly replace that primary db with testing db.
I know that in FastAPI there's something like dependency injection with the help of which I can replace primary database connection dependency with testing database connection dependency but I don't seem to find similar solution in Strawberry.
I am using sqlalchemy with 2 postgres databases(primary and for testing), alembic for migrations and pytest with requests to perform tests.
What I'm trying to achieve:
- I want to apply migrations to my database for testing with alembic.
- Replace primary database session in all the Strawberry fields with test database session.
- Perform tests on GraphQL endpoints with requests module.
So requests library is more suitable for an end to end testing and it's much harder to do that with a separate database, so I replaced that part with
And here's more code of what I did to accomplish what I wanted:
I replaced hard coded
SessionLocal()in my endpoints withget_db()function which is being passed with a context to the endpoint:Then I did pretty much the exact same thing for my second database. I created
get_test_db()function for it andCustomContextclass for it(It would've been better if I'd named itTestContext, but because this class of mine is located in the exact same file as my testing code I can't do this, because pytest automatically detects it as test):And for the last part to perform mocking of the database connection I just needed to replace context when I query graphql:
by default
schemadoesn't have anycontext_valueto it so I need to provide it this way for my code to work and that's exactly what I need.Hope this helps someone who struggles setting up separate database for testing!