本文整理汇总了Python中mock.Mock.side_effect方法的典型用法代码示例。如果您正苦于以下问题:Python Mock.side_effect方法的具体用法?Python Mock.side_effect怎么用?Python Mock.side_effect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mock.Mock
的用法示例。
在下文中一共展示了Mock.side_effect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_rmtree_success
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import side_effect [as 别名]
def test_rmtree_success(self):
dir1_list = ["dir2", "file"]
empty_list = []
mock_listdir = Mock()
mock_listdir.side_effect = [dir1_list, empty_list]
mock_isdir = Mock()
mock_isdir.side_effect = [True, False]
mock_unlink = Mock()
mock_unlink.return_value = 0
mock_rmdir = Mock()
mock_rmdir.return_value = 0
mock_islink = Mock()
mock_islink.return_value = False
with nested(
patch("glusterfs.gfapi.Volume.listdir", mock_listdir),
patch("glusterfs.gfapi.Volume.isdir", mock_isdir),
patch("glusterfs.gfapi.Volume.islink", mock_islink),
patch("glusterfs.gfapi.Volume.unlink", mock_unlink),
patch("glusterfs.gfapi.Volume.rmdir", mock_rmdir),
):
self.vol.rmtree("dir1")
mock_rmdir.assert_any_call("dir1/dir2")
mock_unlink.assert_called_once_with("dir1/file")
mock_rmdir.assert_called_with("dir1")
示例2: test_object_graph_partial_use
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import side_effect [as 别名]
def test_object_graph_partial_use():
"""
Partial initialization succeeds partially and is recoverable.
"""
registry = Registry()
create_first = Mock()
create_first.return_value = "first"
create_second = Mock()
create_second.side_effect = [Exception, "second"]
create_third = Mock()
create_third.side_effect = "third"
registry.bind("first", create_first)
registry.bind("second", create_second)
registry.bind("third", create_third)
graph = create_object_graph("test", registry=registry)
# exception raised from initial call to create_second
assert_that(calling(graph.use).with_args("first", "second", "third"), raises(Exception))
# first and second were called, but not third
assert_that(create_first.call_count, is_(equal_to(1)))
assert_that(create_second.call_count, is_(equal_to(1)))
assert_that(create_third.call_count, is_(equal_to(0)))
# second call succeeds
[first, second, third] = graph.use("first", "second", "third")
# first was not called, second was called again, and third called for the first time
assert_that(create_first.call_count, is_(equal_to(1)))
assert_that(create_second.call_count, is_(equal_to(2)))
assert_that(create_third.call_count, is_(equal_to(1)))
示例3: test_rmtree_ignore_unlink_rmdir_exception
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import side_effect [as 别名]
def test_rmtree_ignore_unlink_rmdir_exception(self):
dir1_list = ["dir2", "file"]
empty_list = []
mock_listdir = Mock()
mock_listdir.side_effect = [dir1_list, empty_list]
mock_isdir = Mock()
mock_isdir.side_effect = [True, False]
mock_unlink = Mock()
mock_unlink.side_effect = [OSError]
mock_rmdir = Mock()
mock_rmdir.side_effect = [0, OSError]
mock_islink = Mock()
mock_islink.return_value = False
with nested(patch("gluster.gfapi.Volume.listdir", mock_listdir),
patch("gluster.gfapi.Volume.isdir", mock_isdir),
patch("gluster.gfapi.Volume.islink", mock_islink),
patch("gluster.gfapi.Volume.unlink", mock_unlink),
patch("gluster.gfapi.Volume.rmdir", mock_rmdir)):
self.vol.rmtree("dir1", True)
mock_rmdir.assert_any_call("dir1/dir2")
mock_unlink.assert_called_once_with("dir1/file")
mock_rmdir.assert_called_with("dir1")
示例4: test_get_cuts
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import side_effect [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))
示例5: test_agent_policies
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import side_effect [as 别名]
def test_agent_policies(self):
# set up data
gc = Mock()
service_key = "service_key"
resource_id = "resource_id"
pdpm = PolicyDecisionPointManager(gc)
invocation = Mock()
mock_header = Mock()
invocation.message_annotations = {}
invocation.message = {"argument1": 0}
invocation.headers = {
"op": "op",
"process": "process",
"request": "request",
"ion-actor-id": "ion-actor-id",
"receiver": "resource-registry",
"sender-type": "sender-type",
"sender-service": "Unknown",
"ion-actor-roles": {"org_name": ["SUPERUSER"]},
}
invocation.get_message_receiver.return_value = "service_key"
invocation.get_service_name.return_value = "Unknown"
invocation.get_message_sender.return_value = ["Unknown", "Unknown"]
def get_header_value(key, default):
return invocation.headers.get(key, default)
mock_header.side_effect = get_header_value
invocation.get_header_value = mock_header
mock_args = Mock()
process = Mock()
process.org_governance_name = "org_name"
process.resource_id = "resource_id"
invocation.args = {"process": process}
def get_arg_value(key, default="Unknown"):
return invocation.args.get(key, default)
mock_args.side_effect = get_arg_value
invocation.get_arg_value = mock_args
gc.system_root_org_name = "sys_org_name"
# check that service policies result in denying the request
pdpm.set_service_policy_rules(service_key, self.deny_SUPERUSER_rule)
pdpm.set_resource_policy_rules(resource_id, self.permit_SUPERUSER_rule)
response = pdpm.check_agent_request_policies(invocation)
self.assertEqual(response.value, "Deny")
# check that resource policies result in denying the request
pdpm.set_service_policy_rules(service_key, self.permit_SUPERUSER_rule)
pdpm.set_resource_policy_rules(resource_id, self.deny_SUPERUSER_rule)
response = pdpm.check_agent_request_policies(invocation)
self.assertEqual(response.value, "Deny")
# check that both service and resource policies need to allow a request
pdpm.set_service_policy_rules(service_key, self.permit_SUPERUSER_rule)
pdpm.set_resource_policy_rules(resource_id, self.permit_SUPERUSER_rule)
response = pdpm.check_agent_request_policies(invocation)
self.assertEqual(response.value, "Permit")
示例6: test_side_effect
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import side_effect [as 别名]
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)
示例7: test_service_policies
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import side_effect [as 别名]
def test_service_policies(self):
gc = Mock()
service_key = 'service_key'
pdpm = PolicyDecisionPointManager(gc)
# see that the PDP for service is the default
self.assertEqual(pdpm.get_service_pdp(service_key), pdpm.load_common_service_pdp)
pdpm.load_service_policy_rules(service_key, self.permit_ION_MANAGER_rule)
# see that the PDP for service is not the default anymore
self.assertNotEqual(pdpm.get_service_pdp(service_key), pdpm.load_common_service_pdp)
# check request without a service_key raises NotFound error
invocation = Mock()
invocation.message_annotations = {}
invocation.get_message_receiver.return_value = None
with self.assertRaises(NotFound) as chk_res:
pdpm.check_service_request_policies(invocation)
self.assertIn(chk_res.exception.message, 'No receiver for this message')
# check that, because actor does not have ION_MANAGER role, policy evaluates to a denial
# (really Not Applicable, because of the inelegant hack of a policy we are setting up our pdp with)
mock_header = Mock()
invocation.message_annotations = {}
invocation.message = {'argument1': 0}
invocation.headers = {'op': 'op', 'process': 'process', 'request': 'request', 'ion-actor-id': 'ion-actor-id', 'receiver': 'resource-registry',
'sender-type': 'sender-type', 'sender-service': 'Unknown', 'ion-actor-roles': {'org_name': ['ion-actor-roles']}}
invocation.get_message_receiver.return_value = 'service_key'
invocation.get_service_name.return_value = 'Unknown'
invocation.get_message_sender.return_value = ['Unknown','Unknown']
def get_header_value(key, default):
return invocation.headers.get(key, default)
mock_header.side_effect = get_header_value
invocation.get_header_value = mock_header
mock_args = Mock()
process = Mock()
process.org_governance_name = 'org_name'
invocation.args = {'process': process}
def get_arg_value(key, default):
return invocation.args.get(key, default)
mock_args.side_effect = get_arg_value
invocation.get_arg_value = mock_args
gc.system_root_org_name = 'sys_org_name'
response = pdpm.check_service_request_policies(invocation)
self.assertEqual(response.value, "NotApplicable")
# check that policy evaluates to Permit because actor has ION_MANAGER role
invocation.message_annotations = {}
invocation.headers = {'op': 'op', 'process': 'process', 'request': 'request', 'ion-actor-id': 'ion-actor-id', 'receiver': 'resource-registry',
'sender-type': 'sender-type', 'sender-service': 'sender-service', 'ion-actor-roles': {'sys_org_name': ['ION_MANAGER']}}
response = pdpm.check_service_request_policies(invocation)
self.assertEqual(response.value, "Permit")
示例8: test_makedirs_success
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import side_effect [as 别名]
def test_makedirs_success(self):
mock_glfs_mkdir = Mock()
mock_glfs_mkdir.side_effect = [0, 0]
mock_exists = Mock()
mock_exists.side_effect = (False, True, False)
with nested(patch("gluster.gfapi.api.glfs_mkdir", mock_glfs_mkdir),
patch("gluster.gfapi.Volume.exists", mock_exists)):
self.vol.makedirs("dir1/", 0775)
self.assertEqual(mock_glfs_mkdir.call_count, 1)
mock_glfs_mkdir.assert_any_call(self.vol.fs, "dir1/", 0775)
示例9: test_notification_dbus
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import side_effect [as 别名]
def test_notification_dbus(self):
'''
Test mocked Linux DBus for plyer.notification.
'''
notif = platform_import(
platform='linux',
module_name='notification'
)
self.assertIn('NotifyDbus', dir(notif))
# (3) mocked Interface called from dbus
interface = Mock()
interface.side_effect = (interface, )
# (2) mocked SessionBus called from dbus
session_bus = Mock()
session_bus.side_effect = (session_bus, )
# (1) mocked dbus for import
dbus = Mock(SessionBus=session_bus, Interface=interface)
# inject the mocked module
self.assertNotIn('dbus', sys.modules)
sys.modules['dbus'] = dbus
try:
notif = notif.instance()
self.assertIn('NotifyDbus', str(notif))
# call notify()
self.show_notification(notif)
# check whether Mocks were called
dbus.SessionBus.assert_called_once()
session_bus.get_object.assert_called_once_with(
'org.freedesktop.Notifications',
'/org/freedesktop/Notifications'
)
interface.Notify.assert_called_once_with(
TestNotification.data['app_name'],
0,
TestNotification.data['app_icon'],
TestNotification.data['title'],
TestNotification.data['message'],
[], [],
TestNotification.data['timeout'] * 1000
)
finally:
del sys.modules['dbus']
self.assertNotIn('dbus', sys.modules)
示例10: test_agent_policies
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import side_effect [as 别名]
def test_agent_policies(self):
# set up data
gc = Mock()
service_key = 'service_key'
resource_id = 'resource_id'
pdpm = PolicyDecisionPointManager(gc)
invocation = Mock()
mock_header = Mock()
invocation.message_annotations = {}
invocation.message = {'argument1': 0 }
invocation.headers = {'op': 'op', 'process': 'process', 'request': 'request', 'ion-actor-id': 'ion-actor-id', 'receiver': 'resource-registry',
'sender-type': 'sender-type', 'sender-service': 'Unknown', 'ion-actor-roles': {'org_name': ['ION_MANAGER']}}
invocation.get_message_receiver.return_value = 'service_key'
invocation.get_service_name.return_value = 'Unknown'
invocation.get_message_sender.return_value = ['Unknown','Unknown']
def get_header_value(key, default):
return invocation.headers.get(key, default)
mock_header.side_effect = get_header_value
invocation.get_header_value = mock_header
mock_args = Mock()
process = Mock()
process.org_governance_name = 'org_name'
process.resource_id = 'resource_id'
invocation.args = {'process': process}
def get_arg_value(key, default='Unknown'):
return invocation.args.get(key, default)
mock_args.side_effect = get_arg_value
invocation.get_arg_value = mock_args
gc.system_root_org_name = 'sys_org_name'
# check that service policies result in denying the request
pdpm.load_service_policy_rules(service_key, self.deny_ION_MANAGER_rule)
pdpm.load_resource_policy_rules(resource_id, self.permit_ION_MANAGER_rule)
response = pdpm.check_agent_request_policies(invocation)
self.assertEqual(response.value, "Deny")
# check that resource policies result in denying the request
pdpm.load_service_policy_rules(service_key, self.permit_ION_MANAGER_rule)
pdpm.load_resource_policy_rules(resource_id, self.deny_ION_MANAGER_rule)
response = pdpm.check_agent_request_policies(invocation)
self.assertEqual(response.value, "Deny")
# check that both service and resource policies need to allow a request
pdpm.load_service_policy_rules(service_key, self.permit_ION_MANAGER_rule)
pdpm.load_resource_policy_rules(resource_id, self.permit_ION_MANAGER_rule)
response = pdpm.check_agent_request_policies(invocation)
self.assertEqual(response.value, "Permit")
示例11: test_walk_success
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import side_effect [as 别名]
def test_walk_success(self):
dir1_list = ["dir2", "file"]
empty_list = []
mock_listdir = Mock()
mock_listdir.side_effect = [dir1_list, empty_list]
mock_isdir = Mock()
mock_isdir.side_effect = [True, False]
with nested(patch("gluster.gfapi.Volume.listdir", mock_listdir),
patch("gluster.gfapi.Volume.isdir", mock_isdir)):
for (path, dirs, files) in self.vol.walk("dir1"):
self.assertEqual(dirs, ['dir2'])
self.assertEqual(files, ['file'])
break
示例12: test_fire_timers_raises
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import side_effect [as 别名]
def test_fire_timers_raises(self):
hub = Hub()
eback = Mock()
eback.side_effect = KeyError('foo')
hub.timer = Mock()
hub.scheduler = iter([(0, eback)])
with self.assertRaises(KeyError):
hub.fire_timers(propagate=(KeyError, ))
eback.side_effect = ValueError('foo')
hub.scheduler = iter([(0, eback)])
with patch('kombu.async.hub.logger') as logger:
with self.assertRaises(StopIteration):
hub.fire_timers()
self.assertTrue(logger.error.called)
示例13: test_makedirs_success_EEXIST
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import side_effect [as 别名]
def test_makedirs_success_EEXIST(self):
err = errno.EEXIST
mock_glfs_mkdir = Mock()
mock_glfs_mkdir.side_effect = [OSError(err, os.strerror(err)), 0]
mock_exists = Mock()
mock_exists.side_effect = [False, True, False]
with nested(patch("gluster.gfapi.api.glfs_mkdir", mock_glfs_mkdir),
patch("gluster.gfapi.Volume.exists", mock_exists)):
self.vol.makedirs("./dir1/dir2", 0775)
self.assertEqual(mock_glfs_mkdir.call_count, 2)
mock_glfs_mkdir.assert_any_call(self.vol.fs, "./dir1", 0775)
mock_glfs_mkdir.assert_called_with(self.vol.fs, "./dir1/dir2",
0775)
示例14: test_resource_policies
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import side_effect [as 别名]
def test_resource_policies(self):
gc = Mock()
resource_id = 'resource_key'
pdpm = PolicyDecisionPointManager(gc)
# see that the PDP for resource is empty
self.assertEqual(pdpm.get_resource_pdp(resource_id), pdpm.empty_pdp)
pdpm.load_resource_policy_rules(resource_id, self.permit_ION_MANAGER_rule)
# see that the PDP for resource is not empty anymore
self.assertNotEqual(pdpm.get_resource_pdp(resource_id), pdpm.empty_pdp)
# check request without a resource_id raises NotFound error
self.invocation = Mock()
with self.assertRaises(NotFound) as chk_res:
pdpm.check_resource_request_policies(self.invocation, None)
self.assertIn(chk_res.exception.message, 'The resource_id is not set')
# check that, because actor does not have ION_MANAGER role, policy evaluates to a denial
# (really Not Applicable, because of the inelegant hack of a policy we are setting up our pdp with)
mock_header = Mock()
self.invocation.headers = {'op': 'op', 'process': 'process', 'request': 'request', 'ion-actor-id': 'ion-actor-id', 'receiver': 'resource-registry',
'sender-type': 'sender-type', 'sender-service': 'sender-service', 'ion-actor-roles': {'org_name': ['ion-actor-roles']}}
def get_header_value(key, default):
return self.invocation.headers.get(key, default)
mock_header.side_effect = get_header_value
self.invocation.get_header_value = mock_header
mock_args = Mock()
process = Mock()
process.org_name = 'org_name'
self.invocation.args = {'process': process}
def get_arg_value(key, default):
return self.invocation.args.get(key, default)
mock_args.side_effect = get_arg_value
self.invocation.get_arg_value = mock_args
gc.system_root_org_name = 'sys_org_name'
response = pdpm.check_resource_request_policies(self.invocation, resource_id)
self.assertEqual(response.value, "NotApplicable")
# check that policy evaluates to Permit because actor has ION_MANAGER role
self.invocation.headers = {'op': 'op', 'process': 'process', 'request': 'request', 'ion-actor-id': 'ion-actor-id', 'receiver': 'resource-registry',
'sender-type': 'sender-type', 'sender-service': 'sender-service', 'ion-actor-roles': {'sys_org_name': ['ION_MANAGER']}}
response = pdpm.check_resource_request_policies(self.invocation, resource_id)
self.assertEqual(response.value, "Permit")
示例15: test_main
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import side_effect [as 别名]
def test_main(self):
mock_recon_check = Mock()
mock_recon_check.side_effect = [['a'], ['b'], ['c']]
with patch(self.module + '_recon_check', mock_recon_check):
actual = replication.main()
self.assertIsInstance(actual, list)
self.assertListEqual(['a', 'b', 'c'], actual)
# Tests account_recon_check in isolation
mock_recon_check = Mock()
mock_recon_check.side_effect = [['a']]
with patch(self.module + '_recon_check', mock_recon_check):
with patch(self.module + 'object_recon_check') as rc1:
with patch(self.module + 'container_recon_check') as rc2:
actual = replication.main()
self.assertIsInstance(actual, list)
self.assertListEqual(['a'], actual)
self.assertTrue(rc1.called)
self.assertTrue(rc2.called)
# Tests container_recon_check in isolation
mock_recon_check = Mock()
mock_recon_check.side_effect = [['a']]
with patch(self.module + '_recon_check', mock_recon_check):
with patch(self.module + 'object_recon_check') as rc1:
with patch(self.module + 'account_recon_check') as rc2:
actual = replication.main()
self.assertIsInstance(actual, list)
self.assertListEqual(['a'], actual)
self.assertTrue(rc1.called)
self.assertTrue(rc2.called)
# Tests object_recon_check in isolation
mock_recon_check = Mock()
mock_recon_check.side_effect = [['a']]
with patch(self.module + '_recon_check', mock_recon_check):
with patch(self.module + 'container_recon_check') as rc1:
with patch(self.module + 'account_recon_check') as rc2:
actual = replication.main()
self.assertIsInstance(actual, list)
self.assertListEqual(['a'], actual)
self.assertTrue(rc1.called)
self.assertTrue(rc2.called)