来自unittest.mock.patch的意外行为

时间:2018-11-05 08:54:01

标签: python unit-testing

下面的代码有什么问题?

我期望assert call_func_once_with("b")在call_func传递'a'时抛出错误。我确信该函数确实被调用过一次并带有参数“ a”。

from unittest.mock import Mock, patch
def call_func(x):
    pass

@patch("__main__.call_func")
def test_call_func(call_func):
    call_func("a")
    assert call_func.called_once_with("b")
    assert call_func.called == 1
    print(call_func.call_args)

test_call_func()

输出:

call('a')

1 个答案:

答案 0 :(得分:1)

您不是第一个注意到这类断言的奇怪事物的人(请参阅Magic mock assert_called_once vs assert_called_once_with weird behaviour

对于它的价值,我只能建议您尝试创建一个从unittest.TestCase继承的测试类,然后使用assertEqual方法来获得更一致的测试行为:

import unittest
from unittest.mock import patch, call


def call_func(x):
    pass


class MyTests(unittest.TestCase):
    @patch("__main__.call_func")
    def test_call_func(self, call_func_mock):
        call_func_mock("a")
        # assert call_func_mock.called == 1
        # assert call_func_mock.called_once_with("b")
        self.assertEqual(call_func_mock.call_count, 1)
        self.assertEqual(call_func_mock.call_args_list[0], call("b"))
        print(call_func_mock.call_args)


unittest.main()

这将产生以下(预期)结果:

F
======================================================================
FAIL: test_call_func (__main__.MyTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "C:\Python36\lib\unittest\mock.py", line 1179, in patched
    return func(*args, **keywargs)
  File "C:/scratch.py", line 16, in test_call_func
    self.assertEquals(call_func_mock.call_args_list[0], call("b"))
AssertionError: call('a') != call('b')

----------------------------------------------------------------------
Ran 1 test in 0.003s

FAILED (failures=1)

Process finished with exit code 1