Python 3.x pytest:为什么我的模拟函数没有被调用

Python 3.x pytest:为什么我的模拟函数没有被调用,python-3.x,pytest,monkeypatching,Python 3.x,Pytest,Monkeypatching,我现在才开始学习pytest,对CpuTest有一些经验。在pytest中嘲笑对我来说很难理解。例如,我不明白为什么这里不调用模拟函数a.ab: 我有一个.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.a

我现在才开始学习pytest,对CpuTest有一些经验。在pytest中嘲笑对我来说很难理解。例如,我不明白为什么这里不调用模拟函数
a.ab

我有一个.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\u dut.py::test\u run\u ab
------------------------------------实时日志呼叫-----------------------------------
dut.py 12调试ab:失败[100%]
=========================================================故障=======================================
___________________________________测试运行____________________________________
monkeypatch=
def测试运行ab(monkeypatch):
mock_a=mock()
monkeypatch.setattr('dut.ab',mock_a)
dut=dut()
dut.run()
#模拟a.ab(“a”、“b”)
>mock_a.ab.assert_称为带(“a”、“b”)
试验件尺寸:13:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
_mock_self=,args=('a','b'),kwargs={}
expected=“ab('a','b')”
使用(_mock_self,*args,**kwargs)调用def assert_:
“”“断言使用指定的参数调用了模拟。
如果传入的参数和关键字参数不正确,则引发AssertionError
与上次对模拟对象的调用不同
self=\u mock\u self
如果self.call_args为无:
预期=自。\格式\模拟\调用\签名(args、kwargs)
>raise AssertionError('预期调用:%s\n未调用“%”(预期,))
E断言错误:预期调用:ab('a','b')
我没打电话
/usr/lib/python3.5/unittest/mock.py:785:AssertionError
----------------------------------捕获的日志调用----------------------------------
dut.py 12调试ab:
===========================================1在0.09秒内失败===============================
登录
dut.run
(第12行)显示我成功地在dut.py中修补了
ab
函数。日志输出为:
dut.py 12 DEBUG ab:
,因此它至少不是原始函数

如果我取消注释对
mock_a.ab(“a”、“b”)
的直接调用,测试就会通过(这并不奇怪)


我真的不明白我的错误

为什么要测试名为的mock_a.ab.assert_
mock_a
dut.ab
的替代品,因此
mock_a.ab
实际上是
dut.ab.ab
。检查
mock\u a.assert\u调用了
。谢谢,我的眼睛上有西红柿……不用担心,我们都会这样:)
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 ===============================