本文整理汇总了Python中unittest.mock函数的典型用法代码示例。如果您正苦于以下问题:Python mock函数的具体用法?Python mock怎么用?Python mock使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了mock函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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')
开发者ID:johndpope,项目名称:sims4-ai-engine,代码行数:26,代码来源:testmock.py
示例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'})])
开发者ID:XayOn,项目名称:katcr,代码行数:27,代码来源:test_main.py
示例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)))
开发者ID:GaloisInc,项目名称:echronos,代码行数:30,代码来源:testmock.py
示例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)
开发者ID:MarkTseng,项目名称:cpython,代码行数:26,代码来源:testmock.py
示例5: async_gen_fixture
async def async_gen_fixture(mock):
try:
yield mock(START)
except Exception as e:
mock(e)
else:
mock(END)
开发者ID:pytest-dev,项目名称:pytest-asyncio,代码行数:7,代码来源:test_async_gen_fixtures_36.py
示例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)
开发者ID:johndpope,项目名称:sims4-ai-engine,代码行数:7,代码来源:testmock.py
示例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()()])
开发者ID:MarkTseng,项目名称:cpython,代码行数:7,代码来源:testmock.py
示例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")
开发者ID:MarkTseng,项目名称:cpython,代码行数:32,代码来源:testmock.py
示例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")
开发者ID:GaloisInc,项目名称:echronos,代码行数:32,代码来源:testmock.py
示例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')
开发者ID:johndpope,项目名称:sims4-ai-engine,代码行数:9,代码来源:testmock.py
示例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)
开发者ID:johndpope,项目名称:sims4-ai-engine,代码行数:9,代码来源:testmock.py
示例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')
开发者ID:MarkTseng,项目名称:cpython,代码行数:10,代码来源:testmock.py
示例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)
开发者ID:XayOn,项目名称:katcr,代码行数:11,代码来源:test_main.py
示例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))
开发者ID:johndpope,项目名称:sims4-ai-engine,代码行数:12,代码来源:testmock.py
示例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)
开发者ID:MarkTseng,项目名称:cpython,代码行数:12,代码来源:testmock.py
示例16: test_call_args_two_tuple
def test_call_args_two_tuple(self):
mock = Mock()
mock(1, a=3)
mock(2, b=4)
self.assertEqual(len(mock.call_args), 2)
(args, kwargs) = mock.call_args
self.assertEqual(args, (2,))
self.assertEqual(kwargs, dict(b=4))
expected_list = [((1,), dict(a=3)), ((2,), dict(b=4))]
for (expected, call_args) in zip(expected_list, mock.call_args_list):
self.assertEqual(len(call_args), 2)
self.assertEqual(expected[0], call_args[0])
self.assertEqual(expected[1], call_args[1])
开发者ID:johndpope,项目名称:sims4-ai-engine,代码行数:13,代码来源:testmock.py
示例17: 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))
开发者ID:GaloisInc,项目名称:echronos,代码行数:13,代码来源:testmock.py
示例18: test_assert_called_with
def test_assert_called_with(self):
mock = Mock()
mock()
# Will raise an exception if it fails
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")
开发者ID:GaloisInc,项目名称:echronos,代码行数:13,代码来源:testmock.py
示例19: test_assert_called_with_function_spec
def test_assert_called_with_function_spec(self):
def f(a, b, c, d=None):
pass
mock = Mock(spec=f)
mock(1, b=2, c=3)
mock.assert_called_with(1, 2, 3)
mock.assert_called_with(a=1, b=2, c=3)
self.assertRaises(AssertionError, mock.assert_called_with, 1, b=3, c=2)
# Expected call doesn't match the spec's signature
with self.assertRaises(AssertionError) as cm:
mock.assert_called_with(e=8)
self.assertIsInstance(cm.exception.__cause__, TypeError)
开发者ID:chayao2015,项目名称:kbengine,代码行数:14,代码来源:testmock.py
示例20: test_subclassing
def test_subclassing(self):
class Subclass(Mock):
pass
mock = Subclass()
self.assertIsInstance(mock.foo, Subclass)
self.assertIsInstance(mock(), Subclass)
class Subclass(Mock):
def _get_child_mock(self, **kwargs):
return Mock(**kwargs)
mock = Subclass()
self.assertNotIsInstance(mock.foo, Subclass)
self.assertNotIsInstance(mock(), Subclass)
开发者ID:MarkTseng,项目名称:cpython,代码行数:15,代码来源:testmock.py
注:本文中的unittest.mock函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论