修补时,assert_called_once应该没有失败

时间:2017-05-15 21:52:18

标签: python mocking python-unittest

在python unittest中,如果多次调用mock.assert_called_once(),则会失败。修补时我没有看到这种行为。

ugh.py

def foo(*args):
    pass

def bar():
    foo(1)
    foo(2)

tests.py

from unittest import TestCase, main
from unittest.mock import patch
from ugh import bar

class Test(TestCase):

    @patch('ugh.foo')
    def test_called_once(self, foo_mock):
        bar()
        foo_mock.assert_called_once()

    @patch('ugh.foo')
    def test_called_count_one(self, foo_mock):
        bar()
        self.assertEqual(foo_mock.call_count, 1)

if __name__ == '__main__':
    main()

测试输出。

razorclaw% python tests.py
F.
======================================================================
FAIL: test_called_count_one (__main__.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib64/python3.4/unittest/mock.py", line 1142, in patched
    return func(*args, **keywargs)
  File "tests.py", line 15, in test_called_count_one
    self.assertEqual(foo_mock.call_count, 1)
AssertionError: 2 != 1

----------------------------------------------------------------------
Ran 2 tests in 0.002s

FAILED (failures=1)

在linux上使用python 3.4.6

2 个答案:

答案 0 :(得分:1)

assert_called_once在3.4中不存在。它直到3.6才存在。如果您使用的是3.4,则可以使用assert_called_once_with

答案 1 :(得分:0)

像这样运行测试:

python -m unittest tests