Home > Blockchain >  Reuse function as pytest fixture
Reuse function as pytest fixture

Time:01-27

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.

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.

CodePudding user response:

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:
    ...

CodePudding user response:

You can use the @pytest.fixture decorator to create a fixture from your get_db() function:

@pytest.fixture(name="db", scope="session")
def get_db() -> Generator[Session, None, None]:
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()

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