本文整理汇总了Python中mock.mock.MagicMock.side_effect方法的典型用法代码示例。如果您正苦于以下问题:Python MagicMock.side_effect方法的具体用法?Python MagicMock.side_effect怎么用?Python MagicMock.side_effect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mock.mock.MagicMock
的用法示例。
在下文中一共展示了MagicMock.side_effect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_run
# 需要导入模块: from mock.mock import MagicMock [as 别名]
# 或者: from mock.mock.MagicMock import side_effect [as 别名]
def test_run(self, ActionQueue_mock, installMock, buildMock):
aq = MagicMock()
ActionQueue_mock.return_value = aq
buildMock.return_value = "opener"
registerAndHeartbeat = MagicMock("registerAndHeartbeat")
calls = []
def side_effect():
if len(calls) == 0:
self.controller.repeatRegistration = True
calls.append(1)
registerAndHeartbeat.side_effect = side_effect
self.controller.registerAndHeartbeat = registerAndHeartbeat
# repeat registration
self.controller.run()
self.assertTrue(buildMock.called)
installMock.called_once_with("opener")
self.assertEqual(2, registerAndHeartbeat.call_count)
# one call, +1
registerAndHeartbeat.side_effect = None
self.controller.run()
self.assertEqual(3, registerAndHeartbeat.call_count)
# Action queue should be started during calls
self.assertTrue(ActionQueue_mock.called)
self.assertTrue(aq.start.called)
示例2: test_watchdog_2
# 需要导入模块: from mock.mock import MagicMock [as 别名]
# 或者: from mock.mock.MagicMock import side_effect [as 别名]
def test_watchdog_2(self):
# Test hangs on Windows TODO
if IS_WINDOWS:
return
"""
Tries to catch false positive watchdog invocations
"""
subproc_mock = self.Subprocess_mockup()
executor = PythonExecutor("/tmp", AgentConfig("", ""), self.agentToggleLogger)
_, tmpoutfile = tempfile.mkstemp()
_, tmperrfile = tempfile.mkstemp()
_, tmpstrucout = tempfile.mkstemp()
PYTHON_TIMEOUT_SECONDS = 5
environment_vars = [("PYTHONPATH", "a:b")]
def launch_python_subprocess_method(command, tmpout, tmperr, environment_vars):
subproc_mock.tmpout = tmpout
subproc_mock.tmperr = tmperr
return subproc_mock
executor.launch_python_subprocess = launch_python_subprocess_method
runShellKillPgrp_method = MagicMock()
runShellKillPgrp_method.side_effect = lambda python : python.terminate()
executor.runShellKillPgrp = runShellKillPgrp_method
subproc_mock.returncode = 0
thread = Thread(target = executor.run_file, args = ("fake_puppetFile", ["arg1", "arg2"],
tmpoutfile, tmperrfile,
PYTHON_TIMEOUT_SECONDS, tmpstrucout, "INFO"))
thread.start()
time.sleep(0.1)
subproc_mock.should_finish_event.set()
subproc_mock.finished_event.wait()
self.assertEquals(subproc_mock.was_terminated, False, "Subprocess should not be terminated before timeout")
self.assertEquals(subproc_mock.returncode, 0, "Subprocess should not be terminated before timeout")
示例3: test_execution_results
# 需要导入模块: from mock.mock import MagicMock [as 别名]
# 或者: from mock.mock.MagicMock import side_effect [as 别名]
def test_execution_results(self):
subproc_mock = self.Subprocess_mockup()
executor = PythonExecutor("/tmp", AmbariConfig().getConfig())
_, tmpoutfile = tempfile.mkstemp()
_, tmperrfile = tempfile.mkstemp()
_, tmpstroutfile = tempfile.mkstemp()
PYTHON_TIMEOUT_SECONDS = 5
def launch_python_subprocess_method(command, tmpout, tmperr):
subproc_mock.tmpout = tmpout
subproc_mock.tmperr = tmperr
return subproc_mock
executor.launch_python_subprocess = launch_python_subprocess_method
runShellKillPgrp_method = MagicMock()
runShellKillPgrp_method.side_effect = lambda python : python.terminate()
executor.runShellKillPgrp = runShellKillPgrp_method
subproc_mock.returncode = 0
subproc_mock.should_finish_event.set()
callback_method = MagicMock()
result = executor.run_file("file", ["arg1", "arg2"], "/fake_tmp_dir",
tmpoutfile, tmperrfile, PYTHON_TIMEOUT_SECONDS,
tmpstroutfile, "INFO", callback_method, "1-1")
self.assertEquals(result, {'exitcode': 0, 'stderr': 'Dummy err', 'stdout': 'Dummy output',
'structuredOut': {}})
self.assertTrue(callback_method.called)
示例4: test_repeatRegistration
# 需要导入模块: from mock.mock import MagicMock [as 别名]
# 或者: from mock.mock.MagicMock import side_effect [as 别名]
def test_repeatRegistration(self,
start_mock, installMock, buildMock):
registerAndHeartbeat = MagicMock(name="registerAndHeartbeat")
self.controller.registerAndHeartbeat = registerAndHeartbeat
self.controller.run()
self.assertTrue(installMock.called)
self.assertTrue(buildMock.called)
self.assertTrue(start_mock.called)
self.controller.registerAndHeartbeat.assert_called_once_with()
calls = []
def switchBool():
if len(calls) == 0:
self.controller.repeatRegistration = True
calls.append(1)
self.controller.repeatRegistration = False
registerAndHeartbeat.side_effect = switchBool
self.controller.run()
self.assertEqual(2, registerAndHeartbeat.call_count)
self.controller.registerAndHeartbeat = \
Controller.Controller.registerAndHeartbeat
示例5: test_watchdog_1
# 需要导入模块: from mock.mock import MagicMock [as 别名]
# 或者: from mock.mock.MagicMock import side_effect [as 别名]
def test_watchdog_1(self, kill_process_with_children_mock):
"""
Tests whether watchdog works
"""
subproc_mock = self.Subprocess_mockup()
executor = PythonExecutor("/tmp", AmbariConfig().getConfig())
_, tmpoutfile = tempfile.mkstemp()
_, tmperrfile = tempfile.mkstemp()
_, tmpstrucout = tempfile.mkstemp()
PYTHON_TIMEOUT_SECONDS = 0.1
kill_process_with_children_mock.side_effect = lambda pid : subproc_mock.terminate()
def launch_python_subprocess_method(command, tmpout, tmperr):
subproc_mock.tmpout = tmpout
subproc_mock.tmperr = tmperr
return subproc_mock
executor.launch_python_subprocess = launch_python_subprocess_method
runShellKillPgrp_method = MagicMock()
runShellKillPgrp_method.side_effect = lambda python : python.terminate()
executor.runShellKillPgrp = runShellKillPgrp_method
subproc_mock.returncode = None
callback_method = MagicMock()
thread = Thread(target = executor.run_file, args = ("fake_puppetFile",
["arg1", "arg2"], tmpoutfile, tmperrfile,
PYTHON_TIMEOUT_SECONDS, tmpstrucout, callback_method, '1'))
thread.start()
time.sleep(0.1)
subproc_mock.finished_event.wait()
self.assertEquals(subproc_mock.was_terminated, True, "Subprocess should be terminated due to timeout")
self.assertTrue(callback_method.called)
示例6: test_watchdog_2
# 需要导入模块: from mock.mock import MagicMock [as 别名]
# 或者: from mock.mock.MagicMock import side_effect [as 别名]
def test_watchdog_2(self):
"""
Tries to catch false positive watchdog invocations
"""
subproc_mock = self.Subprocess_mockup()
executor = PythonExecutor("/tmp", AmbariConfig().getConfig())
_, tmpoutfile = tempfile.mkstemp()
_, tmperrfile = tempfile.mkstemp()
_, tmpstrucout = tempfile.mkstemp()
PYTHON_TIMEOUT_SECONDS = 5
def launch_python_subprocess_method(command, tmpout, tmperr):
subproc_mock.tmpout = tmpout
subproc_mock.tmperr = tmperr
return subproc_mock
executor.launch_python_subprocess = launch_python_subprocess_method
runShellKillPgrp_method = MagicMock()
runShellKillPgrp_method.side_effect = lambda python : python.terminate()
executor.runShellKillPgrp = runShellKillPgrp_method
subproc_mock.returncode = 0
callback_method = MagicMock()
thread = Thread(target = executor.run_file, args = ("fake_puppetFile", ["arg1", "arg2"],
tmpoutfile, tmperrfile,
PYTHON_TIMEOUT_SECONDS, tmpstrucout,
callback_method, "1-1"))
thread.start()
time.sleep(0.1)
subproc_mock.should_finish_event.set()
subproc_mock.finished_event.wait()
self.assertEquals(subproc_mock.was_terminated, False, "Subprocess should not be terminated before timeout")
self.assertEquals(subproc_mock.returncode, 0, "Subprocess should not be terminated before timeout")
self.assertTrue(callback_method.called)
示例7: test_execution_results
# 需要导入模块: from mock.mock import MagicMock [as 别名]
# 或者: from mock.mock.MagicMock import side_effect [as 别名]
def test_execution_results(self):
self.assertEqual.__self__.maxDiff = None
subproc_mock = self.Subprocess_mockup()
executor = PythonExecutor("/tmp", AgentConfig("", ""), self.agentToggleLogger)
_, tmpoutfile = tempfile.mkstemp()
_, tmperrfile = tempfile.mkstemp()
_, tmpstroutfile = tempfile.mkstemp()
if IS_WINDOWS:
if os.path.exists(tmpstroutfile):
tmpstroutfile = tmpstroutfile + "_t"
PYTHON_TIMEOUT_SECONDS = 5
def launch_python_subprocess_method(command, tmpout, tmperr, environment_vars):
subproc_mock.tmpout = tmpout
subproc_mock.tmperr = tmperr
return subproc_mock
executor.launch_python_subprocess = launch_python_subprocess_method
runShellKillPgrp_method = MagicMock()
runShellKillPgrp_method.side_effect = lambda python : python.terminate()
executor.runShellKillPgrp = runShellKillPgrp_method
subproc_mock.returncode = 0
subproc_mock.should_finish_event.set()
result = executor.run_file("file", ["arg1", "arg2"], tmpoutfile, tmperrfile, PYTHON_TIMEOUT_SECONDS, tmpstroutfile, "INFO", True, None)
self.assertEquals(result, {'exitcode': 0, 'stderr': 'Dummy err', 'stdout': 'Dummy output',
'structuredOut': {}})
示例8: test_repeatRegistration
# 需要导入模块: from mock.mock import MagicMock [as 别名]
# 或者: from mock.mock.MagicMock import side_effect [as 别名]
def test_repeatRegistration(self, get_os_version_mock, get_os_type_mock,
run_mock, installMock, buildMock, Popen_mock):
registerAndHeartbeat = MagicMock(name="registerAndHeartbeat")
get_os_type_mock.return_value = "suse"
get_os_version_mock.return_value = "11"
self.controller.registerAndHeartbeat = registerAndHeartbeat
self.controller.run()
self.assertTrue(installMock.called)
self.assertTrue(buildMock.called)
self.controller.registerAndHeartbeat.assert_called_once_with()
calls = []
def switchBool():
if len(calls) == 0:
self.controller.repeatRegistration = True
calls.append(1)
self.controller.repeatRegistration = False
registerAndHeartbeat.side_effect = switchBool
self.controller.run()
self.assertEqual(2, registerAndHeartbeat.call_count)
self.controller.registerAndHeartbeat = \
Controller.Controller.registerAndHeartbeat
示例9: test_watchdog_1
# 需要导入模块: from mock.mock import MagicMock [as 别名]
# 或者: from mock.mock.MagicMock import side_effect [as 别名]
def test_watchdog_1(self, kill_process_with_children_mock):
# Test hangs on Windows TODO
if IS_WINDOWS:
return
"""
Tests whether watchdog works
"""
subproc_mock = self.Subprocess_mockup()
executor = PythonExecutor("/tmp", AgentConfig("", ""), self.agentToggleLogger)
_, tmpoutfile = tempfile.mkstemp()
_, tmperrfile = tempfile.mkstemp()
_, tmpstrucout = tempfile.mkstemp()
PYTHON_TIMEOUT_SECONDS = 0.1
kill_process_with_children_mock.side_effect = lambda pid : subproc_mock.terminate()
def launch_python_subprocess_method(command, tmpout, tmperr, environment_vars):
subproc_mock.tmpout = tmpout
subproc_mock.tmperr = tmperr
return subproc_mock
executor.launch_python_subprocess = launch_python_subprocess_method
runShellKillPgrp_method = MagicMock()
runShellKillPgrp_method.side_effect = lambda python : python.terminate()
executor.runShellKillPgrp = runShellKillPgrp_method
subproc_mock.returncode = None
thread = Thread(target = executor.run_file, args = ("fake_puppetFile",
["arg1", "arg2"], tmpoutfile, tmperrfile, PYTHON_TIMEOUT_SECONDS, tmpstrucout,"INFO"))
thread.start()
time.sleep(0.1)
subproc_mock.finished_event.wait()
self.assertEquals(subproc_mock.was_terminated, True, "Subprocess should be terminated due to timeout")
示例10: test_execution_results
# 需要导入模块: from mock.mock import MagicMock [as 别名]
# 或者: from mock.mock.MagicMock import side_effect [as 别名]
def test_execution_results(self):
subproc_mock = self.Subprocess_mockup()
executor = PythonExecutor("/tmp", AmbariConfig().getConfig())
_, tmpoutfile = tempfile.mkstemp()
_, tmperrfile = tempfile.mkstemp()
tmp_file = tempfile.NamedTemporaryFile() # the structured out file should be preserved across calls to the hooks and script.
tmpstructuredoutfile = tmp_file.name
tmp_file.close()
PYTHON_TIMEOUT_SECONDS = 5
def launch_python_subprocess_method(command, tmpout, tmperr):
subproc_mock.tmpout = tmpout
subproc_mock.tmperr = tmperr
return subproc_mock
executor.launch_python_subprocess = launch_python_subprocess_method
runShellKillPgrp_method = MagicMock()
runShellKillPgrp_method.side_effect = lambda python : python.terminate()
executor.runShellKillPgrp = runShellKillPgrp_method
subproc_mock.returncode = 0
subproc_mock.should_finish_event.set()
callback_method = MagicMock()
result = executor.run_file("file", ["arg1", "arg2"],
tmpoutfile, tmperrfile, PYTHON_TIMEOUT_SECONDS,
tmpstructuredoutfile, callback_method, "1-1")
self.assertEquals(result, {'exitcode': 0, 'stderr': '', 'stdout': '',
'structuredOut': {}})
self.assertTrue(callback_method.called)
示例11: test_recoveryHbCmd
# 需要导入模块: from mock.mock import MagicMock [as 别名]
# 或者: from mock.mock.MagicMock import side_effect [as 别名]
def test_recoveryHbCmd(self, dumpsMock, sleepMock, event_mock, exit_mock):
out = StringIO.StringIO()
sys.stdout = out
hearbeat = MagicMock()
self.controller.heartbeat = hearbeat
event_mock.return_value = False
dumpsMock.return_value = "data"
sendRequest = MagicMock(name="sendRequest")
self.controller.sendRequest = sendRequest
addToQueue = MagicMock(name="addToQueue")
addToStatusQueue = MagicMock(name="addToStatusQueue")
self.addToQueue = addToQueue
self.addToStatusQueue = addToStatusQueue
process_execution_commands = MagicMock(name="process_execution_commands")
self.controller.recovery_manager.process_execution_commands = process_execution_commands
process_status_commands = MagicMock(name="process_status_commands")
self.controller.recovery_manager.process_status_commands = process_status_commands
set_paused = MagicMock(name = "set_paused")
self.controller.recovery_manager.set_paused = set_paused
self.controller.responseId = 0
response = {"responseId":1,
"statusCommands": "commands2",
"executionCommands" : "commands1",
"log":"",
"exitstatus":"0",
"hasPendingTasks": True}
sendRequest.return_value = response
def one_heartbeat(*args, **kwargs):
self.controller.DEBUG_STOP_HEARTBEATING = True
return response
sendRequest.side_effect = one_heartbeat
actionQueue = MagicMock()
actionQueue.isIdle.return_value = True
# one successful request, after stop
self.controller.actionQueue = actionQueue
self.controller.heartbeatWithServer()
self.assertTrue(sendRequest.called)
self.assertTrue(process_execution_commands.called)
self.assertFalse(process_status_commands.called)
process_execution_commands.assert_called_with("commands1")
set_paused.assert_called_with(True)
self.controller.heartbeatWithServer()
sys.stdout = sys.__stdout__
self.controller.sendRequest = Controller.Controller.sendRequest
self.controller.sendRequest = Controller.Controller.addToQueue
self.controller.sendRequest = Controller.Controller.addToStatusQueue
pass
示例12: run_simulation
# 需要导入模块: from mock.mock import MagicMock [as 别名]
# 或者: from mock.mock.MagicMock import side_effect [as 别名]
def run_simulation():
Controller.logger = MagicMock()
sendRequest_method = MagicMock()
tmpfile = tempfile.gettempdir()
config = AmbariConfig().getConfig()
config.set('agent', 'prefix', tmpfile)
scriptsDir = os.path.join(os.getcwd(), os.pardir,os.pardir,
os.pardir, 'main', 'upgrade_stack')
config.set('stack', 'upgradeScriptsDir', scriptsDir)
ver_file = os.path.join(tmpfile, "version")
with open(ver_file, "w") as text_file:
text_file.write(agent_version)
controller = Controller.Controller(config)
controller.sendRequest = sendRequest_method
controller.netutil.HEARTBEAT_IDDLE_INTERVAL_SEC = 0.1
controller.netutil.HEARTBEAT_NOT_IDDLE_INTERVAL_SEC = 0.1
controller.range = 1
for responce in responces:
queue.put(responce)
def send_stub(url, data):
logger.info("Controller sends data to %s :" % url)
logger.info(pprint.pformat(data))
if not queue.empty():
responce = queue.get()
else:
responce = responces[-1]
logger.info("There is no predefined responce available, sleeping for 30 sec")
time.sleep(30)
responce = json.loads(responce)
responseId.inc()
responce["responseId"] = responseId.val()
responce = json.dumps(responce)
logger.info("Returning data to Controller:" + responce)
return responce
sendRequest_method.side_effect = send_stub
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s %(filename)s:%(lineno)d - \
%(message)s")
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
logger.info("Starting")
controller.start()
controller.actionQueue.IDLE_SLEEP_TIME = 0.1
controller.run()
示例13: test_try_to_connect
# 需要导入模块: from mock.mock import MagicMock [as 别名]
# 或者: from mock.mock.MagicMock import side_effect [as 别名]
def test_try_to_connect(self, sleepMock):
netutil = NetUtil.NetUtil()
checkURL = MagicMock(name="checkURL")
checkURL.return_value = True
netutil.checkURL = checkURL
l = MagicMock()
# one successful get
self.assertEqual(0, netutil.try_to_connect("url", 10))
# got successful after N retries
gets = [True, False, False]
def side_effect(*args):
return gets.pop()
checkURL.side_effect = side_effect
self.assertEqual(2, netutil.try_to_connect("url", 10))
# max retries
checkURL.side_effect = None
checkURL.return_value = False
self.assertEqual(5, netutil.try_to_connect("url", 5))
示例14: test_try_to_connect
# 需要导入模块: from mock.mock import MagicMock [as 别名]
# 或者: from mock.mock.MagicMock import side_effect [as 别名]
def test_try_to_connect(self, event_mock,
sleepMock):
event_mock.return_value = False
netutil = NetUtil.NetUtil(MagicMock())
checkURL = MagicMock(name="checkURL")
checkURL.return_value = True, "test"
netutil.checkURL = checkURL
# one successful get
self.assertEqual((0, True, False), netutil.try_to_connect("url", 10))
# got successful after N retries
gets = [[True, ""], [False, ""], [False, ""]]
def side_effect(*args):
return gets.pop()
checkURL.side_effect = side_effect
self.assertEqual((2, True, False), netutil.try_to_connect("url", 10))
# max retries
checkURL.side_effect = None
checkURL.return_value = False, "test"
self.assertEqual((5, False, False), netutil.try_to_connect("url", 5))
示例15: test_execution_results
# 需要导入模块: from mock.mock import MagicMock [as 别名]
# 或者: from mock.mock.MagicMock import side_effect [as 别名]
def test_execution_results(self):
subproc_mock = self.Subprocess_mockup()
executor = PythonExecutor("/tmp", AgentConfig("", ""))
_, tmpoutfile = tempfile.mkstemp()
_, tmperrfile = tempfile.mkstemp()
_, tmpstroutfile = tempfile.mkstemp()
PYTHON_TIMEOUT_SECONDS = 5
def launch_python_subprocess_method(command, tmpout, tmperr, environment_vars):
subproc_mock.tmpout = tmpout
subproc_mock.tmperr = tmperr
return subproc_mock
executor.launch_python_subprocess = launch_python_subprocess_method
runShellKillPgrp_method = MagicMock()
runShellKillPgrp_method.side_effect = lambda python : python.terminate()
executor.runShellKillPgrp = runShellKillPgrp_method
subproc_mock.returncode = 0
subproc_mock.should_finish_event.set()
result = executor.run_file("file", ["arg1", "arg2"], tmpoutfile, tmperrfile, PYTHON_TIMEOUT_SECONDS, tmpstroutfile)
self.assertEquals(result, {'exitcode': 0, 'stderr': 'Dummy err', 'stdout': 'Dummy output',
'structuredOut': {'msg': 'Unable to read structured output from ' + tmpstroutfile}})