【发布时间】:2022-07-04 22:32:14
【问题描述】:
我有一个返回 SQLAlchemy 引擎对象的函数
create_db.py:
from sqlalchemy import create_engine
def init_db():
return create_engine("sqlite://", echo=True, future=True)
我有一个测试试图使用 pytest 的 monkeypatch 来模拟对 create_engine 的调用。
test_db.py:
import sqlalchemy
from create_db import init_db
def test_correct_db_path_selected(monkeypatch):
def mocked_create_engine():
return "test_connection_string"
monkeypatch.setattr(sqlalchemy, "create_engine", mocked_create_engine())
engine = init_db()
assert engine == "test_connection_string"
当我运行 pytest 时,测试失败,因为返回的是真正的 sqlalchemy 引擎对象,而不是模拟的字符串。
AssertionError: assert Engine(sqlite://) == 'test_connection_string'
我尝试了以下对 setattr 的调用,但它们都以相同的方式失败:
monkeypatch.setattr("sqlalchemy.engine.create.create_engine", mocked_create_engine)
monkeypatch.setattr(sqlalchemy.engine.create, "create_engine", mocked_create_engine)
monkeypatch.setattr(sqlalchemy.engine, "create_engine", mocked_create_engine)
我已经从 pytest 文档中获得了 basic examples,但它不包括库中的静态函数。有人对我做错了什么有任何建议吗?
【问题讨论】:
标签: python sqlalchemy pytest monkeypatching