[英]Reuse function as pytest fixture
我的代码中有一个 function,fastapi 使用它向端点提供一个 db session:
def get_db() -> Generator[Session, None, None]:
try:
db = SessionLocal()
yield db
finally:
db.close()
我想使用与 pytest 夹具相同的 function。 如果我执行以下操作,则无法识别灯具:
pytest.fixture(get_db, name="db", scope="session")
def test_item_create(db: Session) -> None:
...
test_item_create
抛出一个关于db
not being a fixture: fixture 'db' not found
的错误。
所以我可以在我的conftest.py
中重写get_db
并用pytest.fixture
包装它并让它工作,但我想知道是否有更好的方法将现有函数重用为固定装置。 如果我有更多像get_db
这样的辅助函数,最好不要为测试重写它们。
我认为pytest
找不到夹具,因为您的示例中已经写了东西。 也许你正在尝试做这样的事情?
db = pytest.fixture(get_db, name="db", scope="session")
def test_item_create(db: Session) -> None:
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.