是否有一种干净的方法来修补对象,以便您assert_call*在测试用例中获得帮助程序,而无需实际删除操作?
例如,如何修改该@patch行以获得以下测试传递:
from unittest import TestCase
from mock import patch
class Potato(object):
def foo(self, n):
return self.bar(n)
def bar(self, n):
return n + 2
class PotatoTest(TestCase):
@patch.object(Potato, 'foo')
def test_something(self, mock):
spud = Potato()
forty_two = spud.foo(n=40)
mock.assert_called_once_with(n=40)
self.assertEqual(forty_two, 42)
Run Code Online (Sandbox Code Playgroud)
我可能会一起使用side_effect,但是我希望有一种更好的方法可以在所有函数,类方法,静态方法,未绑定方法等上以相同的方式工作.
我正在使用Python模拟模块进行测试.我想用模拟替换活动对象,并自动将对模拟对象的所有调用转发到原始对象.我认为这在标准测试术语中被称为"间谍".目前我正在测试中:
# Insert a mock replacement
orig_active_attr = server.active_attr
server.active_attr = mock.Mock()
# Set up side effects to 'proxy' to the original object
server.active_attr.meth1.side_effect = orig_active_attr.meth1
server.active_attr.meth2.side_effect = orig_active_attr.meth2
# Call the method being tested
server.method_being_tested()
# Assert stuff on the mock.
server.active_attr.meth2.assert_called_once()
Run Code Online (Sandbox Code Playgroud)
如果模拟的所有方法调用都可以在没有样板的情况下自动转发到活动对象,那将是很好的.
我想使用补丁来记录对单元测试类中的函数进行的所有函数调用,但需要原始函数仍按预期运行。我在下面创建了一个虚拟代码示例:
from mock import patch
class A(object):
def __init__(self):
self._a = 1
class B(A):
def __init__(self):
super(B, self).__init__() # TypeError: super() argument 1 must be type, not MagicMock
self._b = 11
def bar(self, b):
self._b = self._b + 1 + b
def foo(self, b):
self.bar(b)
class MockB(B):
def foo(self, b):
super(MockB, self).foo(self, b)
@patch('main.B')
def main(b_class):
b_class.side_effect = MockB
b = B()
print b._b # 11
b.foo(0)
print b._b # 12
main()
Run Code Online (Sandbox Code Playgroud)
就我而言,该类的实例b = B()实际上不在主函数中,而是在另一个模块中,因此我无法模拟该实例。我需要它一般作为 B 的所有实例的装饰器。
总结:我不确定如何单独模拟类方法,但仍然调用原始方法。之后,我想使用 …
我最近开始在 python 中使用模拟框架。似乎如果我修补一个函数,则不会调用实际代码-这意味着未实现此实际函数所做的数据库更改等。我一直试图通过事先调用函数并存储返回值并将其作为 arg 传递到 patch() 来绕过它,但是有没有更好的方法来做到这一点?理想情况下,我想要一个可以用作 a 的代码,silent observer我可以简单地询问它是否observed调用了某个函数,调用了多少次,以及使用了哪些参数
return_val = funct()
# C: Now call me again and assert that these intensive computation functions are not called but taken from cache
with patch('funct', return_value=return_val) as mock_task:
me_response = self.client.get(me_url, format='json') #should fetch from cache
assert not mock_task.called
Run Code Online (Sandbox Code Playgroud)