如何使用 pytest 和 mock 来模拟第三方类

问题描述 投票:0回答:1

我的测试代码:

from unittest.mock import patch
import pytest
from journalwatcher.journal import read_for_test

@patch("systemd.journal.Reader")
def test_read(Reader):
    read_for_test(this_boot_only=True)
    Reader.this_boot.assert_called_once()

由 pytest 执行。

我待测试的代码

import systemd.journal

def read_for_test(this_boot_only=False):
    j = systemd.journal.Reader()
    if this_boot_only:
        j.this_boot()

执行代码总是给出未调用

this_boot
的测试错误。调试显示
j
是一个
MagicMock
实例,但与
id
不同(
Reader
值)。

显然,我在这里做错了什么,但是什么?

python mocking pytest
1个回答
0
投票

为了帮助说明评论中提到的内容,“to_be_tested”的含义也可以被视为您正在测试的地方。因此,如果您想要模拟的是

systemd.journal.Reader
,那么您可以通过拥有
read_for_test
方法的任何地方来测试它。从您的示例中,您正在导入:

from journalwatcher.journal import read_for_test

因此,无论您想在测试内容和测试位置的上下文中模拟任何内容,都必须模拟为:

journalwatcher.journal.systemd.Reader

主要的收获还是要确保你的模拟是根据你正在测试的地点和内容来完成的。您可以在此处的文档中阅读有关修补的更多信息:

在哪里打补丁

© www.soinside.com 2019 - 2024. All rights reserved.