【发布时间】:2017-02-17 12:05:19
【问题描述】:
我注意到 python 中 assert_called_once 和 assert_called_once_with 的奇怪行为。这是我真正的简单测试:
文件模块/a.py
from .b import B
class A(object):
def __init__(self):
self.b = B("hi")
def call_b_hello(self):
print(self.b.hello())
文件模块/b.py
class B(object):
def __init__(self, string):
print("created B")
self.string = string;
def hello(self):
return self.string
这些是我的测试:
import unittest
from mock import patch
from module.a import A
class MCVETests(unittest.TestCase):
@patch('module.a.B')
def testAcallBwithMockPassCorrect(self, b1):
a = A()
b1.assert_called_once_with("hi")
a.call_b_hello()
a.b.hello.assert_called_once()
@patch('module.a.B')
def testAcallBwithMockPassCorrectWith(self, b1):
a = A()
b1.assert_called_once_with("hi")
a.call_b_hello()
a.b.hello.assert_called_once_with()
@patch('module.a.B')
def testAcallBwithMockFailCorrectWith(self, b1):
a = A()
b1.assert_called_once_with("hi")
a.b.hello.assert_called_once_with()
@patch('module.a.B')
def testAcallBwithMockPassWrong(self, b1):
a = A()
b1.assert_called_once_with("hi")
a.b.hello.assert_called_once()
if __name__ == '__main__':
unittest.main()
函数名称中所述我的问题是:
- 测试 1 正确通过
- 测试 2 正确通过
- 测试 3 正确失败(我已删除对 b 的调用)
- 测试 4 通过我不知道为什么。
我做错了吗?我不确定但阅读文档docs python:
assert_call_once(*args, **kwargs)
断言模拟只被调用了一次。
【问题讨论】:
-
我实际上无法重现这个。就我而言,3 和 4 都失败了。你使用什么版本的 Python 和什么版本的
mock库?我使用 Python 3.6 进行了测试(并使用了 stdlibunittest.mock)。 -
我使用的是python2.7,我将更改代码并使用python3.5进行检查,谢谢:)
-
在 3.5 中该函数不存在,所以我将使用这种方式解决问题:assert a.b.hello.call_count == 1 engineeringblog.yelp.com/2015/02/…
-
我无法在 Python 2.7 either 中重现这一点,使用
mock版本 2.0.0。 -
我不知道该说什么。我遇到了这个问题,我正在重写所有测试来解决这个问题。在 3.5 版中,我得到: raise AttributeError(name) AttributeError: assert_called_once 在 2.7 版中,我通过了。我无权访问 3.6 版。如果问题不合适,请关闭/删除问题,我的解决方法是在这一点上使用解决方法:)
标签: python unit-testing magicmock