本文整理汇总了Python中unittest.mock函数的典型用法代码示例。如果您正苦于以下问题:Python mock函数的具体用法?Python mock怎么用?Python mock使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了mock函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_reset_mock
def test_reset_mock(self):
parent = Mock()
spec = ['something']
mock = Mock(name='child', parent=parent, spec=spec)
mock(sentinel.Something, something=sentinel.SomethingElse)
something = mock.something
mock.something()
mock.side_effect = sentinel.SideEffect
return_value = mock.return_value
return_value()
mock.reset_mock()
self.assertEqual(mock._mock_name, 'child', 'name incorrectly reset')
self.assertEqual(mock._mock_parent, parent, 'parent incorrectly reset')
self.assertEqual(mock._mock_methods, spec, 'methods incorrectly reset')
self.assertFalse(mock.called, 'called not reset')
self.assertEqual(mock.call_count, 0, 'call_count not reset')
self.assertEqual(mock.call_args, None, 'call_args not reset')
self.assertEqual(mock.call_args_list, [], 'call_args_list not reset')
self.assertEqual(mock.method_calls, [], 'method_calls not initialised correctly: %r != %r' % (mock.method_calls, []))
self.assertEqual(mock.mock_calls, [])
self.assertEqual(mock.side_effect, sentinel.SideEffect, 'side_effect incorrectly reset')
self.assertEqual(mock.return_value, return_value, 'return_value incorrectly reset')
self.assertFalse(return_value.called, 'return value mock not reset')
self.assertEqual(mock._mock_children, {'something': something}, 'children reset incorrectly')
self.assertEqual(mock.something, something, 'children incorrectly cleared')
self.assertFalse(mock.something.called, 'child not reset')
示例2: test_main_with_shortener
def test_main_with_shortener():
"""Test usage with url shortener."""
from katcr import main, get_from_short
from unittest.mock import patch, call
opts = {'<SEARCH_TERM>': "foo", '--search-engines': ['Katcr'],
'--interactive': False, '--open': False, '-d': False,
'--shortener': ['bar'],
'--disable-shortener': False, '--pages': [1]}
with patch('katcr.Katcr') as mock:
with patch('katcr.get_from_short') as short_mock:
with patch('katcr.docopt', side_effect=(opts,)):
main()
mock().search.assert_called_with(opts['<SEARCH_TERM>'], 1)
short_mock.assert_called_with('bar', None)
class Foo:
# pylint: disable=too-few-public-methods, missing-docstring
text = "foo"
with patch('katcr.requests.post', return_value=Foo) as mock:
with patch('katcr.docopt', side_effect=(opts,)):
result = list(get_from_short(
"foo.com", [("1", "2"), ("3", "4")]))
assert [result == [('1', '2', 'foo.com/foo'),
('3', '4', 'foo.com/foo')]]
mock.assert_has_calls([call('foo.com', data={'magnet': '2'}),
call('foo.com', data={'magnet': '4'})])
示例3: test_assert_has_calls
def test_assert_has_calls(self):
kalls1 = [call(1, 2), ({"a": 3},), ((3, 4),), call(b=6), ("", (1,), {"b": 6})]
kalls2 = [call.foo(), call.bar(1)]
kalls2.extend(call.spam().baz(a=3).call_list())
kalls2.extend(call.bam(set(), foo={}).fish([1]).call_list())
mocks = []
for mock in Mock(), MagicMock():
mock(1, 2)
mock(a=3)
mock(3, 4)
mock(b=6)
mock(1, b=6)
mocks.append((mock, kalls1))
mock = Mock()
mock.foo()
mock.bar(1)
mock.spam().baz(a=3)
mock.bam(set(), foo={}).fish([1])
mocks.append((mock, kalls2))
for mock, kalls in mocks:
for i in range(len(kalls)):
for step in 1, 2, 3:
these = kalls[i : i + step]
mock.assert_has_calls(these)
if len(these) > 1:
self.assertRaises(AssertionError, mock.assert_has_calls, list(reversed(these)))
示例4: test_side_effect
def test_side_effect(self):
mock = Mock()
def effect(*args, **kwargs):
raise SystemError('kablooie')
mock.side_effect = effect
self.assertRaises(SystemError, mock, 1, 2, fish=3)
mock.assert_called_with(1, 2, fish=3)
results = [1, 2, 3]
def effect():
return results.pop()
mock.side_effect = effect
self.assertEqual([mock(), mock(), mock()], [3, 2, 1],
"side effect not used correctly")
mock = Mock(side_effect=sentinel.SideEffect)
self.assertEqual(mock.side_effect, sentinel.SideEffect,
"side effect in constructor not used")
def side_effect():
return DEFAULT
mock = Mock(side_effect=side_effect, return_value=sentinel.RETURN)
self.assertEqual(mock(), sentinel.RETURN)
示例5: async_gen_fixture
async def async_gen_fixture(mock):
try:
yield mock(START)
except Exception as e:
mock(e)
else:
mock(END)
示例6: test_wraps_calls
def test_wraps_calls(self):
real = Mock()
mock = Mock(wraps=real)
self.assertEqual(mock(), real())
real.reset_mock()
mock(1, 2, fish=3)
real.assert_called_with(1, 2, fish=3)
示例7: test_adding_return_value_mock
def test_adding_return_value_mock(self):
for Klass in Mock, MagicMock:
mock = Klass()
mock.return_value = MagicMock()
mock()()
self.assertEqual(mock.mock_calls, [call(), call()()])
示例8: test_call
def test_call(self):
mock = Mock()
self.assertTrue(is_instance(mock.return_value, Mock),
"Default return_value should be a Mock")
result = mock()
self.assertEqual(mock(), result,
"different result from consecutive calls")
mock.reset_mock()
ret_val = mock(sentinel.Arg)
self.assertTrue(mock.called, "called not set")
self.assertEqual(mock.call_count, 1, "call_count incoreect")
self.assertEqual(mock.call_args, ((sentinel.Arg,), {}),
"call_args not set")
self.assertEqual(mock.call_args_list, [((sentinel.Arg,), {})],
"call_args_list not initialised correctly")
mock.return_value = sentinel.ReturnValue
ret_val = mock(sentinel.Arg, key=sentinel.KeyArg)
self.assertEqual(ret_val, sentinel.ReturnValue,
"incorrect return value")
self.assertEqual(mock.call_count, 2, "call_count incorrect")
self.assertEqual(mock.call_args,
((sentinel.Arg,), {'key': sentinel.KeyArg}),
"call_args not set")
self.assertEqual(mock.call_args_list, [
((sentinel.Arg,), {}),
((sentinel.Arg,), {'key': sentinel.KeyArg})
],
"call_args_list not set")
示例9: test_reset_mock
def test_reset_mock(self):
parent = Mock()
spec = ["something"]
mock = Mock(name="child", parent=parent, spec=spec)
mock(sentinel.Something, something=sentinel.SomethingElse)
something = mock.something
mock.something()
mock.side_effect = sentinel.SideEffect
return_value = mock.return_value
return_value()
mock.reset_mock()
self.assertEqual(mock._mock_name, "child", "name incorrectly reset")
self.assertEqual(mock._mock_parent, parent, "parent incorrectly reset")
self.assertEqual(mock._mock_methods, spec, "methods incorrectly reset")
self.assertFalse(mock.called, "called not reset")
self.assertEqual(mock.call_count, 0, "call_count not reset")
self.assertEqual(mock.call_args, None, "call_args not reset")
self.assertEqual(mock.call_args_list, [], "call_args_list not reset")
self.assertEqual(
mock.method_calls, [], "method_calls not initialised correctly: %r != %r" % (mock.method_calls, [])
)
self.assertEqual(mock.mock_calls, [])
self.assertEqual(mock.side_effect, sentinel.SideEffect, "side_effect incorrectly reset")
self.assertEqual(mock.return_value, return_value, "return_value incorrectly reset")
self.assertFalse(return_value.called, "return value mock not reset")
self.assertEqual(mock._mock_children, {"something": something}, "children reset incorrectly")
self.assertEqual(mock.something, something, "children incorrectly cleared")
self.assertFalse(mock.something.called, "child not reset")
示例10: test_assert_called_with
def test_assert_called_with(self):
mock = Mock()
mock()
mock.assert_called_with()
self.assertRaises(AssertionError, mock.assert_called_with, 1)
mock.reset_mock()
self.assertRaises(AssertionError, mock.assert_called_with)
mock(1, 2, 3, a='fish', b='nothing')
mock.assert_called_with(1, 2, 3, a='fish', b='nothing')
示例11: test_java_exception_side_effect
def test_java_exception_side_effect(self):
import java
mock = Mock(side_effect=java.lang.RuntimeException('Boom!'))
try:
mock(1, 2, fish=3)
except java.lang.RuntimeException:
pass
self.fail('java exception not raised')
mock.assert_called_with(1, 2, fish=3)
示例12: test_setting_call
def test_setting_call(self):
mock = Mock()
def __call__(self, a):
return self._mock_call(a)
type(mock).__call__ = __call__
mock('one')
mock.assert_called_with('one')
self.assertRaises(TypeError, mock, 'one', 'two')
示例13: test_main
def test_main():
"""Test argument parsing and calling."""
from katcr import main
from unittest.mock import patch
opts = {'<SEARCH_TERM>': "foo", '--search-engines': ['Katcr'],
'--interactive': False, '--open': False, '-d': False,
'--disable-shortener': True, '--pages': [1]}
with patch('katcr.Katcr') as mock:
with patch('katcr.docopt', side_effect=(opts,)):
main()
mock().search.assert_called_with(opts['<SEARCH_TERM>'], 1)
示例14: test_repr
def test_repr(self):
mock = Mock(name='foo')
self.assertIn('foo', repr(mock))
self.assertIn("'%s'" % id(mock), repr(mock))
mocks = [(Mock(), 'mock'), (Mock(name='bar'), 'bar')]
for (mock, name) in mocks:
self.assertIn('%s.bar' % name, repr(mock.bar))
self.assertIn('%s.foo()' % name, repr(mock.foo()))
self.assertIn('%s.foo().bing' % name, repr(mock.foo().bing))
self.assertIn('%s()' % name, repr(mock()))
self.assertIn('%s()()' % name, repr(mock()()))
self.assertIn('%s()().foo.bar.baz().bing' % name, repr(mock()().foo.bar.baz().bing))
示例15: test_java_exception_side_effect
def test_java_exception_side_effect(self):
import java
mock = Mock(side_effect=java.lang.RuntimeException("Boom!"))
# can't use assertRaises with java exceptions
try:
mock(1, 2, fish=3)
except java.lang.RuntimeException:
pass
else:
self.fail('java exception not raised')
mock.assert_called_with(1,2, fish=3)