Roh*_*uva 18 python unit-testing
我正在编写单元测试,并希望检查具有函数对象的调用,如下所示:
call(u'mock', u'foobar', <function <lambda> at 0x1ea99b0>, 10)
如何检查call()是否具有我想要的所有参数,而不重现lambda?
编辑:我想澄清我正在使用mock这里的库:http://mock.readthedocs.org/en/latest/.在call我发现上面是在通话MagicMock对象,我想用检查assert_has_calls.
Roh*_*uva 30
我终于找到了如何做我想做的事.基本上,在使用时assert_has_calls,我想要一个参数匹配,无论它是什么(因为我不能lambda在测试期间每次都重新创建).
这样做的方法是使用mock.ANY.
所以,在我的例子中,这可以匹配调用:
mocked_object.assert_has_calls([
call('mock', 'foobar', mock.ANY, 10)
])
Run Code Online (Sandbox Code Playgroud)
Mic*_*Tom 11
如果你想要比mock.ANY更多的粒度,你可以创建自己的验证器类,用于调用比较,如assert_has_calls,assert_called_once_with等.
class MockValidator(object):
def __init__(self, validator):
# validator is a function that takes a single argument and returns a bool.
self.validator = validator
def __eq__(self, other):
return bool(self.validator(other))
Run Code Online (Sandbox Code Playgroud)
哪个可以用作:
import mock
my_mock = mock.Mock()
my_mock('foo', 8)
# Raises AssertionError.
my_mock.assert_called_with('foo', MockValidator(lambda x: isinstance(x, str)))
# Does not raise AssertionError.
my_mock.assert_called_with('foo', MockValidator(lambda x: isinstance(x, int)))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5857 次 |
| 最近记录: |