-
Notifications
You must be signed in to change notification settings - Fork 38
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
how to use db session in router level unit test #27
Comments
@mfreeborn any suggestion? |
@zzmao did you get any solution of this? |
One QUICK WAY to fix this is using conftest.pyimport unittest.mock
import pytest
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy_utils import create_database, database_exists
from fastapi_sqlalchemy import db
from app.config import config
from app import models
@pytest.fixture
def use_db():
if not database_exists(config.DB_URL):
create_database(config.DB_URL)
engine = create_engine(config.DB_URL, pool_pre_ping=True)
models.Base.metadata.create_all(engine)
_Session = sessionmaker(bind=engine)
with unittest.mock.patch( # !! HERE !!
'fastapi_sqlalchemy.middleware._Session',
_Session,
):
with db():
yield None
models.Base.metadata.drop_all(engine)
engine.dispose() test_dummy_model.pyimport uuid
import pytest
from fastapi_sqlalchemy import db
from app import models
@pytest.mark.usefixtures('use_db')
class TestDummyModel:
def test_create(self):
assert len(db.session.query(models.DummyModel).all()) == 0
instance = models.DummyModel(foo='foo', bar='bar')
assert not instance.id
db.session.add(instance)
db.session.commit()
assert len(db.session.query(models.DummyModel).all()) == 1
instance_id = db.session.query(models.DummyModel).first().id
assert isinstance(instance_id, uuid.UUID) |
I am doing it this way. In my case it's service-level testing:
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
I have added fastapi-sqlalchemy to my app and it runs well if I start from main.py, where
is added.
Now I am trying to build router-level unit test, which uses
client = TestClient(router)
to create router level client. So it won't run the code in main. the test failed and reports:Any suggestion to use it in router level unit test?
The text was updated successfully, but these errors were encountered: