有没有办法使用模拟来模拟 pytest 中的完整代码?
例如,每当测试找到
database.db.session.using_bind("reader")
我要删除lust_bind(“读取器”))
并与
database.db.session
使用模拟器
一起使用conftest.py.py
尝试使用它来删除)
>
@pytest.fixture(scope='function')
def session(mocker):
mocker.patch('store.database.db.session.using_bind', return_value=_db.db.session)
但是到目前为止什么都没有。
正在测试的代码:
from store import database
results = database.db.session.using_bind("reader").query(database.Order.id).join(database.Shop).filter(database.Shop.deleted == False).all(),
我得到
AttributeError: 'scoped_session' object has no attribute 'using_bind' as an error.
For instance, every time a test finds
database.db.session.using_bind("reader")
I want to remove the using_bind("reader"))
and just work with
database.db.session
using mocker
Tried to use it like this in conftest.py
@pytest.fixture(scope='function')
def session(mocker):
mocker.patch('store.database.db.session.using_bind', return_value=_db.db.session)
But nothing has worked so far.
Code under test:
from store import database
results = database.db.session.using_bind("reader").query(database.Order.id).join(database.Shop).filter(database.Shop.deleted == False).all(),
and I get
AttributeError: 'scoped_session' object has no attribute 'using_bind' as an error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
让我们从一个MRE开始,其中正在测试的代码使用假数据库:
运行此测试失败:
因此,我们要模拟
session.used_bind
incode_under_teste_test
,以便它返回<<代码>会话 - 这将使我们的测试通过。我们使用
patch
这样做,例如:请注意,我的代码位于名为
test.py
的文件中,因此我的patch> patch
呼叫适用于测试
模块 - 您需要对其进行调整,以指向您自己的代码中测试的模块。还要注意,在调用正在测试的代码之前,我需要设置模拟。
Let's start with an MRE where the code under test uses a fake database:
Running this test fails with:
So we want to mock
session.using_bind
incode_under_test
so that it returnssession
-- that will make our test pass.We do that using
patch
, like so:Note that my code is in a file called
test.py
, so mypatch
call applies to thetest
module -- you will need to adjust this to point to the module under test in your own code.Note also that I need to set up my mock before calling the code under test.