Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reuse function as pytest fixture

I have a function in my code that is being used by fastapi to provide a db session to the endpoints:

def get_db() -> Generator[Session, None, None]:
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()

I want to use the same function as a pytest fixture. If I do something like the following, the fixture is not being recognized:

pytest.fixture(get_db, name="db", scope="session")

def test_item_create(db: Session) -> None:
    ...

test_item_create throws an error about db not being a fixture: fixture 'db' not found.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So I can rewrite get_db in my conftest.py and wrap it with pytest.fixture and get things working, but I was wondering if there’s a better way of reusing existing functions as fixtures. If I have more helper functions like get_db, it’d be nice not to have rewrite them for tests.

>Solution :

I think pytest cannot find the fixture as things are written in your example. Maybe you are trying to get to something like this?

db = pytest.fixture(get_db, name="db", scope="session")

def test_item_create(db: Session) -> None:
    ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading