本文整理汇总了Python中mock.Mock.assert_has_calls方法的典型用法代码示例。如果您正苦于以下问题:Python Mock.assert_has_calls方法的具体用法?Python Mock.assert_has_calls怎么用?Python Mock.assert_has_calls使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mock.Mock
的用法示例。
在下文中一共展示了Mock.assert_has_calls方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_merge
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_has_calls [as 别名]
def test_merge(self):
sut = MergePdfPage(key='test_content', destkey='test_merged_content')
insert = {
'inserts': ['a'],
'deletes': [],
'data': {
'a': {
'test_content': [
'pdf page content',
'pdf watermark content'
],
}
}
}
expected = copy.deepcopy(insert)
expected['data']['a']['test_merged_content'] = ('pdf page with watermark',)
matches = MatchesSendDeltaItemInvocation(expected, sut)
send = Mock(spec=Scheduler.send)
merge_mock = Mock(spec=pdfrw.PageMerge)
merge_mock.return_value.render.return_value = 'pdf page with watermark'
with patch('pdfrw.PageMerge', merge_mock):
sut(insert, send)
self.assertEquals(send.call_count, 1)
self.assertThat(send.call_args, matches)
merge_mock.assert_has_calls([
call(),
call().add('pdf page content'),
call().add('pdf watermark content'),
call().render()
])
示例2: test_mock_asserts
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_has_calls [as 别名]
def test_mock_asserts(self):
"""The mock object has four useful helpers (assert_called_with, assert_called_once_with, assert_any_call, assert_has_calls)
that you can use to assert various things about what the mock has been called with since instantiation"""
m = Mock()
m(1)
m.assert_called_with(1)
self.assertRaises(AssertionError, m.assert_called_with, 2)
# assert_called_with asserts what the Mock's most recent call was, not that a call occurred, ever.
# calling m.assert_called_with(1) now will raise error
m(2)
m.assert_called_with(2)
self.assertRaises(AssertionError, m.assert_called_with, 1)
# assert_called_once_with is the stronger assertion that the mock has been called exactly once in its history, with the
# specified argument. (this mock has already been called twice, so both of these fail)
self.assertRaises(AssertionError, m.assert_called_once_with, 1)
self.assertRaises(AssertionError, m.assert_called_once_with, 2)
# assert_any_call means it was called with the given args at any point in history
m.assert_any_call(1)
m.assert_any_call(2)
self.assertRaises(AssertionError, m.assert_called_with, 3)
# use assert_has_calls to assert the whole call history. it takes a set of mock.call objects
m.assert_has_calls([mock.call(1), mock.call(2)])
# this fails because order of calls was m(1) then m(2) and by default any_order=False
self.assertRaises(AssertionError, m.assert_has_calls, [mock.call(2), mock.call(1)])
# this works because any_order=true
m.assert_has_calls([mock.call(2), mock.call(1)], any_order=True)
示例3: test_ensure_testing_spec_base_image_build
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_has_calls [as 别名]
def test_ensure_testing_spec_base_image_build(self):
mock_docker_client = Mock()
mock_build = Mock()
mock_docker_client.build = mock_build
testing_spec = {"build": "/path/to/docker_file_folder"}
_ensure_testing_spec_base_image(mock_docker_client, testing_spec)
mock_build.assert_has_calls([call(path="/path/to/docker_file_folder", tag="dusty_testing_base/image")])
示例4: URLTestCase
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_has_calls [as 别名]
class URLTestCase(ConnectionTestMixin, TestCase):
def setUp(self):
super(URLTestCase, self).setUp()
self.plugin = self.connection.settings.enable(Default.name, [])
self.fetch_title = Mock(return_value=succeed('title'))
self.plugin.fetcher.fetch_title = self.fetch_title
self.outgoing = self.connection.settings.enable(
OutgoingPlugin.name, [])
def test_simple(self):
self.receive('PRIVMSG {} :http://www.example.com/'
.format(self.connection.nickname))
self.fetch_title.assert_called_with(
u'http://www.example.com/',
hostname_tag=True, friendly_errors=True)
self.assertEqual(self.outgoing.last_seen.content, 'title')
def test_multiple_iris(self):
self.receive('PRIVMSG {} :http://foo.test/ http://bar.test/'
.format(self.connection.nickname))
self.fetch_title.assert_has_calls([
call(u'http://foo.test/', hostname_tag=True, friendly_errors=True),
call(u'http://bar.test/', hostname_tag=True, friendly_errors=True),
])
self.assertEqual(self.outgoing.last_seen.content, 'title')
示例5: test_include_excelude_tuple
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_has_calls [as 别名]
def test_include_excelude_tuple(self, mock_time, get_value, init):
"""
Include/exclude should accept a tuple of flags
"""
self._helper()
self.conf.watcher_added_at = 1
add_watch = Mock()
add_watch.side_effect = iter(["src descr", "conf descr"])
self.conf.watch_manager.add_watch = add_watch
filter_include = (1, 4094)
filter_exclude = (8, 16, 32)
get_value.side_effect = iter([
filter_include, filter_exclude, "dir", None, "config"
])
ored_include = 4095
ored_exclude = 56
expected_mask = ored_include & ~ored_exclude
mock_time.return_value = 2
self.conf.update_watch()
self.assertEqual(add_watch.call_count, 2)
add_watch.assert_has_calls([
call(path="dir", mask=expected_mask, auto_add=True,
rec=True, exclude_filter=self.conf.filter_wrapper),
call(path="config", mask=expected_mask),
])
self.assertEqual(
self.conf.watch_descriptors, ("src descr", "conf descr"))
self.assertEqual(self.conf.watcher_added_at, 2)
示例6: test__teardown_stage_error
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_has_calls [as 别名]
def test__teardown_stage_error(self, ntf_class_mock, rap_mock):
ntf_instance_mock = ntf_class_mock.return_value
ntf_instance_mock.name = self.OUTPUT_FILE
rap_mock.side_effect = [0, 0, 1]
test = Test(self.TEST_PLAYBOOK, self.INVENTORY, self.SETUP_PLAYBOOK, self.TEARDOWN_PLAYBOOK)
events_callback = Mock()
expected_result_status = TestResultStatus.error
expected = TestResult(test, expected_result_status)
returned = run_single_test(test, events_callback)
self.assertEqual(expected, returned)
self.assertEqual(5, events_callback.call_count)
events_callback.assert_has_calls([
call(TestStartedEvent(self.TEST_NAME, self.OUTPUT_FILE)),
call(TestLifeCycleEvent(self.TEST_NAME, TestLifeCycleStage.setup)),
call(TestLifeCycleEvent(self.TEST_NAME, TestLifeCycleStage.test)),
call(TestLifeCycleEvent(self.TEST_NAME, TestLifeCycleStage.teardown)),
call(TestFinishedEvent(self.TEST_NAME, expected_result_status))
])
self.assertEqual(3, rap_mock.call_count)
rap_mock.assert_has_calls([
call(self.INVENTORY, self.SETUP_PLAYBOOK, self.OUTPUT_FILE),
call(self.INVENTORY, self.TEST_PLAYBOOK, self.OUTPUT_FILE),
call(self.INVENTORY, self.TEARDOWN_PLAYBOOK, self.OUTPUT_FILE)
])
示例7: test_purge_deleted_datasets
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_has_calls [as 别名]
def test_purge_deleted_datasets(self, mock_get_action, mock_session_query):
# prepare
package1 = DummyClass()
package1.id = 'abc'
package1.name = 'package1_name'
package2 = DummyClass()
package2.id = 'xyz'
package2.name = 'package2_name'
mock_session_query.return_value.filter_by.return_value.filter.return_value = [package1, package2]
self.target.log_deleted_packages_in_file = Mock()
mock_action_methods = Mock("action-methods")
mock_get_action.return_value = mock_action_methods
admin_user = 'default'
self.target.admin_user = {'name': admin_user}
# execute
self.target.purge_deleted_datasets()
# verify
mock_session_query.assert_called_once_with(model.package.Package)
mock_session_query.return_value.filter_by.assert_called_once_with(state=model.State.DELETED)
mock_session_query.return_value.filter_by.return_value.filter.assert_called_once_with(ANY)
expected_logging_calls = [call(package1, ANY), call(package2, ANY)]
self.target.log_deleted_packages_in_file.assert_has_calls(expected_logging_calls)
self.assertEqual(2, mock_get_action.call_count)
self.assertEqual(mock_get_action.call_args_list, [call("dataset_purge"), call("dataset_purge")])
expected_purge_calls = [call({'user': admin_user}, {'id': package1.id}),
call({'user': admin_user}, {'id': package2.id})]
mock_action_methods.assert_has_calls(expected_purge_calls)
示例8: test_act_must_abort_hooks_after_exception
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_has_calls [as 别名]
def test_act_must_abort_hooks_after_exception(self):
# ie. after a hook raises an exception, subsequent hooks must NOT be run
# Create three plugins, and setup hook methods on it
plugin1 = _make_mock_plugin("plugin1"); setattr(plugin1, "on_"+self.my_event.name, Mock())
plugin2 = _make_mock_plugin("plugin2"); setattr(plugin2, "on_"+self.my_event.name, Mock())
plugin3 = _make_mock_plugin("plugin3"); setattr(plugin3, "on_"+self.my_event.name, Mock())
# Create a parent mock and attach child mocks to help assert order of the calls
# https://stackoverflow.com/questions/32463321/how-to-assert-method-call-order-with-python-mock
parent_mock = Mock()
parent_mock.attach_mock(plugin1.on_my_event, "plugin1_hook")
parent_mock.attach_mock(plugin2.on_my_event, "plugin2_hook")
parent_mock.attach_mock(plugin3.on_my_event, "plugin3_hook")
self.sam_plugins.register(plugin1)
self.sam_plugins.register(plugin2)
self.sam_plugins.register(plugin3)
# setup plugin2 to raise exception
plugin2.on_my_event.side_effect = IOError
# Call the act method
with self.assertRaises(IOError):
self.sam_plugins.act(self.my_event)
# Since Plugin2 raised the exception, plugin3's hook must NEVER be called
parent_mock.assert_has_calls([call.plugin1_hook(), call.plugin2_hook()])
示例9: test_display
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_has_calls [as 别名]
def test_display():
# Given
matrix = Mock()
color = Mock()
font = Mock()
draw = Mock()
sleep = Mock()
canvas = Mock()
canvas.width = 2
matrix.CreateFrameCanvas.return_value = canvas
matrix.SwapOnVSync.return_value = canvas
draw.side_effect = [1, 0, 0]
text = 'Hi'
tape = Tape(matrix, color, font, draw, sleep)
# When
tape.display(text)
# Then
draw1 = call(canvas, font, 2, 12, color, text)
draw2 = call(canvas, font, 2, 12, color, text)
draw3 = call(canvas, font, 1, 12, color, text)
draw.assert_has_calls([draw1, draw2, draw3], any_order=False)
sleep.assert_has_calls([call(0.05), call(0.05)])
assert canvas.Clear.call_count == 2
示例10: test_build_dependent_packages
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_has_calls [as 别名]
def test_build_dependent_packages(monkeypatch, mock_logger):
mock_build_with_fpm = Mock()
monkeypatch.setattr('vdt.versionplugin.buildout.shared.build_with_fpm', mock_build_with_fpm)
monkeypatch.setattr('vdt.versionplugin.buildout.shared.ruby_to_json', MagicMock())
monkeypatch.setattr('vdt.versionplugin.buildout.shared.read_dependencies_package',
Mock(side_effect=[['fabric', 'setuptools'],
['paramiko', 'fabric'],
None]))
monkeypatch.setattr('vdt.versionplugin.buildout.shared.lookup_versions',
Mock(side_effect=[[('fabric', '1.0.0'), ('setuptools', '2.0.0')],
[('paramiko', None), ('fabric', '1.0.0')]]))
dependencies = build_dependent_packages([('pyyaml', '1.0.0'), ('puka', None), ('pyasn1', '2.0.0')],
'versions.cfg')
build_with_fpm_calls = [call('pyyaml', no_python_dependencies=False, version='1.0.0'),
call('pyyaml', no_python_dependencies=True, extra_args=['-d', 'python-fabric >= 1.0.0', '-d', 'python-setuptools >= 2.0.0'], version='1.0.0'),
call('puka', no_python_dependencies=False, version=None),
call('puka', no_python_dependencies=True, extra_args=['-d', 'python-paramiko', '-d', 'python-fabric >= 1.0.0'], version=None),
call('pyasn1', no_python_dependencies=False, version='2.0.0')]
mock_build_with_fpm.assert_has_calls(build_with_fpm_calls)
assert dependencies == [('fabric', '1.0.0'), ('setuptools', '2.0.0'),
('paramiko', None)]
示例11: assert_has_calls
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_has_calls [as 别名]
def assert_has_calls():
mockFoo = Mock(spec=Foo)
print mockFoo
mockFoo.callFoo()
mockFoo.doFoo("narf")
mockFoo.doFoo("zort")
fooCalls = [call.callFoo(), call.doFoo("narf"), call.doFoo("zort")]
mockFoo.assert_has_calls(fooCalls)
fooCalls = [call.callFoo(), call.doFoo("zort"), call.doFoo("narf")]
mockFoo.assert_has_calls(fooCalls, any_order=True)
try:
mockFoo.assert_has_calls(fooCalls)
except AssertionError as e:
print e
fooCalls = [call.callFoo(), call.dooFoo("zort"), call.doFoo("narf")]
try:
mockFoo.assert_has_calls(fooCalls, any_order=True)
except AssertionError as e:
print e
try:
mockFoo.assert_has_calls(fooCalls)
except AssertionError as e:
print e
示例12: test_add_field_processors
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_has_calls [as 别名]
def test_add_field_processors(self):
event = Mock()
event.field.new_value = 'admin'
config = Mock()
processor = Mock(return_value='user12')
events.add_field_processors(
config, [processor, processor],
model='User', field='username')
assert config.add_subscriber.call_count == 5
assert not event.set_field_value.called
assert not processor.called
last_call = config.add_subscriber.mock_calls[0]
wrapper = last_call[1][0]
wrapper(event)
event.set_field_value.assert_called_once_with(
'username', 'user12')
assert event.field.new_value == 'user12'
processor.assert_has_calls([
call(new_value='admin', instance=event.instance,
field=event.field, request=event.view.request,
model=event.model, event=event),
call(new_value='user12', instance=event.instance,
field=event.field, request=event.view.request,
model=event.model, event=event),
])
示例13: test_get_cuts
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_has_calls [as 别名]
def test_get_cuts(self):
gps_station = (datetime_to_gps(datetime(2014, 1, 1, 10, 3)),
datetime_to_gps(datetime(2014, 3, 1, 11, 32)))
gps_ref_station = (datetime_to_gps(datetime(2014, 1, 5, 0, 1, 1)),
datetime_to_gps(datetime(2014, 3, 5, 3, 34, 4)))
elec_station = (datetime_to_gps(datetime(2014, 1, 3, 3, 34, 3)),
datetime_to_gps(datetime(2014, 3, 5, 23, 59, 59)))
elec_ref_station = (datetime_to_gps(datetime(2014, 1, 9, 0, 0, 0)),
datetime_to_gps(datetime(2014, 3, 15, 1, 2, 3)))
gps_mock = Mock()
elec_mock = Mock()
gps_mock.side_effect = [array(gps_station), array(gps_ref_station)]
elec_mock.side_effect = [array(elec_station), array(elec_ref_station)]
self.off._get_electronics_timestamps = elec_mock
self.off._get_gps_timestamps = gps_mock
cuts = self.off._get_cuts(sentinel.station, sentinel.ref_station)
elec_mock.assert_has_calls([call(sentinel.ref_station), call(sentinel.station)], any_order=True)
gps_mock.assert_has_calls([call(sentinel.ref_station), call(sentinel.station)], any_order=True)
self.assertEqual(len(cuts), 8)
six.assertCountEqual(self, sorted(cuts), cuts)
self.assertEqual(cuts[0], datetime(2014, 1, 1))
today = datetime.now()
self.assertEqual(cuts[-1], datetime(today.year, today.month, today.day))
示例14: test_autoCreateSensor
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_has_calls [as 别名]
def test_autoCreateSensor(self):
sensorNotFound = Mock()
sensorNotFound.status_code = 404
sensorNotFound.text = '{"errorcode": "404-001", "message": ""}'
created = Mock()
created.status_code = 201
ok = Mock()
ok.status_code = 200
request = Mock()
request.side_effect = [authRequest(), sensorNotFound, created, ok]
sensorcloud.webrequest.Requests.Request = request
device = sensorcloud.Device("FAKE", "fake")
sensor = device.sensor("sensor")
self.assertTrue("channel" in sensor)
calls = [
mock.call('GET', 'https://dsx.sensorcloud.microstrain.com/SensorCloud/devices/FAKE/sensors/sensor/channels/channel/attributes/', mock.ANY),
mock.call('PUT', 'https://dsx.sensorcloud.microstrain.com/SensorCloud/devices/FAKE/sensors/sensor/', mock.ANY),
mock.call('GET', 'https://dsx.sensorcloud.microstrain.com/SensorCloud/devices/FAKE/sensors/sensor/channels/channel/attributes/', mock.ANY)
]
request.assert_has_calls(calls)
示例15: test_validate_list_calls_validate_for_schema_values_as_necessary
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import assert_has_calls [as 别名]
def test_validate_list_calls_validate_for_schema_values_as_necessary(self):
def mock_return(schema, data, path):
if not isinstance(data, schema):
raise Invalid("")
return data
mocked = Mock(side_effect=mock_return)
with patch.object(Schema, "_validate", mocked):
Schema._validate_list([int, unicode], [], [])
self.assertFalse(mocked.called)
mocked.reset_mock()
Schema._validate_list([int, unicode], ["a"], [])
mocked.assert_has_calls([
call(int, "a", [0]),
call(unicode, "a", [0])
])
mocked.reset_mock()
Schema._validate_list([int, unicode], [1], [])
mocked.assert_called_once_with(int, 1, [0])
mocked.reset_mock()
with self.assertRaises(InvalidGroup):
Schema._validate_list([int, unicode], [None], [])
mocked.assert_has_calls([
call(int, None, [0]),
call(unicode, None, [0])
])