[英]Magic mock assert_called_once vs assert_called_once_with weird behaviour
I am noticing a weird behavior with assert_called_once
and assert_called_once_with
in python.我注意到在 python 中使用
assert_called_once
和assert_called_once_with
有一个奇怪的行为。 This is my real simple test:这是我真正的简单测试:
File module/a.py文件模块/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())
File module/b.py文件模块/b.py
class B(object):
def __init__(self, string):
print("created B")
self.string = string;
def hello(self):
return self.string
These are my tests:这些是我的测试:
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()
My problem as stated in the name of the function is:我在函数名称中提到的问题是:
Am I doing something wrong?难道我做错了什么? I am not sure but reading the documentation docs python :
我不确定,但阅读文档docs python :
assert_called_once(*args, **kwargs)
assert_Called_once(*args, **kwargs)
Assert that the mock was called exactly once.
断言模拟只被调用了一次。
This is old, but for others landing here...这是旧的,但对于其他登陆这里的人......
For python < 3.6, assert_called_once
isn't a thing and so you're actually making a mocked function call which doesn't error对于 python < 3.6,
assert_called_once
不是一回事,所以你实际上是在做一个不会出错的assert_called_once
函数调用
Please see: http://engineroom.trackmaven.com/blog/mocking-mistakes/请参阅: http : //engineroom.trackmaven.com/blog/mocking-mistakes/
You can check the call count instead.您可以改为检查呼叫计数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.