本文整理汇总了Python中mock.MagicMock.return_value方法的典型用法代码示例。如果您正苦于以下问题:Python MagicMock.return_value方法的具体用法?Python MagicMock.return_value怎么用?Python MagicMock.return_value使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mock.MagicMock
的用法示例。
在下文中一共展示了MagicMock.return_value方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_pick_api_with_shortest_wait_for_method_picks_different_api_for_each_method
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import return_value [as 别名]
def test_pick_api_with_shortest_wait_for_method_picks_different_api_for_each_method():
"""
When apis[0] is throttled for METHOD_NAME_1 at now(),
and apis[1] is throttled for METHOD_NAME_2 at now(),
it should pick apis[1] for that METHOD_NAME_1
and pick apis[0] for METHOD_NAME_2.
"""
METHOD_NAME_1 = 'twitter_method_1'
METHOD_NAME_2 = 'twitter_method_2'
api_mock = MagicMock()
api_mock.return_value = api_mock
api_mock2 = MagicMock()
api_mock2.return_value = api_mock2
with patch('tweepy.API', api_mock):
api_pool = tweepy_pool.APIPool([OAUTH_DICT, OAUTH_DICT])
api_pool._apis[0][0] = api_mock
api_pool._apis[0][1][METHOD_NAME_1] = datetime.now()
api_pool._apis[1][0] = api_mock2
api_pool._apis[1][1][METHOD_NAME_2] = datetime.now()
picked_api_for_method_1 = api_pool._pick_api_with_shortest_waiting_time_for_method(METHOD_NAME_1)
picked_api_for_method_2 = api_pool._pick_api_with_shortest_waiting_time_for_method(METHOD_NAME_2)
assert api_mock2 == picked_api_for_method_1[0]
assert api_mock == picked_api_for_method_2[0]
示例2: mock_controller
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import return_value [as 别名]
def mock_controller(self, plugin_label, method, return_value = None,
side_effect = None, mock = None):
"""
Mocks controller by label. Can only be used to test controllers
that get instantiated automatically by cement.
@param plugin_label: e.g. 'drupal'
@param method: e.g. 'enumerate_plugins'
@param return_value: what to return. Default is None, unless the
method starts with enumerate_*, in which case the result is a
tuple as expected by BasePlugin.
@param mock: the MagicMock to place. If None, a blank MagicMock is
created.
@param side_effect: if set to an exception, it will raise an
exception.
"""
if mock:
m = mock
else:
m = MagicMock()
if return_value != None:
m.return_value = return_value
else:
if method.startswith("enumerate_"):
m.return_value = ({"a":[]}, True)
if side_effect:
m.side_effect = side_effect
setattr(self.controller_get(plugin_label), method, m)
return m
示例3: test_with_per_method_throttling_calls_calls_the_right_api_for_each_method
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import return_value [as 别名]
def test_with_per_method_throttling_calls_calls_the_right_api_for_each_method():
"""
When apis[0] is throttled for METHOD_NAME_1 at now(),
and apis[1] is throttled for METHOD_NAME_2 at now(),
it should route METHOD_NAME_1 to apis[1],
and METHOD_NAME_2 to apis[0].
"""
METHOD_NAME_1 = 'followers_ids'
METHOD_NAME_2 = 'user_timeline'
api_mock = MagicMock()
api_mock.return_value = api_mock
ut_mock = Mock(return_value='called user_timeline on api_mock')
api_mock.user_timeline = ut_mock
api_mock2 = MagicMock()
api_mock2.return_value = api_mock2
fids_mock = Mock(return_value='called followers_ids on api_mock2')
api_mock2.followers_ids = fids_mock
with patch('tweepy.API', api_mock):
api_pool = tweepy_pool.APIPool([OAUTH_DICT, OAUTH_DICT])
api_pool._apis[0][0] = api_mock
api_pool._apis[0][1][METHOD_NAME_1] = datetime.now()
api_pool._apis[1][0] = api_mock2
api_pool._apis[1][1][METHOD_NAME_2] = datetime.now()
api_pool._call_with_throttling_per_method(METHOD_NAME_2, id=456)
api_pool._call_with_throttling_per_method(METHOD_NAME_1, id=654)
api_mock.user_timeline.assert_called_with(id=456)
api_mock2.followers_ids.assert_called_with(id=654)
示例4: test_appdynamics_log_query
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import return_value [as 别名]
def test_appdynamics_log_query(monkeypatch, fx_log_hits):
es_url, kwargs, res = fx_log_hits
search = MagicMock()
search.return_value = res
monkeypatch.setattr('zmon_worker_monitor.builtins.plugins.appdynamics.ElasticsearchWrapper.search', search)
timestamp = 1234
timestamp_mock = MagicMock()
timestamp_mock.return_value = timestamp
monkeypatch.setattr(AppdynamicsWrapper, '_AppdynamicsWrapper__get_timestamp', timestamp_mock)
cli = AppdynamicsWrapper(url=URL, es_url=es_url, username=USER, password=PASS, index_prefix='PREFIX_')
exp_q = ('{} AND eventTimestamp:>{}'
.format(kwargs.get('q', ''), timestamp)
.lstrip(' AND '))
result = cli.query_logs(**kwargs)
expected = res['hits']['hits'] if not kwargs.get('raw_result', False) else res
assert result == expected
kwargs.pop('raw_result', None)
kwargs['q'] = exp_q
kwargs['size'] = 100
kwargs['indices'] = ['PREFIX_*']
if 'body' not in kwargs:
kwargs['body'] = None
search.assert_called_with(**kwargs)
示例5: test_appdynamics_healthrule_violations_severity
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import return_value [as 别名]
def test_appdynamics_healthrule_violations_severity(monkeypatch, fx_violations, fx_severity):
kwargs, violations = fx_violations
resp = resp_mock(violations)
get = requests_mock(resp)
monkeypatch.setattr('requests.Session.get', get)
start_time = 12345
end_time = 23456
mktime_mock = MagicMock()
time_mock = MagicMock()
mktime_mock.return_value = start_time
time_mock.return_value = end_time
monkeypatch.setattr('time.mktime', mktime_mock)
monkeypatch.setattr('time.time', time_mock)
cli = AppdynamicsWrapper(URL, username=USER, password=PASS)
res = cli.healthrule_violations(APPLICATION, severity=fx_severity, **kwargs)
assert [v for v in violations if v['severity'] == fx_severity] == res
assert_client(cli)
params = kwargs_to_params(kwargs, start_time, end_time)
get.assert_called_with(cli.healthrule_violations_url(APPLICATION), params=params)
示例6: test_appdynamics_log_count
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import return_value [as 别名]
def test_appdynamics_log_count(monkeypatch, fx_log_count):
es_url, kwargs, res = fx_log_count
count = MagicMock()
count.return_value = res
monkeypatch.setattr('zmon_worker_monitor.builtins.plugins.appdynamics.ElasticsearchWrapper.count', count)
timestamp = 1234
timestamp_mock = MagicMock()
timestamp_mock.return_value = timestamp
monkeypatch.setattr(AppdynamicsWrapper, '_AppdynamicsWrapper__get_timestamp', timestamp_mock)
cli = AppdynamicsWrapper(url=URL, es_url=es_url, username=USER, password=PASS, index_prefix='PREFIX_')
exp_q = ('{} AND eventTimestamp:>{}'
.format(kwargs.get('q', ''), timestamp)
.lstrip(' AND '))
result = cli.count_logs(**kwargs)
assert result == res['count']
kwargs['q'] = exp_q
kwargs['indices'] = ['PREFIX_*']
if 'body' not in kwargs:
kwargs['body'] = None
count.assert_called_with(**kwargs)
示例7: test_logs_subcommand
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import return_value [as 别名]
def test_logs_subcommand():
get_logs_method = MagicMock()
result_value = ""
get_logs_method.return_value = (True, result_value)
spark_controller.get_logs = get_logs_method
command = "logs -s"
name = "sessions_name"
line = " ".join([command, name])
cell = "cell code"
# Could get results
result = magic.spark(line, cell)
get_logs_method.assert_called_once_with(name)
assert result is None
ipython_display.write.assert_called_once_with(result_value)
# Could not get results
get_logs_method.reset_mock()
get_logs_method.return_value = (False, result_value)
result = magic.spark(line, cell)
get_logs_method.assert_called_once_with(name)
assert result is None
ipython_display.send_error.assert_called_once_with(result_value)
示例8: test_getScaledCPU
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import return_value [as 别名]
def test_getScaledCPU( self ):
tl = TimeLeft()
res = tl.getScaledCPU()
self.assertEqual( res, 0 )
tl.scaleFactor = 5.0
tl.normFactor = 5.0
for batch, retValue in [( 'LSF', LSF_ReturnValue )]:
self.tl = importlib.import_module( "DIRAC.Core.Utilities.TimeLeft.TimeLeft" )
rcMock = MagicMock()
rcMock.return_value = S_OK( retValue )
self.tl.runCommand = rcMock
batchSystemName = '%sTimeLeft' % batch
batchPlugin = __import__( 'DIRAC.Core.Utilities.TimeLeft.%s' %
batchSystemName, globals(), locals(), [batchSystemName] )
batchStr = 'batchPlugin.%s()' % ( batchSystemName )
tl.batchPlugin = eval( batchStr )
res = tl.getScaledCPU()
self.assertEqual( res, 0.0 )
for batch, retValue in [( 'SGE', SGE_ReturnValue )]:
self.tl = importlib.import_module( "DIRAC.Core.Utilities.TimeLeft.TimeLeft" )
rcMock = MagicMock()
rcMock.return_value = S_OK( retValue )
self.tl.runCommand = rcMock
batchSystemName = '%sTimeLeft' % batch
batchPlugin = __import__( 'DIRAC.Core.Utilities.TimeLeft.%s' %
batchSystemName, globals(), locals(), [batchSystemName] )
batchStr = 'batchPlugin.%s()' % ( batchSystemName )
tl.batchPlugin = eval( batchStr )
res = tl.getScaledCPU()
self.assertEqual( res, 300.0 )
示例9: test_util_tags_stats_tool_fitered_data
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import return_value [as 别名]
def test_util_tags_stats_tool_fitered_data(
m_path,
m_locales,
m_proj,
m_tag,
trs_mock,
):
# tests all filter functions are called when filtering data
# and that they are called with the result of previous
stats_tool = TagsStatsTool()
m = m_tag, m_proj, m_locales, m_path
# mock trs for translated_resources.all()
_m = MagicMock()
_m.all.return_value = 0
trs_mock.return_value = _m
for i, _m in enumerate(m):
if i >= len(m) - 1:
_m.return_value = 23
else:
_m.return_value = i
# get the filtered_data
result = stats_tool.filtered_data
assert result == 23
for i, _m in enumerate(m):
assert _m.called
if i > 0:
assert _m.call_args[0][0] == i - 1
示例10: test_getattr_with_correct_path
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import return_value [as 别名]
def test_getattr_with_correct_path(self):
mocked_repo = MagicMock()
mocked_first = MagicMock()
mocked_last = MagicMock()
mocked_first.return_value = "tomorrow"
mocked_last.return_value = "tomorrow"
mocked_repo.get_commit_dates.return_value = ['/']
with patch('gitfs.views.history.lru_cache') as mocked_cache:
mocked_cache.__call__ = lambda f: f
history = HistoryView(repo=mocked_repo, uid=1, gid=1,
mount_time="now")
history._get_first_commit_time = mocked_first
history._get_last_commit_time = mocked_last
result = history.getattr("/", 1)
asserted_result = {
'st_uid': 1,
'st_gid': 1,
'st_ctime': "tomorrow",
'st_mtime': "tomorrow",
'st_nlink': 2,
'st_mode': S_IFDIR | 0o555,
}
assert asserted_result == result
示例11: test_check_connection
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import return_value [as 别名]
def test_check_connection(self):
"""
Does it only ping the server if the option was set?
"""
ping = MagicMock()
dut = MagicMock()
configuration_mock = MagicMock()
dut.operating_system = 'linux'
self.tester._dut = dut
self.tester._server = MagicMock()
self.tester._server.TestInterface = 'server'
# check that it doesn't run
self.parser.has_section.return_value = False
#self.tester.configuration.ping = None
outcome = self.tester.connected()
with self.assertRaises(AssertionError):
ping.assert_called_with()
self.assertTrue(outcome)
# check that it does run
self.tester._ping = ping
mock_time = MagicMock()
times = [500,4,3, 2, 1]
# pinged
mock_time.side_effect = lambda: times.pop()
with patch('time.time', mock_time):
ping.return_value = True
outcome = self.tester.connected()
ping.assert_called_with()
times = [700, 600, 500,400 ,300, 40,30, 20, 10]
def time_effects():
output = times.pop()
return output
# timed out
mock_time.side_effect = time_effects
#mock_time_2 = MagicMock()
self.tester._result_location = 'cache'
with patch('time.time', mock_time):
ping.return_value = False
outcome = self.tester.connected()
ping.assert_called_with()
self.assertFalse(outcome)
# timed out
times = [700, 600, 100, 10]
mock_time.side_effect = lambda: times.pop()
# raises exception if asked to
start = 0
attenuation = 0
with self.assertRaises(CameraobscuraError):
with patch('time.time', mock_time):
ping.return_value = False
self.tester.connected(raise_error=start==attenuation)
return
示例12: getObject_Mock
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import return_value [as 别名]
def getObject_Mock(cci_id):
mock = MagicMock()
return_values = get_raw_cci_mocks()
if cci_id in return_values:
mock.return_value = return_values[cci_id]
else:
mock.return_value = {}
return mock
示例13: getObject_Mock
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import return_value [as 别名]
def getObject_Mock(hw_id):
mock = MagicMock()
return_values = get_raw_hardware_mocks()
if hw_id in return_values:
mock.return_value = return_values[hw_id]
else:
mock.return_value = {}
return mock
示例14: test_aws_get_running_elbs
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import return_value [as 别名]
def test_aws_get_running_elbs(monkeypatch):
get_classic = MagicMock()
get_classic.return_value = [1, 2]
get_application = MagicMock()
get_application.return_value = [3, 4]
monkeypatch.setattr('zmon_aws_agent.aws.get_running_elbs_classic', get_classic)
monkeypatch.setattr('zmon_aws_agent.aws.get_running_elbs_application', get_application)
res = aws.get_running_elbs('r1', 'acc1')
assert res == [1, 2, 3, 4]
示例15: test_mkdir
# 需要导入模块: from mock import MagicMock [as 别名]
# 或者: from mock.MagicMock import return_value [as 别名]
def test_mkdir(self):
from gitfs.views import current as current_view
old_mkdir = current_view.PassthroughView.mkdir
old_chmod = current_view.PassthroughView.chmod
mocked_mkdir = lambda self, path, mode: "done"
mocked_chmod = MagicMock()
mocked_chmod.return_value = None
current_view.PassthroughView.mkdir = mocked_mkdir
current_view.PassthroughView.chmod = mocked_chmod
mocked_release = MagicMock()
mocked_full_path = MagicMock()
mocked_repo = MagicMock()
mocked_full_path.return_value = "full_path"
mocked_repo._full_path = mocked_full_path
keep_path = '/path/.keep'
mode = (os.O_WRONLY | os.O_CREAT)
with patch('gitfs.views.current.os') as mocked_os:
mocked_os.path.exists.return_value = False
mocked_os.open.return_value = 10
mocked_os.O_WRONLY = os.O_WRONLY
mocked_os.O_CREAT = os.O_CREAT
current = CurrentView(repo=mocked_repo, uid=1, gid=1,
repo_path="repo_path",
ignore=CachedIgnore())
current.release = mocked_release
assert current.mkdir("/path", "mode") == "done"
mocked_full_path.assert_called_once_with(keep_path)
mocked_os.path.exists.assert_called_once_with(keep_path)
mocked_os.open.assert_called_once_with("full_path", mode)
mocked_chmod.assert_called_once_with(
keep_path,
0o644,
)
assert current.dirty == {
10: {
'message': "Create the /path directory",
'stage': True
}
}
mocked_release.assert_called_once_with(keep_path, 10)
current_view.PassthroughView.mkdir = old_mkdir
current_view.PassthroughView.chmod = old_chmod