pytest:为什么不调用我的模拟函数

时间:2018-08-17 14:23:21

标签: python-3.x pytest monkeypatching

我只是从pytest开始,对cpputest有一些经验。我很难理解pytest中的模拟。例如,我不明白为什么此处未调用模拟函数a.ab

我有一个仅定义一个小功能的a.py:

"""Some module, defines something."""
import logging


def ab(a, b):
    logging.debug("a,b :{}".format(a, b))

然后我有一个dut.py,它调用a.ab

"""Module that uses a.ab"""

import logging
from a import ab


class Dut():
    """Device (code) under test
    """

    def run(self):
        logging.debug("ab: {}".format(ab))
        ab("a", "b")


if __name__ == '__main__':
    logging.basicConfig(level="DEBUG")
    dut = Dut()
    dut.run()

现在,我想测试ab("a", "b")是否真的被调用。那是我的考验:

from unittest.mock import Mock
from dut import Dut


def test_run_ab(monkeypatch):
    mock_a = Mock()
    monkeypatch.setattr('dut.ab', mock_a)
    dut = Dut()
    dut.run()

    # mock_a.ab("a", "b")
    mock_a.ab.assert_called_with("a", "b")

这是测试运行的结果(在pytest.ini中启用了loggin):

test_dut.py::test_run_ab 
------------------------------------ live log call  -----------------------------------
dut.py                      12 DEBUG    ab: <Mock id='47533802232072'> FAILED                                                                          [100%]

====================================== FAILURES =======================================
___________________________________ test_run_ab ____________________________________

monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x2b3b536597f0>

    def test_run_ab(monkeypatch):
        mock_a = Mock()
        monkeypatch.setattr('dut.ab', mock_a)
        dut = Dut()
        dut.run()

        # mock_a.ab("a", "b")
>       mock_a.ab.assert_called_with("a", "b")

test_dut.py:13: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

_mock_self = <Mock name='mock.ab' id='47533802232464'>, args = ('a', 'b'), kwargs = {}
expected = "ab('a', 'b')"

    def assert_called_with(_mock_self, *args, **kwargs):
        """assert that the mock was called with the specified arguments.

            Raises an AssertionError if the args and keyword args passed in are
            different to the last call to the mock."""
        self = _mock_self
        if self.call_args is None:
            expected = self._format_mock_call_signature(args, kwargs)
>           raise AssertionError('Expected call: %s\nNot called' %     (expected,))
E           AssertionError: Expected call: ab('a', 'b')
E           Not called

/usr/lib/python3.5/unittest/mock.py:785: AssertionError
---------------------------------- Captured log call ----------------------------------
dut.py                      12 DEBUG    ab: <Mock id='47533802232072'>
============================== 1 failed in 0.09 seconds ===============================

dut.run(第12行)中的登录显示我设法在dut.py中修补了ab函数。日志输出为:dut.py 12 DEBUG ab: <Mock id='47533802232072'>,因此至少不是原始函数。

如果我取消对直接致电mock_a.ab("a", "b")的评论,则测试通过(嗯,不足为奇)。

我真的没有犯错。

0 个答案:

没有答案