Fixture set up and tear down in pytest
July 25, 2024
@pytest.fixture(scope="session", autouse=True)
def fixt_datastore(
fixt_datastore_settings: DatabaseConnectionSettings,
) -> Generator[Datastore, None, None]:
datastore = create_datastore(fixt_datastore_settings)
with datastore._session_factory.get_session() as session:
engine = session.get_bind()
assert engine.url.drivername == "sqlite"
datastore.create_all_models()
yield datastore
datastore.drop_all_models()
Autouse:
- scope mismatch (especially with tmp_path fixture) can cause issues, use fixture factories to avoid this
ScopeMismatch: You tried to access the function scoped fixture tmp_path with a session scoped request object, involved factories:
- https://github.com/tortoise/tortoise-orm/issues/638
- https://docs.pytest.org/en/6.2.x/fixture.html#autouse-order
Fixture factory:
Sharing in-memory sqlite database across tests:
- https://stackoverflow.com/questions/32681761/how-can-i-attach-an-in-memory-sqlite-database-in-python/32681822#32681822
- when you use datastore as a fixture, it will be created and destroyed for each test that uses it, the tables won't be present across tests, but we can attach an in-memory database to the sqlite engine to share the tables across tests