本文整理汇总了Python中mock.Mock.return_value方法的典型用法代码示例。如果您正苦于以下问题:Python Mock.return_value方法的具体用法?Python Mock.return_value怎么用?Python Mock.return_value使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mock.Mock
的用法示例。
在下文中一共展示了Mock.return_value方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_request_handler_returns_process_stdout_when_making_response
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import return_value [as 别名]
def test_request_handler_returns_process_stdout_when_making_response(self, lambda_output_parser_mock):
make_response_mock = Mock()
self.service.service_response = make_response_mock
self.service._get_current_route = Mock()
self.service._construct_event = Mock()
parse_output_mock = Mock()
parse_output_mock.return_value = ("status_code", "headers", "body")
self.service._parse_lambda_output = parse_output_mock
lambda_logs = "logs"
lambda_response = "response"
is_customer_error = False
lambda_output_parser_mock.get_lambda_output.return_value = lambda_response, lambda_logs, is_customer_error
service_response_mock = Mock()
service_response_mock.return_value = make_response_mock
self.service.service_response = service_response_mock
result = self.service._request_handler()
self.assertEquals(result, make_response_mock)
lambda_output_parser_mock.get_lambda_output.assert_called_with(ANY)
# Make sure the parse method is called only on the returned response and not on the raw data from stdout
parse_output_mock.assert_called_with(lambda_response, ANY, ANY)
# Make sure the logs are written to stderr
self.stderr.write.assert_called_with(lambda_logs)
示例2: test_login
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import return_value [as 别名]
def test_login(self):
resp = self.client.post(reverse(views.login),
dict(openid='http://me.yahoo.com'))
assert 'login.yahooapis' in resp['location']
with patch('allauth.socialaccount.providers'
'.openid.views._openid_consumer') as consumer_mock:
client = Mock()
complete = Mock()
consumer_mock.return_value = client
client.complete = complete
complete_response = Mock()
complete.return_value = complete_response
complete_response.status = consumer.SUCCESS
complete_response.identity_url = 'http://dummy/john/'
with patch('allauth.socialaccount.providers'
'.openid.utils.SRegResponse') as sr_mock:
with patch('allauth.socialaccount.providers'
'.openid.utils.FetchResponse') as fr_mock:
sreg_mock = Mock()
ax_mock = Mock()
sr_mock.fromSuccessResponse = sreg_mock
fr_mock.fromSuccessResponse = ax_mock
sreg_mock.return_value = {}
ax_mock.return_value = {AXAttribute.PERSON_FIRST_NAME:
['raymond']}
resp = self.client.post(reverse('openid_callback'))
self.assertEqual('http://testserver/accounts/profile/',
resp['location'])
get_user_model().objects.get(first_name='raymond')
示例3: test_rmtree_success
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import return_value [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("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")
mock_rmdir.assert_any_call("dir1/dir2")
mock_unlink.assert_called_once_with("dir1/file")
mock_rmdir.assert_called_with("dir1")
示例4: test_canInstall
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import return_value [as 别名]
def test_canInstall(self, mock_canInstall):
posix = self.get_obj()
entry = lxml.etree.Element("Path", name="test", type="file")
# first, test superclass canInstall failure
mock_canInstall.return_value = False
self.assertFalse(posix.canInstall(entry))
mock_canInstall.assert_called_with(posix, entry)
# next, test fully_specified failure
posix.logger.error.reset_mock()
mock_canInstall.reset_mock()
mock_canInstall.return_value = True
mock_fully_spec = Mock()
mock_fully_spec.return_value = False
posix._handlers[entry.get("type")].fully_specified = \
mock_fully_spec
self.assertFalse(posix.canInstall(entry))
mock_canInstall.assert_called_with(posix, entry)
mock_fully_spec.assert_called_with(entry)
self.assertTrue(posix.logger.error.called)
# finally, test success
posix.logger.error.reset_mock()
mock_canInstall.reset_mock()
mock_fully_spec.reset_mock()
mock_fully_spec.return_value = True
self.assertTrue(posix.canInstall(entry))
mock_canInstall.assert_called_with(posix, entry)
mock_fully_spec.assert_called_with(entry)
self.assertFalse(posix.logger.error.called)
示例5: test_handles
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import return_value [as 别名]
def test_handles(self, mock_get_regex):
match = Mock()
mock_get_regex.return_value = Mock()
mock_get_regex.return_value.match = match
evt = Mock()
evt.filename = "event.txt"
if self.test_obj.__basenames__:
match.return_value = False
self.assertFalse(self.test_obj.handles(evt))
mock_get_regex.assert_called_with([b for b in self.test_obj.__basenames__])
print("match calls: %s" % match.call_args_list)
print("expected: %s" % [call(evt.filename) for b in self.test_obj.__basenames__])
match.assert_called_with(evt.filename)
mock_get_regex.reset_mock()
match.reset_mock()
match.return_value = True
self.assertTrue(self.test_obj.handles(evt))
match.assert_called_with(evt.filename)
else:
match.return_value = False
self.assertFalse(self.test_obj.handles(evt, basename=os.path.basename(self.path)))
mock_get_regex.assert_called_with([os.path.basename(self.path)])
match.assert_called_with(evt.filename)
mock_get_regex.reset_mock()
match.reset_mock()
match.return_value = True
self.assertTrue(self.test_obj.handles(evt, basename=os.path.basename(self.path)))
mock_get_regex.assert_called_with([os.path.basename(self.path)])
match.assert_called_with(evt.filename)
示例6: test_channel_pool_release
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import return_value [as 别名]
def test_channel_pool_release(self):
ncm = Mock()
ncm.return_value = Mock(spec=BidirClientChannel)
ncm.return_value._queue_auto_delete = False
ncm.return_value.get_channel_id.return_value = sentinel.chid
with patch('pyon.net.messaging.NodeB._new_channel', ncm):
ch = self._node.channel(BidirClientChannel)
# return value is not a mock factory - it returns the same mock instance as we declared above
# so redeclare it so they get unique chids
ncm.return_value = Mock(spec=BidirClientChannel)
ncm.return_value._queue_auto_delete = False
ncm.return_value.get_channel_id.return_value = sentinel.chid2
with patch('pyon.net.messaging.NodeB._new_channel', ncm):
ch2 = self._node.channel(BidirClientChannel)
self.assertEquals(ch.get_channel_id(), sentinel.chid)
self.assertEquals(ch2.get_channel_id(), sentinel.chid2)
# return ch to the pool
with patch('pyon.net.messaging.log'):
self._node.on_channel_request_close(ch)
# expect to have bidir pool of two, pool map of 1
self.assertEquals(len(self._node._bidir_pool), 2)
self.assertEquals(len(self._node._pool_map), 1)
# ch2 still active so it should be in the pool map
self.assertIn(sentinel.chid2, self._node._pool_map)
示例7: test_init_sts_external_id
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import return_value [as 别名]
def test_init_sts_external_id(self):
mock_svc1 = Mock(spec_set=_AwsService)
mock_svc2 = Mock(spec_set=_AwsService)
mock_foo = Mock(spec_set=_AwsService)
mock_bar = Mock(spec_set=_AwsService)
mock_ta = Mock(spec_set=TrustedAdvisor)
mock_foo.return_value = mock_svc1
mock_bar.return_value = mock_svc2
svcs = {'SvcFoo': mock_foo, 'SvcBar': mock_bar}
with patch.dict('awslimitchecker.checker._services',
values=svcs, clear=True):
with patch.multiple(
'awslimitchecker.checker',
logger=DEFAULT,
_get_version_info=DEFAULT,
TrustedAdvisor=DEFAULT,
autospec=True,
) as mocks:
mock_version = mocks['_get_version_info']
mock_version.return_value = self.mock_ver_info
mock_ta_constr = mocks['TrustedAdvisor']
mocks['TrustedAdvisor'].return_value = mock_ta
cls = AwsLimitChecker(
account_id='123456789012',
account_role='myrole',
region='myregion',
external_id='myextid',
mfa_serial_number=None,
mfa_token=None
)
# dict should be of _AwsService instances
services = {
'SvcFoo': mock_svc1,
'SvcBar': mock_svc2
}
assert cls.services == services
# _AwsService instances should exist, but have no other calls
assert mock_foo.mock_calls == [
call(80, 99, '123456789012', 'myrole', 'myregion', 'myextid',
None, None)
]
assert mock_bar.mock_calls == [
call(80, 99, '123456789012', 'myrole', 'myregion', 'myextid',
None, None)
]
assert mock_ta_constr.mock_calls == [
call(
services,
account_id='123456789012',
account_role='myrole',
region='myregion',
external_id='myextid',
mfa_serial_number=None,
mfa_token=None,
)
]
assert mock_svc1.mock_calls == []
assert mock_svc2.mock_calls == []
assert self.mock_version.mock_calls == [call()]
assert self.cls.vinfo == self.mock_ver_info
示例8: test_channel_pool_release_reacquire
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import return_value [as 别名]
def test_channel_pool_release_reacquire(self, bcbmock):
ncm = Mock()
ncm.return_value = Mock(spec=BidirClientChannel)
ncm.return_value._queue_auto_delete = False
ncm.return_value.get_channel_id.return_value = sentinel.chid
with patch('pyon.net.messaging.NodeB._new_channel', ncm):
ch = self._node.channel(BidirClientChannel)
# return value is not a mock factory - it returns the same mock instance as we declared above
# so redeclare it so they get unique chids
ncm.return_value = Mock(spec=BidirClientChannel)
ncm.return_value._queue_auto_delete = False
ncm.return_value.get_channel_id.return_value = sentinel.chid2
with patch('pyon.net.messaging.NodeB._new_channel', ncm):
ch2 = self._node.channel(BidirClientChannel)
self.assertEquals(ch.get_channel_id(), sentinel.chid)
self.assertEquals(ch2.get_channel_id(), sentinel.chid2)
# return ch to the pool
with patch('pyon.net.messaging.log'):
self._node.on_channel_request_close(ch)
# reacquire ch
call_count = ncm.call_count
with patch('pyon.net.messaging.NodeB._new_channel', ncm):
ch3 = self._node.channel(BidirClientChannel)
# no new calls to the create method have been made
self.assertEquals(ncm.call_count, call_count)
# we got the first mocked channel back
self.assertEquals(ch3.get_channel_id(), sentinel.chid)
示例9: layer_vars
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import return_value [as 别名]
def layer_vars(self, request, dummy_input_layer, DenseLayer):
input_shape = dummy_input_layer.shape
num_units = 5
num_leading_axes = request.param
W_shape = (np.prod(input_shape[num_leading_axes:]), num_units)
b_shape = (num_units,)
W = Mock()
b = Mock()
nonlinearity = Mock()
W.return_value = np.arange(np.prod(W_shape)).reshape(W_shape)
b.return_value = np.arange(np.prod(b_shape)).reshape(b_shape) * 3
layer = DenseLayer(
dummy_input_layer,
num_units=num_units,
num_leading_axes=num_leading_axes,
W=W,
b=b,
nonlinearity=nonlinearity,
)
return {
'input_shape': input_shape,
'num_units': num_units,
'num_leading_axes': num_leading_axes,
'W_shape': W_shape,
'b_shape': b_shape,
'W': W,
'b': b,
'nonlinearity': nonlinearity,
'layer': layer,
}
示例10: test_actualizar
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import return_value [as 别名]
def test_actualizar(self):
'''
Prueba el metodo actualizar.
'''
# preparo datos
self.actualizador.version_actual = 'a'
self.actualizador.version_disponible = 'b'
mock_descargar = Mock()
mock_descargar.return_value = [
{
'nombre': 'foo',
'descripcion': 'bar'
},
{
'nombre': 'bar',
'descripcion': 'bar'
},
]
self.actualizador.descargar_actualizacion = mock_descargar
mock_aplicar = Mock()
mock_aplicar.return_value = True
self.actualizador.aplicar_actualizacion = mock_aplicar
# llamo metodo a probar
self.actualizador.actualizar()
# verifico que todo este bien
mock_descargar.assert_called_once()
mock_aplicar.assert_called()
assert mock_aplicar.call_count == 2
assert self.actualizador.version_actual == 'b'
示例11: test_validation
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import return_value [as 别名]
def test_validation(self):
mock_get_data = Mock()
mock_get_data.return_value = {}
mock_construct = Mock()
mock_construct.return_value = {}
with patch.multiple(self.client, get_data=mock_get_data,
construct_single_location_data=mock_construct):
with self.assertRaises(TypeError):
self.client.get_districts(12.3456, 10.432)
with self.assertRaises(ValueError):
self.client.get_districts(('a', 10.432))
with self.assertRaises(ValueError):
self.client.get_districts((10.432, 'a'))
try:
self.client.get_districts((12.3456, 10.432))
self.client.get_districts((12.3456, -10.432))
self.client.get_districts((12, 10))
self.client.get_districts((12, -10))
self.client.get_districts(('12.3456', '10.432'))
self.client.get_districts(('12.3456', '-10.432'))
self.client.get_districts(('12', '10'))
self.client.get_districts(('12', '-10'))
except (TypeError, ValueError):
self.fail('get_districts should accept float, int, and strings that '
'can be converted to floats/ints')
示例12: test_get_all_with_clauses
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import return_value [as 别名]
def test_get_all_with_clauses(get_query_clauses):
"""
Test :py:meth:`~.BaseRallyModel.get_all` with clauses passed in.
Test that:
* ``get_all`` calls ``get_query_clauses``
* Uses the result to call ``get_all_results_for_query``
* returns the set of objects as returned by
``convert_from_query_result``
"""
DummyClass = get_inherited_class_object()
get_query_clauses.return_value = "mock_query"
mock_get_all_results_for_query = Mock()
mock_get_all_results_for_query.return_value = "mock_results"
mock_convert_from_query_result = Mock()
mock_convert_from_query_result.return_value = "mock_conversion"
DummyClass.get_all_results_for_query = mock_get_all_results_for_query
DummyClass.convert_from_query_result = mock_convert_from_query_result
response = DummyClass.get_all("clauses")
assert_equal(get_query_clauses.call_args[0][0], "clauses")
assert_equal(mock_get_all_results_for_query.call_args[0][0], "mock_query")
assert_equal(mock_convert_from_query_result.call_args[0][0], "mock_results")
assert_equal(response, "mock_conversion")
示例13: test_get_all_without_clauses
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import return_value [as 别名]
def test_get_all_without_clauses(get_query_clauses):
"""
Test :py:meth:`~.BaseRallyModel.get_all` with no clauses passed in.
Test that:
* ``get_all`` does not call ``get_query_clauses``
* Calls ``get_all_results_for_query`` with a blank query.
* returns the set of objects as returned by
``convert_from_query_result``
"""
DummyClass = get_inherited_class_object()
mock_get_all_results_for_query = Mock()
mock_get_all_results_for_query.return_value = "mock_results"
mock_convert_from_query_result = Mock()
mock_convert_from_query_result.return_value = "mock_conversion"
DummyClass.get_all_results_for_query = mock_get_all_results_for_query
DummyClass.convert_from_query_result = mock_convert_from_query_result
response = DummyClass.get_all()
assert_false(get_query_clauses.called)
assert_equal(mock_get_all_results_for_query.call_args[0][0], "")
assert_equal(mock_convert_from_query_result.call_args[0][0], "mock_results")
assert_equal(response, "mock_conversion")
示例14: setup_interval_thread
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import return_value [as 别名]
def setup_interval_thread(self, **kwargs):
"""
Sets up an interval thread class with mocks of unimplemented methods
to allow testing of the base implementation of those methods that have
concrete implementations.
"""
logger = kwargs.get('logger', self.logger)
config = kwargs.get('config', self.config)
source = kwargs.get('source', self.source)
dest = kwargs.get('dest', self.dest)
terminate_event = kwargs.get('terminate_event', self.terminate_event)
interval = kwargs.get('interval', self.interval)
oneshot = kwargs.get('oneshot', self.oneshot)
interval_thread = IntervalThread(logger, config, source, dest,
terminate_event, interval, oneshot)
mock_get_data_impl = kwargs.get('mock_get_data', None)
if mock_get_data_impl is None:
mock_get_data_impl = Mock()
mock_get_data_impl.return_value = self._get_data_return
mock_send_data_impl = kwargs.get('mock_send_data', None)
if mock_send_data_impl is None:
mock_send_data_impl = Mock()
mock_send_data_impl.return_value = self._send_data_return
interval_thread._get_data = mock_get_data_impl
interval_thread._send_data = mock_send_data_impl
return interval_thread
示例15: test_collect_uses_defaults
# 需要导入模块: from mock import Mock [as 别名]
# 或者: from mock.Mock import return_value [as 别名]
def test_collect_uses_defaults(self, cmdgen):
oids = {
'1.2.3': 'foo.bar',
}
# We should allow assuming default values for community and port
config = {
'devices': {
'mydevice': {
'host': 'localhost',
'oids': oids,
}
}
}
# Setup mocks
auth = Mock()
auth.return_value = auth
transport = Mock()
transport.return_value = transport
collect_snmp = Mock()
with patch.multiple(self.collector,
config=config,
collect_snmp=collect_snmp):
self.collector.collect()
collect_snmp.assert_called_with(
'mydevice', 'localhost', 161, 'public'
)