def setup_mocks(mocker): mocker.patch('mount_efs.start_watchdog') mocker.patch('mount_efs.get_tls_port_range', return_value=(DEFAULT_TLS_PORT, DEFAULT_TLS_PORT + 10)) mocker.patch('socket.socket', return_value=MagicMock()) mocker.patch('mount_efs.get_dns_name_and_fallback_mount_target_ip_address', return_value=(DNS_NAME, None)) mocker.patch('mount_efs.get_target_region', return_value=REGION) mocker.patch('mount_efs.write_tls_tunnel_state_file', return_value='~mocktempfile') mocker.patch('mount_efs.create_certificate') mocker.patch('os.rename') mocker.patch('os.kill') process_mock = MagicMock() process_mock.communicate.return_value = ( 'stdout', 'stderr', ) process_mock.returncode = 0 popen_mock = mocker.patch('subprocess.Popen', return_value=process_mock) write_config_mock = mocker.patch('mount_efs.write_stunnel_config_file', return_value=EXPECTED_STUNNEL_CONFIG_FILE) return popen_mock, write_config_mock
def test_install(self): process = MagicMock() process.communicate.return_value = ('', '') process.returncode = 0 self.popen.return_value = process self.ubuntu.install(self.params) self.popen.assert_has_calls([ call( ['service', 'codedeploy-agent', 'stop'], stdout=subprocess.PIPE, stderr=subprocess.PIPE ), call().communicate() ]) self.check_call.assert_has_calls([ call(['apt-get', '-y', 'update']), call(['apt-get', '-y', 'install', 'ruby2.0']), call(['chmod', '+x', './{0}'.format(self.installer)]), call( ['./{0}'.format(self.installer), 'auto'], env=self.environment ) ]) self.open.assert_called_with(self.installer, 'wb') self.open().write.assert_called_with(self.body)
def test_uninstall(self): process = MagicMock() process.communicate.side_effect = [('', ''), ('', '')] process.returncode = 0 self.popen.return_value = process self.windows.uninstall(self.params) self.popen.assert_has_calls([ call( [ 'powershell.exe', '-Command', 'Stop-Service', '-Name', 'codedeployagent' ], stdout=subprocess.PIPE, stderr=subprocess.PIPE ), call().communicate(), call( [ 'wmic', 'product', 'where', 'name="CodeDeploy Host Agent"', 'call', 'uninstall', '/nointeractive' ], stdout=subprocess.PIPE, stderr=subprocess.PIPE ), call().communicate() ])
def test_call_ipam_plugin_binary_mainline(self, m_popen): # Mock _find_ipam_plugin. plugin_path = "/opt/bin/cni/calico-ipam" self.plugin._find_ipam_plugin = MagicMock(spec=self.plugin._find_ipam_plugin) self.plugin._find_ipam_plugin.return_value = plugin_path # Mock out return values. ip4 = "10.0.0.1/32" ip6 = "0:0:0:0:0:ffff:a00:1" stdout = json.dumps({"ip4": {"ip": ip4}, "ip6": {"ip": ip6}}) stderr = "" m_proc = MagicMock(spec=Popen) m_proc.communicate.return_value = (stdout, stderr) m_proc.returncode = 0 m_popen.return_value = m_proc env = {} # Set IPAM type. self.plugin.ipam_type = "not-calico" # Call _call_ipam_plugin. rc, result = self.plugin._call_ipam_plugin(env) # Assert. assert_equal(rc, 0) m_popen.assert_called_once_with(plugin_path, stdin=PIPE, stdout=PIPE, stderr=PIPE, env=env) m_proc.communicate.assert_called_once_with(json.dumps(self.plugin.network_config)) assert_equal(result, stdout)
def test_call_ipam_plugin_binary_mainline(self, m_popen): # Mock _find_ipam_plugin. plugin_path = "/opt/bin/cni/calico-ipam" self.plugin._find_ipam_plugin = MagicMock( spec=self.plugin._find_ipam_plugin) self.plugin._find_ipam_plugin.return_value = plugin_path # Mock out return values. ip4 = "10.0.0.1/32" ip6 = "0:0:0:0:0:ffff:a00:1" stdout = json.dumps({"ip4": {"ip": ip4}, "ip6": {"ip": ip6}}) stderr = "" m_proc = MagicMock(spec=Popen) m_proc.communicate.return_value = (stdout, stderr) m_proc.returncode = 0 m_popen.return_value = m_proc env = {} # Set IPAM type. self.plugin.ipam_type = "not-calico" # Call _call_ipam_plugin. rc, result = self.plugin._call_ipam_plugin(env) # Assert. assert_equal(rc, 0) m_popen.assert_called_once_with(plugin_path, stdin=PIPE, stdout=PIPE, stderr=PIPE, env=env) m_proc.communicate.assert_called_once_with( json.dumps(self.plugin.network_config)) assert_equal(result, stdout)
def get_proc(self, return_value=0, stdout='', stderr=''): """Return a proc object to attach to the output of Popen """ proc = MagicMock() proc.communicate.return_value = self.get_communicate(stdout, stderr) proc.returncode = return_value return proc
def test_install(self): process = MagicMock() process.communicate.side_effect = [('', ''), ('Running', '')] process.returncode = 0 self.popen.return_value = process self.windows.install(self.params) self.popen.assert_has_calls([ call([ 'powershell.exe', '-Command', 'Stop-Service', '-Name', 'codedeployagent' ], stdout=subprocess.PIPE, stderr=subprocess.PIPE), call().communicate(), call([ 'powershell.exe', '-Command', 'Get-Service', '-Name', 'codedeployagent' ], stdout=subprocess.PIPE, stderr=subprocess.PIPE), call().communicate() ]) self.check_call.assert_has_calls([ call([ r'.\{0}'.format(self.installer), '/quiet', '/l', r'.\codedeploy-agent-install-log.txt' ], shell=True), call([ 'powershell.exe', '-Command', 'Restart-Service', '-Name', 'codedeployagent' ]) ]) self.open.assert_called_with(self.installer, 'wb') self.open().write.assert_called_with(self.body)
def test_run_xml_workflow_kinit(self, m_Popen): """test rm dry workflow""" proc = MagicMock() proc.returncode = 10 proc.communicate = MagicMock() proc.communicate.return_value = ('test_output', '') m_Popen.return_value = proc self.assertFalse(self.utilities_run.run_xml_workflow('sample_wf'))
def Popen(command, env=None, *args, **kwargs): process = MagicMock() process.stdout = StringIO(command) process.returncode = 0 self.assertEqual(environment, env) return process
def test_rm_dry_workflow(self, m_Popen): """test rm dry workflow""" proc = MagicMock() proc.returncode = 0 proc.communicate = MagicMock() proc.communicate.return_value = ('test_output', '') m_Popen.return_value = proc self.assertEquals(self.utilities.rm_dry_workflow('sample_wf'), None)
def test_main_kafka_dies(self, mock_kafka_start, mock_kazoo): mock_popen = MagicMock(spec=Popen) mock_kafka_start.return_value = mock_popen mock_popen.returncode = -1 main_return = main() self.assertEqual(-1, main_return) mock_kazoo.assert_not_called()
def _mock_popen(mocker, returncode=0): popen_mock = MagicMock() popen_mock.communicate.return_value = ( 'stdout', 'stderr', ) popen_mock.returncode = returncode return mocker.patch('subprocess.Popen', return_value=popen_mock)
def fake_subprocess(stdout, stderr, returncode): proc = MagicMock() proc.returncode = returncode proc.communicate.return_value = (stdout, stderr) sub = MagicMock() sub.popen.return_value = proc return (sub, proc)
def _mock_popen(mocker, returncode=0, stdout="stdout", stderr="stderr"): popen_mock = MagicMock() popen_mock.communicate.return_value = ( stdout, stderr, ) popen_mock.returncode = returncode return mocker.patch("subprocess.Popen", return_value=popen_mock)
def test_get_nfs_mount_options_on_macos(mocker): mount_point = "/mnt" process_mock = MagicMock() process_mock.stdout = str(json.dumps(NFSSTAT_DEFAULT_OUTPUT)) process_mock.returncode = 0 mocker.patch("subprocess.run", return_value=process_mock) nfs_options = watchdog.get_nfs_mount_options_on_macos(mount_point) assert "port=12345" in nfs_options
def test_run_workflow(self, m_Popen, m_run_subprocess): """test run workflow""" m_run_subprocess.return_value = 0 proc = MagicMock() proc.returncode = 0 proc.communicate = MagicMock() proc.communicate.return_value = ('test_output', '') m_Popen.return_value = proc self.assertTrue(self.utilities.run_workflow('sample_workflow'))
def test_dryrun_workflow(self, m_Popen, m_gen_dryrun_workflow): """test dryrun workflow""" m_gen_dryrun_workflow.return_value = (True, 'sample_wf_dryrun') proc = MagicMock() proc.returncode = 0 proc.communicate = MagicMock() proc.communicate.return_value = ('test_output', '') m_Popen.return_value = proc self.assertTrue(self.utilities.dryrun_workflow('sample_wf'))
def test_main_static(self, mock_conn_string, mock_kafka_start, mock_kazoo): mock_conn_string.return_value = [] mock_popen = MagicMock(spec=Popen) mock_kafka_start.return_value = mock_popen mock_popen.returncode = None main_return = main(loops=1, loop_interval=0.001) self.assertEqual(0, main_return) mock_kazoo.assert_not_called()
def _mock_popen(mocker, returncode=0): popen_mock = MagicMock() popen_mock.communicate.return_value = ( "stdout", "stderr", ) popen_mock.pid = PID popen_mock.returncode = returncode return mocker.patch("subprocess.Popen", return_value=popen_mock)
def test_upstart_system(mocker): process_mock = MagicMock() process_mock.communicate.return_value = ('stop', '', ) process_mock.returncode = 0 popen_mock = mocker.patch('subprocess.Popen', return_value=process_mock) mount_efs.start_watchdog('init') assert 2 == popen_mock.call_count assert '/sbin/start' in popen_mock.call_args[0][0]
def subprocess_run_mock(cmd=None, shell=None, stdout=None, stderr=None, env=None, returncode=0): result = MagicMock() result.returncode = returncode result.stdout = MagicMock() result.stderr = MagicMock() return result
def test_supervisor_system_watchdog_status(mocker): process_mock = MagicMock() process_mock.communicate.return_value = ('RUNNING', '', ) process_mock.returncode = 0 popen_mock = mocker.patch('subprocess.Popen', return_value=process_mock) mount_efs.start_watchdog('supervisord') utils.assert_called_once(popen_mock) assert 'supervisorctl' in popen_mock.call_args[0][0] assert 'status' in popen_mock.call_args[0][0]
def test_run_cmd_list(self, m_Popen): m_pd = MagicMock() m_pd.returncode = 0 stdout = b"stdout" stderr = b"stderr" m_pd.communicate.return_value = stdout, stderr m_Popen.return_value = m_pd a = module.Antivirus() res = a.run_cmd(["ls", "-la", "/tmp"]) m_Popen.assert_called_once_with(['ls', '-la', '/tmp'], stderr=module.PIPE, stdout=module.PIPE) self.assertEquals(res, (0, "stdout", "stderr"))
def test_run_cmd_str(self, m_Popen): m_pd = MagicMock() m_pd.returncode = 0 stdout = b"stdout" stderr = b"stderr" m_pd.communicate.return_value = stdout, stderr m_Popen.return_value = m_pd a = module.Antivirus() res = a.run_cmd("/usr/bin/ls") m_Popen.assert_called_once_with(['/usr/bin/ls'], stderr=module.PIPE, stdout=module.PIPE) self.assertEquals(res, (0, "stdout", "stderr"))
def test_upstart_system(mocker): process_mock = MagicMock() process_mock.communicate.return_value = ( "stop", "", ) process_mock.returncode = 0 popen_mock = mocker.patch("subprocess.Popen", return_value=process_mock) mount_efs.start_watchdog("init") assert 2 == popen_mock.call_count assert "/sbin/start" in popen_mock.call_args[0][0]
def test_uninstall(self): process = MagicMock() process.communicate.return_value = ('', '') process.returncode = 0 self.popen.return_value = process self.ubuntu.uninstall(self.params) self.popen.assert_has_calls([ call(['service', 'codedeploy-agent', 'stop'], stdout=subprocess.PIPE, stderr=subprocess.PIPE), call().communicate() ]) self.check_call.assert_has_calls( [call(['dpkg', '-r', 'codedeploy-agent'])])
def update_job_test(self, mock_popen, mock_gjax): mock_popen_instance = MagicMock() mock_popen.return_value = mock_popen_instance mock_popen_instance.returncode = 0 mock_popen_instance.communicate = MagicMock() mock_gjax.return_value = "job as xml" self.jenkins.update_job(self.job) assert mock_popen.called command = mock_popen.call_args[0][0] assert sorted(command) == sorted(self.jenkins.cli + [platform_ci.jenkins.PlatformJenkinsJavaCLI.UPDATE_JOB, self.job.name]) assert mock_gjax.called assert mock_popen_instance.communicate.called communicate = mock_popen_instance.communicate.call_args[1] assert communicate == {"input": mock_gjax.return_value} mock_popen_instance.returncode = 1 assert_raises(platform_ci.jenkins.PlatformJenkinsException, self.jenkins.update_job, self.job)
def test_prune_obsolete_builds_handle_script_error(self, test_pruner, mc_popen): mc_handle = MagicMock() mc_popen.return_value = mc_handle mc_handle.returncode = 1 mc_handle.communicate.return_value = ("foo", "bar") # doesn't touch FS if `find_obsolete_build` produce error return code self.pruner.prune_obsolete_success_builds(os.path.join(self.tmp_dir_name, self.prj, self.chroots[0])) assert mc_popen.called assert_same_dirs( os.path.join(self.tmp_dir_name, self.prj, self.chroots[0]), os.path.join(self.expect_dir_name, self.prj, self.chroots[0]), )
def test_main_restart(self, mock_conn_string, mock_kafka_start, mock_kazoo): mock_conn_string.side_effect = [ ['1.1.1.1', '2.2.2.2'], ['2.2.2.2', '3.3.3.3'] ] mock_popen = MagicMock(spec=Popen) mock_kafka_start.return_value = mock_popen mock_popen.returncode = None main_return = main(loops=1, loop_interval=0.001, restart_interval=0.001) self.assertEqual(0, main_return) mock_kazoo.assert_called_with(hosts=ANY) self.assertEqual(2, mock_kafka_start.call_count)
def test_quality_error(self): # Patch the output stderr/stdout and returncode of `pylint` _mock_communicate = patch.object(subprocess, 'Popen').start() subproc_mock = MagicMock() subproc_mock.returncode = 1 subproc_mock.communicate.return_value = (b'file1.py:1: [C0111] Missing docstring', b'oops') _mock_communicate.return_value = subproc_mock # Parse the report quality = PylintQualityReporter('pylint', []) # Expect an error self.assertRaises(QualityReporterError, quality.violations, 'file1.py')
def test_main_restart(self, mock_conn_string, mock_kafka_start, mock_kazoo): mock_conn_string.side_effect = [['1.1.1.1', '2.2.2.2'], ['2.2.2.2', '3.3.3.3']] mock_popen = MagicMock(spec=Popen) mock_kafka_start.return_value = mock_popen mock_popen.returncode = None main_return = main(loops=1, loop_interval=0.001, restart_interval=0.001) self.assertEqual(0, main_return) mock_kazoo.assert_called_with(hosts=ANY) self.assertEqual(2, mock_kafka_start.call_count)
def test_run_xml_workflow(self, m_open, m_Popen): """test rm dry workflow""" proc = MagicMock() proc.returncode = 0 proc.communicate = MagicMock() proc.communicate.return_value = ('test_output', '') m_Popen.return_value = proc file_h = open(os.path.join(BASE_DIR, 'fixtures/sample_wf.xml')) m_open.return_value = file_h response = MagicMock() response.post = MagicMock() response.post.status_code = 250 response.post.json.return_value = "250" response.post.return_value = Response(400, text="true") with patch('requests.post', response): self.assertFalse(self.utilities_run.run_xml_workflow('sample_wf'))
def test_launchd_system(mocker): process_mock = MagicMock() process_mock.communicate.return_value = ( "stop", "", ) process_mock.returncode = 0 popen_mock = mocker.patch("subprocess.Popen", return_value=process_mock) mocker.patch("os.path.exists", return_value=True) mount_efs.start_watchdog("launchd") assert 2 == popen_mock.call_count assert "sudo" in popen_mock.call_args[0][0] assert "launchctl" in popen_mock.call_args[0][0] assert "load" in popen_mock.call_args[0][0]
def test_uninstall(self): process = MagicMock() process.communicate.return_value = ('', '') process.returncode = 0 self.popen.return_value = process self.ubuntu.uninstall(self.params) self.popen.assert_has_calls([ call( ['service', 'codedeploy-agent', 'stop'], stdout=subprocess.PIPE, stderr=subprocess.PIPE ), call().communicate() ]) self.check_call.assert_has_calls([ call(['dpkg', '-r', 'codedeploy-agent']) ])
def test_install(self): process = MagicMock() process.communicate.side_effect = [('', ''), ('Running', '')] process.returncode = 0 self.popen.return_value = process self.windows.install(self.params) self.popen.assert_has_calls([ call( [ 'powershell.exe', '-Command', 'Stop-Service', '-Name', 'codedeployagent' ], stdout=subprocess.PIPE, stderr=subprocess.PIPE ), call().communicate(), call( [ 'powershell.exe', '-Command', 'Get-Service', '-Name', 'codedeployagent' ], stdout=subprocess.PIPE, stderr=subprocess.PIPE ), call().communicate() ]) self.check_call.assert_has_calls([ call( [ r'.\{0}'.format(self.installer), '/quiet', '/l', r'.\codedeploy-agent-install-log.txt' ], shell=True ), call([ 'powershell.exe', '-Command', 'Restart-Service', '-Name', 'codedeployagent' ]) ]) self.open.assert_called_with(self.installer, 'wb') self.open().write.assert_called_with(self.body)
def test_callSnappy(): """ Test pdinstall.snappy.callSnappy """ from pdinstall.snappy import callSnappy with patch("pdinstall.snappy.subprocess") as subprocess: proc = MagicMock() subprocess.Popen.return_value = proc proc.stdout = ["Output message"] proc.stderr = ["Error message"] proc.returncode = 0 assert callSnappy("install") assert proc.wait.called subprocess.Popen.side_effect = Exception("Boom!") assert callSnappy("install") is False
def test_quality_deprecation_warning(self): # Patch the output stderr/stdout and returncode of `pylint` _mock_communicate = patch.object(subprocess, 'Popen').start() subproc_mock = MagicMock() # Pylint may raise deprecation warnings on pylint usage itself (such # as pylintrc configuration), but continue evaluating for violations. # Diff-quality, likewise, will continue. subproc_mock.returncode = 0 subproc_mock.communicate.return_value = ( b'file1.py:1: [C0111] Missing docstring\n' b'file1.py:1: [C0111, func_1] Missing docstring', b'Foobar: pylintrc deprecation warning' ) _mock_communicate.return_value = subproc_mock # Parse the report quality = PylintQualityReporter('pylint', []) actual_violations = quality.violations('file1.py') # Assert that pylint successfully runs and finds 2 violations self.assertEqual(len(actual_violations), 2)