def test_restore_files(self, Command): class temp_glob: def __init__(self, path): self.path = path self.index = 0 self.paths = [ 'anaconda-enterprise-anaconda-platform.yml', 'first.yaml', 'second.yaml', 'third.yaml' ] def __iter__(self): return self def __next__(self): index = self.index if index > 3: raise StopIteration() self.index += 1 return self.paths[index] Command().side_effect = [ 'REPLACE ERROR: (NotFound)', 'File created', sh.ErrorReturnCode_1('kubectl', ''.encode('utf-8'), ''.encode('utf-8')), sh.ErrorReturnCode_1('kubectl', ''.encode('utf-8'), ''.encode('utf-8')), 'file replaced' ] test_class = models.Accord( self.setup_args_restore_default(override=True, no_config=True)) with mock.patch('accord.process.glob.glob', side_effect=temp_glob): process.restoring_files(test_class)
def test_restore_ingress(self, Command): class temp_glob: def __init__(self, path): self.path = path self.index = 0 self.paths = ['master_ingress.yaml', 'failure.yaml'] def __iter__(self): return self def __next__(self): index = self.index if index > 1: raise StopIteration() self.index += 1 return self.paths[index] Command().side_effect = [ 'configured ingress', sh.ErrorReturnCode_1('kubectl', ''.encode('utf-8'), ''.encode('utf-8')) ] test_class = models.Accord( self.setup_args_restore_default(override=True, no_config=True, ingress=True)) with mock.patch('accord.process.glob.glob', side_effect=temp_glob): process.restoring_ingress(test_class)
def test_backup_ingress_failure(self, Command): test_class = None with mock.patch('accord.models.Accord.setup_backup_directory'): with mock.patch('accord.models.Accord.remove_signal_restore_file'): with mock.patch('accord.models.Accord.test_sync_to_backup'): test_class = models.Accord( self.setup_args_backup_default()) test_class.backup_directory = '.' Command().side_effect = sh.ErrorReturnCode_1('kubectl', ''.encode('utf-8'), ''.encode('utf-8')) with mock.patch('accord.models.Accord.get_all_ingress') as ingress: ingress.return_value = ['test-master', ''] try: process.backup_ingress_definitions(test_class) assert False, 'An error was not generated when it should have' except exceptions.IngressError: pass if not os.path.exists('ingress'): assert False, 'Did not automatically create the directory' if os.path.exists('ingress/test-master.yaml'): assert False, 'Created the ingress backup when it should not have'
def test_executes_catches_and_exits_return_code(patched_run_command, _instance): patched_run_command.side_effect = sh.ErrorReturnCode_1(sh.ls, b'', b'') with pytest.raises(SystemExit) as e: _instance.execute() assert 1 == e.value.code
def test_commit_error(self): self.forwarder.git = mock.Mock() self.forwarder.git.commit.side_effect = sh.ErrorReturnCode_1( "/usr/bin/git commit -am 'msg'", '', 'an error occured', False) with pytest.raises(tool.ManagerError) as exc: self.forwarder._commit() assert exc.value[0] == 'Committing failed: an error occured'
def test_backup_secrets_cm_failure_configmap(self, Command): test_class = None with mock.patch('accord.models.Accord.setup_backup_directory'): with mock.patch('accord.models.Accord.remove_signal_restore_file'): with mock.patch('accord.models.Accord.test_sync_to_backup'): test_class = models.Accord( self.setup_args_backup_default()) test_class.backup_directory = '.' test_class.secret_files = {} test_class.config_maps = {'default': ['test-cm']} Command().side_effect = sh.ErrorReturnCode_1('kubectl', ''.encode('utf-8'), ''.encode('utf-8')) with mock.patch('accord.models.Accord.get_all_secrets'): try: process.backup_secrets_config_maps(test_class) except exceptions.ConfigMapNotFound: pass except Exception: assert False, 'Exception should have been caught' if not os.path.exists('secrets'): assert False, 'Did not automatically create the directory' if not os.path.exists('secrets/test-cm.yaml'): assert False, 'Did not create the secret'
def test_executes_catches_and_exits_return_code( patched_run_command, _patched_ansible_galaxy_has_requirements_file, _instance ): patched_run_command.side_effect = sh.ErrorReturnCode_1(sh.ansible_galaxy, b'', b'') with pytest.raises(SystemExit) as e: _instance.execute() assert 1 == e.value.code
def test_cleanup_sessions_none(self, Command, grep, awk): awk().side_effect = [ sh.ErrorReturnCode_1('grep', 'out'.encode('utf-8'), 'error'.encode('utf-8')) ] test_class = models.Accord( self.setup_args_restore_default(override=True)) process.cleanup_sessions_deployments(test_class)
def test_scale_up_pod_success(self, Command, grep): grep().side_effect = [ 'kubectl', sh.ErrorReturnCode_1('grep', 'out'.encode('utf-8'), 'error'.encode('utf-8')), '' ] test_class = models.Accord( self.setup_args_restore_default(override=True)) process.scale_postgres_pod(test_class, 1)
def test_execute_exits_when_command_fails_and_exit_flag_set( mocker, patched_ansible_lint, patched_trailing, patched_ssh_config, patched_print_error, molecule_instance): patched_testinfra = mocker.patch('molecule.verifier.testinfra.Testinfra') patched_testinfra.side_effect = sh.ErrorReturnCode_1(sh.ls, b'', b'') v = verify.Verify({}, {}, molecule_instance) with pytest.raises(SystemExit): v.execute()
def test_executes_catches_and_exits_return_code( patched_flake8, patched_run_command, patched_testinfra_get_tests, testinfra_instance): patched_run_command.side_effect = sh.ErrorReturnCode_1(sh.testinfra, b'', b'') with pytest.raises(SystemExit) as e: testinfra_instance.execute() assert 1 == e.value.code
def test_scale_down_pod_success(self, Command, grep): Command().side_effect = ['', process_returns.RUNNING_PODS] grep().side_effect = [ 'NAME'.encode('utf-8'), sh.ErrorReturnCode_1('grep', 'out'.encode('utf-8'), 'error'.encode('utf-8')) ] test_class = models.Accord( self.setup_args_restore_default(override=True)) process.scale_postgres_pod(test_class, 0)
def test_commit_no_changes(self, captured_log): self.forwarder.git = mock.Mock() cmd = "/usr/bin/git commit -m 'ipa.dummy dump at 2017-12-29T23-59-59'" stdout = ("On branch master\nYour branch is up-to-date with " "'origin/master'.\nnothing to commit, working tree clean\n") self.forwarder.git.commit.side_effect = sh.ErrorReturnCode_1( cmd, stdout, '', False) with mock.patch('%s.socket.getfqdn' % modulename, lambda: 'ipa.dummy'): self.forwarder._commit() captured_log.check( ('GitHubForwarder', 'INFO', 'No changes, nothing to commit'))
def test_execute_returns_when_command_fails_and_exit_flag_unset( mocker, patched_ansible_lint, patched_trailing, patched_ssh_config, patched_print_error, molecule_instance): patched_testinfra = mocker.patch('molecule.verifier.testinfra.Testinfra') patched_testinfra.side_effect = sh.ErrorReturnCode_1(sh.ls, b'', b'') v = verify.Verify({}, {}, molecule_instance) result = v.execute(exit=False) patched_print_error.assert_called() assert (1, b'') == result
def test_executes_catches_and_exits_return_code_with_stdout( patched_run_command, patched_logger_critical, _instance): patched_run_command.side_effect = sh.ErrorReturnCode_1( sh.ansible_playbook, b'out', b'err') with pytest.raises(SystemExit) as e: _instance.execute() assert 1 == e.value.code msg = 'out' patched_logger_critical.assert_called_once_with(msg)
def test_main_error_tarball(self, Command, tar): Command().return_value = '' tar.side_effect = sh.ErrorReturnCode_1('tar', ''.encode('utf-8'), ''.encode('utf-8')) with mock.patch('repo_mirror.mirror.Mirror.build_yaml'): with mock.patch('repo_mirror.mirror.Mirror.run_mirror'): with mock.patch('repo_mirror.pool.upload_files'): pool.main() temp_archives = glob.glob('*.tar.gz') self.assertEqual(len(temp_archives), 0, 'Incorrect number of archives')
def test_restart_pods(self, Command, grep): Command().side_effect = ['', process_returns.RUNNING_PODS] grep().side_effect = [ 'kubectl', 'NAME'.encode('utf-8'), sh.ErrorReturnCode_1('grep', 'out'.encode('utf-8'), 'error'.encode('utf-8')) ] # grep().return_value = sh.ErrorReturnCode_1 test_class = models.Accord( self.setup_args_restore_default(override=True)) process.restart_pods(test_class)
def test_returns_when_command_fails_and_exit_flag_unset( mocker, patched_main, patched_ansible_lint, patched_trailing, patched_ssh_config, patched_logger_error, molecule_instance): mocked_testinfra = mocker.patch('molecule.verifier.testinfra.Testinfra') mocked_testinfra.side_effect = sh.ErrorReturnCode_1(sh.ls, None, None) v = verify.Verify([], dict(), molecule_instance) result = v.execute(exit=False) patched_logger_error.assert_called() assert (1, None) == result
def test_run_step_fail_sonar_scanner_internal_error(self, sonar_mock): self.__run__run_step_fail_sonar_scanner_error_test( sonar_scanner_error=sh.ErrorReturnCode_1('sonar-scanner', b'mock out', b'mock internal error'), expected_result_message_regex=re.compile( r"Error running static code analysis using sonar-scanner:" r".*RAN: sonar-scanner" r".*STDOUT:" r".*mock out" r".*STDERR:" r".*mock internal error", re.DOTALL), sonar_mock=sonar_mock)
def test_run_mirror_bad_config(self, Command): Command().side_effect = [ sh.ErrorReturnCode_1('cas-sync', ''.encode('utf-8'), ''.encode('utf-8')) ] test_class = mirror.Mirror() try: test_class.run_mirror('ae5-admin') assert False, 'Exception was not thrown' except exceptions.MirrorConfig: pass except Exception: assert False, 'Did not catch proper exception'
def test_exits_when_command_fails_and_exit_flag_set( mocker, patched_main, patched_ansible_lint, patched_trailing, patched_ssh_config, patched_logger_error, molecule_instance): mocked_testinfra = mocker.patch('molecule.verifier.testinfra.Testinfra') mocked_testinfra.side_effect = sh.ErrorReturnCode_1(sh.ls, None, None) v = verify.Verify([], dict(), molecule_instance) with pytest.raises(SystemExit): v.execute() msg = ("ERROR: \n\n RAN: <Command '/bin/ls'>\n\n " "STDOUT:\n<redirected>\n\n STDERR:\n<redirected>") patched_logger_error.assert_called_once_with(msg)
def test_push_error(self): self.forwarder.git = mock.Mock() cmd = '/usr/bin/git push billie-jean some-branch' stderr = ("error: src refspec master does not match any.\n" "error: failed to push some refs to " "'ssh://[email protected]/gooddata/gdc-ipa-utils.git'\n") self.forwarder.git.push.side_effect = sh.ErrorReturnCode_1( cmd, '', stderr, False) with pytest.raises(tool.ManagerError) as exc: self.forwarder._push() assert exc.value[0] == ( "Pushing failed: error: src refspec master does not match any.\n" "error: failed to push some refs to " "'ssh://[email protected]/gooddata/gdc-ipa-utils.git'\n")
def test_execute_exits_when_command_fails_and_exit_flag_set( mocker, patched_ansible_lint, patched_trailing, patched_ssh_config, patched_print_error, molecule_instance): patched_testinfra = mocker.patch('molecule.verifier.testinfra.Testinfra') patched_testinfra.side_effect = sh.ErrorReturnCode_1(sh.ls, None, None) v = verify.Verify({}, {}, molecule_instance) with pytest.raises(SystemExit): v.execute() ls_path = sh.which('ls') msg = ("\n\n RAN: <Command '{}'>\n\n " "STDOUT:\n<redirected>\n\n STDERR:\n<redirected>").format(ls_path) patched_print_error.assert_called_once_with(msg)
def test_main_error_file_list(self, Command): test_class = mirror.Mirror() Command().side_effect = [ sh.ErrorReturnCode_1('tree', ''.encode('utf-8'), ''.encode('utf-8')), '', '', '', '', '', '', '', '', '', '', '' ] with mock.patch('repo_mirror.mirror.Mirror.build_yaml'): with mock.patch('repo_mirror.mirror.Mirror.run_mirror'): with mock.patch('repo_mirror.pool.upload_files'): pool.main() temp_archives = glob.glob('*.tar.gz') platform_count = 0 for key, value in test_class.channels.items(): platform_count += len(value.get('platforms', [])) self.assertEqual(len(temp_archives), platform_count, 'Incorrect number of archives')
def __run_test___run_oscap_scan_xccdf_do_not_fetch_remote_with_profile_all_pass( self, buildah_mock, oscap_eval_type, oscap_fetch_remote_resources, oscap_stdout, oscap_stdout_expected, oscap_profile=None, oscap_tailoring_file=None, oscap_eval_success_expected=True, exit_code=0, oscap_eval_fails_expected=None): with TempDirectory() as temp_dir: buildah_unshare_comand = sh.buildah.bake('unshare') oscap_input_file = '/does/not/matter/input.xml' oscap_out_file_path = os.path.join(temp_dir.path, 'out') oscap_xml_results_file_path = '/does/not/matter/results.xml' oscap_html_report_path = '/does/not/matter/results.html' container_mount_path = '/does/not/matter/coutainer_mount' exception = None if exit_code == 2: exception = sh.ErrorReturnCode_2( 'oscap-chroot eval', bytes(oscap_stdout, 'utf-8'), bytes(f'mock error - exit code {exit_code}', 'utf-8')) elif exit_code == 1: exception = sh.ErrorReturnCode_1( 'oscap-chroot eval', bytes(oscap_stdout, 'utf-8'), bytes(f'mock error - exit code {exit_code}', 'utf-8')) elif exit_code: exception = sh.ErrorReturnCode( 'oscap-chroot eval', bytes(oscap_stdout, 'utf-8'), bytes(f'mock error - exit code {exit_code}', 'utf-8')) buildah_mock.bake('unshare').bake( 'oscap-chroot').side_effect = create_sh_side_effect( mock_stdout=oscap_stdout, exception=exception) stdout_buff = StringIO() with redirect_stdout(stdout_buff): oscap_eval_success, oscap_eval_fails = OpenSCAPGeneric._OpenSCAPGeneric__run_oscap_scan( buildah_unshare_comand=buildah_unshare_comand, oscap_eval_type=oscap_eval_type, oscap_input_file=oscap_input_file, oscap_out_file_path=oscap_out_file_path, oscap_xml_results_file_path=oscap_xml_results_file_path, oscap_html_report_path=oscap_html_report_path, container_mount_path=container_mount_path, oscap_profile=oscap_profile, oscap_tailoring_file=oscap_tailoring_file, oscap_fetch_remote_resources=oscap_fetch_remote_resources) if oscap_profile: oscap_profile_flag = f"--profile={oscap_profile}" else: oscap_profile_flag = None if oscap_fetch_remote_resources: oscap_fetch_remote_resources_flag = "--fetch-remote-resources" else: oscap_fetch_remote_resources_flag = None if oscap_tailoring_file: oscap_tailoring_file_flag = f"--tailoring-file={oscap_tailoring_file}" else: oscap_tailoring_file_flag = None buildah_mock.bake('unshare').bake.assert_called_with( 'oscap-chroot') buildah_mock.bake('unshare').bake( 'oscap-chroot').assert_called_once_with( container_mount_path, oscap_eval_type, 'eval', oscap_profile_flag, oscap_fetch_remote_resources_flag, oscap_tailoring_file_flag, f'--results={oscap_xml_results_file_path}', f'--report={oscap_html_report_path}', oscap_input_file, _out=Any(IOBase), _err=Any(IOBase), _tee='err') self.assertEqual(oscap_eval_success, oscap_eval_success_expected) if oscap_eval_fails_expected: self.assertEqual(oscap_eval_fails, oscap_eval_fails_expected) stdout = stdout_buff.getvalue() self.assertEqual(stdout, oscap_stdout_expected)
def _aux_sh(*args): call = args[0] if call == '-f': raise sh.ErrorReturnCode_1('blabla'.encode(), ''.encode(), ''.encode()) return