[英]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:我的代码中有一个 function,fastapi 使用它向端点提供一个 db session:
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.我想使用与 pytest 夹具相同的 function。 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
. test_item_create
抛出一个关于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.所以我可以在我的conftest.py
中重写get_db
并用pytest.fixture
包装它并让它工作,但我想知道是否有更好的方法将现有函数重用为固定装置。 If I have more helper functions like get_db
, it'd be nice not to have rewrite them for tests.如果我有更多像get_db
这样的辅助函数,最好不要为测试重写它们。
I think pytest
cannot find the fixture as things are written in your example.我认为pytest
找不到夹具,因为您的示例中已经写了东西。 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:
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.