是否有一种干净的方法来修补对象,以便您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)
如果模拟的所有方法调用都可以在没有样板的情况下自动转发到活动对象,那将是很好的.
如何在模拟中有条件地调用orignal方法?
在这个例子中,我只想伪造一个返回值if bar=='x'.否则我想调用原始方法.
def mocked_some_method(bar):
if bar=='x':
return 'fake'
return some_how_call_original_method(bar)
with mock.patch('mylib.foo.some_method', mocked_some_method):
do_some_stuff()
Run Code Online (Sandbox Code Playgroud)
我知道这有点奇怪.如果我想mylib.foo.some_method在侧面假装do_some_stuff()它应该是无条件的.some_method应该嘲笑所有(不是一些)呼叫.
在我的情况下,它是一个集成测试,而不是mylib.foo.some_method一个小的单元测试,并且是一种经常被使用的调度程序.在一个案例中,我需要伪造结果.
下面两个测试有什么区别? (如果有的话)
**在 python 3.10 中
import unittest
from unittest.mock import Mock, patch
class Potato(object):
def spam(self, n):
return self.foo(n=n)
def foo(self, n):
return self.bar(n)
def bar(self, n):
return n + 2
class PotatoTest(unittest.TestCase):
def test_side_effect(self):
spud = Potato()
with patch.object(spud, 'foo', side_effect=spud.foo) as mock_foo:
forty_two = spud.spam(n=40)
mock_foo.assert_called_once_with(n=40)
self.assertEqual(forty_two, 42)
def test_wraps(self):
spud = Potato()
with patch.object(spud, 'foo', wraps=spud.foo) as mock_foo:
forty_two = spud.spam(n=40)
mock_foo.assert_called_once_with(n=40)
self.assertEqual(forty_two, 42)
Run Code Online (Sandbox Code Playgroud)
一个用于side_effect保留原始方法,而另一个用于wraps有效地做同样的事情(或者至少据我所知)。
我最近开始在 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) python ×5
mocking ×3
python-mock ×2
django ×1
patch ×1
pytest ×1
python-3.10 ×1
unit-testing ×1