def test_register_add_channel(self): """Register an unregistered host and add another channel""" set_module_args({ 'activationkey': 'key', 'username': '******', 'password': '******', 'channels': 'rhel-x86_64-server-6-debuginfo' }) responses = [ ('auth.login', ['X' * 43]), ('channel.software.listSystemChannels', [[{ 'channel_name': 'Red Hat Enterprise Linux Server (v. 6 for 64-bit x86_64)', 'channel_label': 'rhel-x86_64-server-6'}]]), ('channel.software.setSystemChannels', [1]), ('auth.logout', [1]), ] with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.return_value = 0, '', '' # successful execution, no output with patch.object(rhn_register.Rhn, 'systemid', PropertyMock(return_value=12345)): with mock_request(responses, self.module.__name__): with self.assertRaises(AnsibleExitJson) as result: self.module.main() self.assertTrue(result.exception.args[0]['changed']) self.assertFalse(responses) # all responses should have been consumed self.assertEqual(self.mock_enable.call_count, 1) self.mock_enable.reset_mock() self.assertEqual(run_command.call_count, 1) self.assertEqual(run_command.call_args[0][0][0], '/usr/sbin/rhnreg_ks')
def test_module_utils_basic_ansible_module_set_mode_if_different(self): with patch('os.lstat') as m: with patch('os.lchmod', return_value=None, create=True) as m_os: m.side_effect = [self.mock_stat1, self.mock_stat2, self.mock_stat2] self.am._symbolic_mode_to_octal = MagicMock(side_effect=Exception) self.assertRaises(SystemExit, self.am.set_mode_if_different, '/path/to/file', 'o+w,g+w,a-r', False) original_hasattr = hasattr def _hasattr(obj, name): if obj == os and name == 'lchmod': return False return original_hasattr(obj, name) # FIXME: this isn't working yet with patch('os.lstat', side_effect=[self.mock_stat1, self.mock_stat2]): with patch.object(builtins, 'hasattr', side_effect=_hasattr): with patch('os.path.islink', return_value=False): with patch('os.chmod', return_value=None) as m_chmod: self.assertEqual(self.am.set_mode_if_different('/path/to/file/no_lchmod', 0o660, False), True) with patch('os.lstat', side_effect=[self.mock_stat1, self.mock_stat2]): with patch.object(builtins, 'hasattr', side_effect=_hasattr): with patch('os.path.islink', return_value=True): with patch('os.chmod', return_value=None) as m_chmod: with patch('os.stat', return_value=self.mock_stat2): self.assertEqual(self.am.set_mode_if_different('/path/to/file', 0o660, False), True)
def test_task_executor_poll_async_result(self): fake_loader = DictDataLoader({}) mock_host = MagicMock() mock_task = MagicMock() mock_task.async = 0.1 mock_task.poll = 0.05 mock_play_context = MagicMock() mock_connection = MagicMock() mock_action = MagicMock() mock_queue = MagicMock() shared_loader = MagicMock() shared_loader.action_loader = action_loader new_stdin = None job_vars = dict(omit="XXXXXXXXXXXXXXXXXXX") te = TaskExecutor( host = mock_host, task = mock_task, job_vars = job_vars, play_context = mock_play_context, new_stdin = new_stdin, loader = fake_loader, shared_loader_obj = shared_loader, rslt_q = mock_queue, ) te._connection = MagicMock() def _get(*args, **kwargs): mock_action = MagicMock() mock_action.run.return_value = dict(stdout='') return mock_action # testing with some bad values in the result passed to poll async, # and with a bad value returned from the mock action with patch.object(action_loader, 'get', _get): mock_templar = MagicMock() res = te._poll_async_result(result=dict(), templar=mock_templar) self.assertIn('failed', res) res = te._poll_async_result(result=dict(ansible_job_id=1), templar=mock_templar) self.assertIn('failed', res) def _get(*args, **kwargs): mock_action = MagicMock() mock_action.run.return_value = dict(finished=1) return mock_action # now testing with good values with patch.object(action_loader, 'get', _get): mock_templar = MagicMock() res = te._poll_async_result(result=dict(ansible_job_id=1), templar=mock_templar) self.assertEqual(res, dict(finished=1))
def test_module_utils_basic_ansible_module_set_mode_if_different(self): from ansible.module_utils import basic reload(basic) am = basic.AnsibleModule( argument_spec = dict(), ) mock_stat1 = MagicMock() mock_stat1.st_mode = 0o444 mock_stat2 = MagicMock() mock_stat2.st_mode = 0o660 with patch('os.lstat', side_effect=[mock_stat1]): self.assertEqual(am.set_mode_if_different('/path/to/file', None, True), True) with patch('os.lstat', side_effect=[mock_stat1]): self.assertEqual(am.set_mode_if_different('/path/to/file', None, False), False) with patch('os.lstat') as m: with patch('os.lchmod', return_value=None, create=True) as m_os: m.side_effect = [mock_stat1, mock_stat2, mock_stat2] self.assertEqual(am.set_mode_if_different('/path/to/file', 0o660, False), True) m_os.assert_called_with('/path/to/file', 0o660) m.side_effect = [mock_stat1, mock_stat2, mock_stat2] am._symbolic_mode_to_octal = MagicMock(return_value=0o660) self.assertEqual(am.set_mode_if_different('/path/to/file', 'o+w,g+w,a-r', False), True) m_os.assert_called_with('/path/to/file', 0o660) m.side_effect = [mock_stat1, mock_stat2, mock_stat2] am._symbolic_mode_to_octal = MagicMock(side_effect=Exception) self.assertRaises(SystemExit, am.set_mode_if_different, '/path/to/file', 'o+w,g+w,a-r', False) m.side_effect = [mock_stat1, mock_stat2, mock_stat2] am.check_mode = True self.assertEqual(am.set_mode_if_different('/path/to/file', 0o660, False), True) am.check_mode = False original_hasattr = hasattr def _hasattr(obj, name): if obj == os and name == 'lchmod': return False return original_hasattr(obj, name) # FIXME: this isn't working yet with patch('os.lstat', side_effect=[mock_stat1, mock_stat2]): with patch.object(builtins, 'hasattr', side_effect=_hasattr): with patch('os.path.islink', return_value=False): with patch('os.chmod', return_value=None) as m_chmod: self.assertEqual(am.set_mode_if_different('/path/to/file/no_lchmod', 0o660, False), True) with patch('os.lstat', side_effect=[mock_stat1, mock_stat2]): with patch.object(builtins, 'hasattr', side_effect=_hasattr): with patch('os.path.islink', return_value=True): with patch('os.chmod', return_value=None) as m_chmod: with patch('os.stat', return_value=mock_stat2): self.assertEqual(am.set_mode_if_different('/path/to/file', 0o660, False), True)
def test_run(self): ''' verifies that the GalaxyCLI object's api is created and that execute() is called. ''' gc = GalaxyCLI(args=["ansible-galaxy", "install", "--ignore-errors", "imaginary_role"]) gc.parse() with patch.object(ansible.cli.CLI, "execute", return_value=None) as mock_ex: with patch.object(ansible.cli.CLI, "run", return_value=None) as mock_run: gc.run() # testing self.assertEqual(mock_run.call_count, 1) self.assertTrue(isinstance(gc.api, ansible.galaxy.api.GalaxyAPI)) self.assertEqual(mock_ex.call_count, 1)
def setUp(self): super(TestOnyxVlanModule, self).setUp() self.mock_get_config = patch.object( onyx_vlan.OnyxVlanModule, "_get_vlan_config") self.get_config = self.mock_get_config.start() self.mock_load_config = patch( 'ansible.module_utils.network.onyx.onyx.load_config') self.load_config = self.mock_load_config.start() self.mock_get_version = patch.object( onyx_vlan.OnyxVlanModule, "_get_os_version") self.get_version = self.mock_get_version.start()
def setUp(self): super(TestOnyxLinkaggModule, self).setUp() self.mock_get_config = patch.object( onyx_linkagg.OnyxLinkAggModule, "_get_port_channels") self.get_config = self.mock_get_config.start() self.mock_load_config = patch( 'ansible.module_utils.network.onyx.onyx.load_config') self.load_config = self.mock_load_config.start() self.mock_get_version = patch.object( onyx_linkagg.OnyxLinkAggModule, "_get_os_version") self.get_version = self.mock_get_version.start()
def setUp(self): super(TestOnyxProtocolModule, self).setUp() self.mock_get_config = patch.object( onyx_protocol.OnyxProtocolModule, "_get_protocols") self.get_config = self.mock_get_config.start() self.mock_get_ip_config = patch.object( onyx_protocol.OnyxProtocolModule, "_get_ip_routing") self.get_ip_config = self.mock_get_ip_config.start() self.mock_load_config = patch( 'ansible.module_utils.network.onyx.onyx.load_config') self.load_config = self.mock_load_config.start()
def setUp(self): super(TestOnyxMlagVipModule, self).setUp() self._mlag_enabled = True self.mock_show_mlag = patch.object( onyx_mlag_vip.OnyxMLagVipModule, "_show_mlag") self.show_mlag = self.mock_show_mlag.start() self.mock_show_mlag_vip = patch.object( onyx_mlag_vip.OnyxMLagVipModule, "_show_mlag_vip") self.show_mlag_vip = self.mock_show_mlag_vip.start() self.mock_load_config = patch( 'ansible.module_utils.network.onyx.onyx.load_config') self.load_config = self.mock_load_config.start()
def test_content_written(self): with patch.object(builtins, 'open', mock_open()) as m: password._write_password_file(b'/this/is/a/test/caf\xc3\xa9', u'Testing Café') m.assert_called_once_with(b'/this/is/a/test/caf\xc3\xa9', 'wb') m().write.assert_called_once_with(u'Testing Café\n'.encode('utf-8'))
def setUp(self): """Setup.""" super(TestIcinga2Feature, self).setUp() self.module = icinga2_feature self.mock_get_bin_path = patch.object(basic.AnsibleModule, 'get_bin_path', get_bin_path) self.mock_get_bin_path.start() self.addCleanup(self.mock_get_bin_path.stop) # ensure that the patching is 'undone'
def test_botocore_exception_without_response_reports_nicely_via_fail_json_aws(self): basic._ANSIBLE_ARGS = to_bytes(json.dumps({'ANSIBLE_MODULE_ARGS': {}})) module = AnsibleAWSModule(argument_spec=dict( fail_mode=dict(type='list', default=['success']) )) fail_json_double = Mock() err_msg = None with patch.object(basic.AnsibleModule, 'fail_json', fail_json_double): try: raise botocore.exceptions.ClientError(err_msg, 'Could not find you') except Exception as e: print("exception is " + str(e)) module.fail_json_aws(e, msg="Fake failure for testing boto exception messages") assert(len(fail_json_double.mock_calls) > 0), "failed to call fail_json when should have" assert(len(fail_json_double.mock_calls) < 2), "called fail_json multiple times" assert("test_botocore_exception_without_response_reports_nicely_via_fail_json_aws" in fail_json_double.mock_calls[0][2]["exception"]), \ "exception traceback doesn't include correct function, fail call was actually: " \ + str(fail_json_double.mock_calls[0]) assert("Fake failure for testing boto exception messages" in fail_json_double.mock_calls[0][2]["msg"]), \ "error message doesn't include the local message; was: " \ + str(fail_json_double.mock_calls[0])
def test_create_lambda_if_not_exist(): set_module_args(base_module_args) (boto3_conn_double, lambda_client_double) = make_mock_no_connection_connection(code_change_lambda_config) with patch.object(lda, 'boto3_conn', boto3_conn_double): try: lda.main() except SystemExit: pass # guard against calling other than for a lambda connection (e.g. IAM) assert(len(boto3_conn_double.mock_calls) > 0), "boto connections never used" assert(len(boto3_conn_double.mock_calls) < 2), "multiple boto connections used unexpectedly" assert(len(lambda_client_double.update_function_configuration.mock_calls) == 0), \ "unexpectedly updated lambda configuration when should have only created" assert(len(lambda_client_double.update_function_code.mock_calls) == 0), \ "update lambda function code when function should have been created only" assert(len(lambda_client_double.create_function.mock_calls) > 0), \ "failed to call create_function " (create_args, create_kwargs) = lambda_client_double.create_function.call_args assert (len(create_kwargs) > 0), "expected create called with keyword args, none found" try: # For now I assume that we should NOT send an empty environment. It might # be okay / better to explicitly send an empty environment. However `None' # is not acceptable - mikedlr create_kwargs["Environment"] raise(Exception("Environment sent to boto when none expected")) except KeyError: pass # We are happy, no environment is fine
def test_policy_table_no_change(self): """Test don't change policy of a chain if the policy is right""" set_module_args({ 'policy': 'ACCEPT', 'chain': 'INPUT', }) commands_results = [ (0, 'Chain INPUT (policy ACCEPT)\n', ''), (0, '', '') ] with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.side_effect = commands_results with self.assertRaises(AnsibleExitJson) as result: iptables.main() self.assertFalse(result.exception.args[0]['changed']) self.assertEqual(run_command.call_count, 1) # import pdb # pdb.set_trace() self.assertEqual(run_command.call_args_list[0][0][0], [ '/sbin/iptables', '-t', 'filter', '-L', 'INPUT', ])
def run_parse_common(self, galaxycli_obj, action): with patch.object(ansible.cli.SortedOptParser, "set_usage") as mocked_usage: galaxycli_obj.parse() # checking that the common results of parse() for all possible actions have been created/called self.assertIsInstance(galaxycli_obj.parser, ansible.cli.SortedOptParser) self.assertIsInstance(galaxycli_obj.galaxy, ansible.galaxy.Galaxy) formatted_call = { 'import': 'usage: %prog import [options] github_user github_repo', 'delete': 'usage: %prog delete [options] github_user github_repo', 'info': 'usage: %prog info [options] role_name[,version]', 'init': 'usage: %prog init [options] role_name', 'install': 'usage: %prog install [options] [-r FILE | role_name(s)[,version] | scm+role_repo_url[,version] | tar_file(s)]', 'list': 'usage: %prog list [role_name]', 'login': '******', 'remove': 'usage: %prog remove role1 role2 ...', 'search': ('usage: %prog search [searchterm1 searchterm2] [--galaxy-tags galaxy_tag1,galaxy_tag2] [--platforms platform1,platform2] ' '[--author username]'), 'setup': 'usage: %prog setup [options] source github_user github_repo secret', } first_call = 'usage: %prog [delete|import|info|init|install|list|login|remove|search|setup] [--help] [options] ...' second_call = formatted_call[action] calls = [call(first_call), call(second_call)] mocked_usage.assert_has_calls(calls)
def test_policy_table_changed_false(self): """Test flush without parameters and change == false""" set_module_args({ 'policy': 'ACCEPT', 'chain': 'INPUT', '_ansible_check_mode': True, }) commands_results = [ (0, 'Chain INPUT (policy DROP)\n', ''), ] with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.side_effect = commands_results with self.assertRaises(AnsibleExitJson) as result: iptables.main() self.assertTrue(result.exception.args[0]['changed']) self.assertEqual(run_command.call_count, 1) # import pdb # pdb.set_trace() self.assertEqual(run_command.call_args_list[0][0][0], [ '/sbin/iptables', '-t', 'filter', '-L', 'INPUT', ])
def test_insert_jump_reject_with_reject(self): """ Using reject_with with a previously defined jump: REJECT results in two Jump statements #18988 """ set_module_args({ 'chain': 'INPUT', 'protocol': 'tcp', 'jump': 'REJECT', 'reject_with': 'tcp-reset', 'ip_version': 'ipv4', }) commands_results = [ (0, '', ''), ] with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.side_effect = commands_results with self.assertRaises(AnsibleExitJson) as result: iptables.main() self.assertTrue(result.exception.args[0]['changed']) self.assertEqual(run_command.call_count, 1) self.assertEqual(run_command.call_args_list[0][0][0], [ '/sbin/iptables', '-t', 'filter', '-C', 'INPUT', '-p', 'tcp', '-j', 'REJECT', '--reject-with', 'tcp-reset', ])
def test_ensure_backupPlanName_outputs_correctly(self): """ Testing that command is executed with correct args :return: """ set_module_args({ 'operation': "Provision", 'opsName': 'Provision_test', 'WS': "PLMN-PLMN/MRBTS-746", 'createBackupPlan': "Yes", 'backupPlanName': "backupPlanName" }) with patch.object(basic.AnsibleModule, 'run_command') as mock_run_command: stdout = 'configuration updated' stderr = '' return_code = 0 mock_run_command.return_value = return_code, stdout, stderr # successful execution with self.assertRaises(AnsibleExitJson) as result: netact_cm_command.main() print(result.exception.args) self.assertTrue(result.exception.args[0]['changed']) # ensure result is changed mock_run_command.assert_called_once_with( ['/opt/oss/bin/racclimx.sh', '-op', 'Provision', '-opsName', 'Provision_test', '-WS', 'PLMN-PLMN/MRBTS-746', '-createBackupPlan', 'true', '-backupPlanName', 'backupPlanName'], check_rc=True)
def test_unregister_unknown_host(self, mock_unlink): """Unregister an unknown host (an host with a systemid available locally, check that result contains failed""" set_module_args({ 'activationkey': 'key', 'username': '******', 'password': '******', 'state': 'absent', }) responses = [ ('auth.login', ['X' * 43]), ('system.deleteSystems', xmlrpc_client.Fault(1003, 'The following systems were NOT deleted: 123456789')), ('auth.logout', [1]), ] with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.return_value = 0, '', '' # successful execution, no output mock_is_registered = PropertyMock(return_value=True) mock_systemid = PropertyMock(return_value=12345) with patch.multiple(rhn_register.Rhn, systemid=mock_systemid, is_registered=mock_is_registered): with mock_request(responses, self.module.__name__): with self.assertRaises(AnsibleFailJson) as result: self.module.main() self.assertTrue(result.exception.args[0]['failed']) self.assertFalse(responses) # all responses should have been consumed self.assertEqual(mock_systemid.call_count, 1) self.assertEqual(mock_is_registered.call_count, 1) self.assertFalse(run_command.called) self.assertFalse(mock_unlink.called)
def test_unregister(self, mock_unlink): """Unregister an host, check that result is changed""" mock_unlink.return_value = True set_module_args({ 'activationkey': 'key', 'username': '******', 'password': '******', 'state': 'absent', }) responses = [ ('auth.login', ['X' * 43]), ('system.deleteSystems', [1]), ('auth.logout', [1]), ] with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.return_value = 0, '', '' # successful execution, no output mock_is_registered = PropertyMock(return_value=True) mock_systemid = PropertyMock(return_value=12345) with patch.multiple(rhn_register.Rhn, systemid=mock_systemid, is_registered=mock_is_registered): with mock_request(responses, self.module.__name__): with self.assertRaises(AnsibleExitJson) as result: self.module.main() self.assertTrue(result.exception.args[0]['changed']) self.assertFalse(responses) # all responses should have been consumed self.assertEqual(mock_systemid.call_count, 1) self.assertEqual(mock_is_registered.call_count, 1) self.assertFalse(run_command.called) self.assertEqual(mock_unlink.call_count, 1)
def test_ensure_command_called(self): """ Testing that command is executed with correct args :return: """ set_module_args({ 'operation': "Upload", 'opsName': 'Uploading_testi', 'DN': "PLMN-PLMN/MRBTS-746", }) with patch.object(basic.AnsibleModule, 'run_command') as mock_run_command: stdout = 'configuration updated' stderr = '' return_code = 0 mock_run_command.return_value = return_code, stdout, stderr # successful execution with self.assertRaises(AnsibleExitJson) as result: netact_cm_command.main() print(result.exception.args) self.assertTrue(result.exception.args[0]['changed']) # ensure result is changed mock_run_command.assert_called_once_with( ['/opt/oss/bin/racclimx.sh', '-op', 'Upload', '-opsName', 'Uploading_testi', '-DN', 'PLMN-PLMN/MRBTS-746'], check_rc=True)
def test_remove_rule_check_mode(self): """Test flush without parameters check mode""" set_module_args({ 'chain': 'PREROUTING', 'source': '1.2.3.4/32', 'destination': '7.8.9.10/42', 'jump': 'SNAT', 'table': 'nat', 'to_source': '5.5.5.5/32', 'protocol': 'udp', 'source_port': '22', 'to_ports': '8600', 'state': 'absent', 'in_interface': 'eth0', 'out_interface': 'eth1', 'comment': 'this is a comment', '_ansible_check_mode': True, }) commands_results = [ (0, '', ''), ] with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.side_effect = commands_results with self.assertRaises(AnsibleExitJson) as result: iptables.main() self.assertTrue(result.exception.args[0]['changed']) self.assertEqual(run_command.call_count, 1) self.assertEqual(run_command.call_args_list[0][0][0], [ '/sbin/iptables', '-t', 'nat', '-C', 'PREROUTING', '-p', 'udp', '-s', '1.2.3.4/32', '-d', '7.8.9.10/42', '-j', 'SNAT', '--to-source', '5.5.5.5/32', '-i', 'eth0', '-o', 'eth1', '--source-port', '22', '--to-ports', '8600', '-m', 'comment', '--comment', 'this is a comment' ])
def test_exit_without_ignore_with_flag(self): ''' tests that GalaxyCLI exits without the error specified if the --ignore-errors flag is used ''' # testing with --ignore-errors flag gc = GalaxyCLI(args=["ansible-galaxy", "install", "--server=None", "fake_role_name", "--ignore-errors"]) gc.parse() with patch.object(ansible.utils.display.Display, "display", return_value=None) as mocked_display: gc.run() self.assertTrue(mocked_display.called_once_with("- downloading role 'fake_role_name', owned by "))
def setUp(self): super(TestOnyxInterfaceModule, self).setUp() self.mock_get_config = patch.object( onyx_interface.OnyxInterfaceModule, "_get_interfaces_config") self.get_config = self.mock_get_config.start() self.mock_get_interfaces_status = patch.object( onyx_interface.OnyxInterfaceModule, "_get_interfaces_status") self.get_interfaces_status = self.mock_get_interfaces_status.start() self.mock_get_interfaces_rates = patch.object( onyx_interface.OnyxInterfaceModule, "_get_interfaces_rates") self.get_interfaces_rates = self.mock_get_interfaces_rates.start() self.mock_load_config = patch( 'ansible.module_utils.network.onyx.onyx.load_config') self.load_config = self.mock_load_config.start()
def test_password_already_created_encrypt(self, mock_get_paths, mock_write_file): mock_get_paths.return_value = ['/path/one', '/path/two', '/path/three'] password.os.path.exists = lambda x: True with patch.object(builtins, 'open', mock_open(read_data=b'hunter42 salt=87654321\n')) as m: results = self.password_lookup.run([u'/path/to/somewhere chars=anything encrypt=pbkdf2_sha256'], None) for result in results: self.assertEqual(result, u'$pbkdf2-sha256$20000$ODc2NTQzMjE$Uikde0cv0BKaRaAXMrUQB.zvG4GmnjClwjghwIRf2gU')
def test_read_file_not_executable(self, mock_popen): self._mock_popen(mock_popen) secret = vault.ScriptVaultSecret() with patch.object(secret, 'loader') as mock_loader: mock_loader.is_executable = MagicMock(return_value=False) self.assertRaisesRegexp(vault.AnsibleVaultError, 'The vault password script .* was not executable', secret.load)
def test_exit_without_ignore_without_flag(self): ''' tests that GalaxyCLI exits with the error specified if the --ignore-errors flag is not used ''' gc = GalaxyCLI(args=["install", "--server=None", "fake_role_name"]) gc.parse() with patch.object(ansible.utils.display.Display, "display", return_value=None) as mocked_display: # testing that error expected is raised self.assertRaises(AnsibleError, gc.run) self.assertTrue(mocked_display.called_once_with("- downloading role 'fake_role_name', owned by "))
def test_read_file_empty(self, mock_popen): self._mock_popen(mock_popen, stdout=b'') secret = vault.ScriptVaultSecret() with patch.object(secret, 'loader') as mock_loader: mock_loader.is_executable = MagicMock(return_value=True) self.assertRaisesRegexp(vault.AnsibleVaultPasswordError, 'Invalid vault password was provided from script', secret.load)
def setUp(self): super(TestOnyxBgpModule, self).setUp() self.mock_get_config = patch.object( onyx_bgp.OnyxBgpModule, "_get_bgp_summary") self.get_config = self.mock_get_config.start() self.mock_load_config = patch( 'ansible.module_utils.network.onyx.onyx.load_config') self.load_config = self.mock_load_config.start()
def test_read_file_os_error(self, mock_popen): self._mock_popen(mock_popen) mock_popen.side_effect = OSError('That is not an executable') secret = vault.ScriptVaultSecret() with patch.object(secret, 'loader') as mock_loader: mock_loader.is_executable = MagicMock(return_value=True) self.assertRaisesRegexp(errors.AnsibleError, 'Problem running vault password script.*', secret.load)
def failed(self): def fail_json(*args, **kwargs): kwargs['failed'] = True raise AnsibleFailJson(kwargs) with patch.object(basic.AnsibleModule, 'fail_json', fail_json): with self.assertRaises(AnsibleFailJson) as exc: self.module.main() result = exc.exception.args[0] self.assertTrue(result['failed'], result) return result
def setUp(self): super(TestOnyxInterfaceModule, self).setUp() self.mock_get_config = patch.object( onyx_interface.OnyxInterfaceModule, "_get_interfaces_config") self.get_config = self.mock_get_config.start() self.mock_get_interfaces_status = patch.object( onyx_interface.OnyxInterfaceModule, "_get_interfaces_status") self.get_interfaces_status = self.mock_get_interfaces_status.start() self.mock_get_interfaces_rates = patch.object( onyx_interface.OnyxInterfaceModule, "_get_interfaces_rates") self.get_interfaces_rates = self.mock_get_interfaces_rates.start() self.mock_load_config = patch( 'ansible.module_utils.network.onyx.onyx.load_config') self.load_config = self.mock_load_config.start() self.mock_get_version = patch.object( onyx_interface.OnyxInterfaceModule, "_get_os_version") self.get_version = self.mock_get_version.start()
def test_exit_without_ignore_without_flag(self): ''' tests that GalaxyCLI exits with the error specified if the --ignore-errors flag is not used ''' gc = GalaxyCLI(args=["install", "--server=None", "fake_role_name"]) gc.parse() with patch.object(ansible.utils.display.Display, "display", return_value=None) as mocked_display: # testing that error expected is raised self.assertRaises(AnsibleError, gc.run) self.assertTrue( mocked_display.called_once_with( "- downloading role 'fake_role_name', owned by "))
def test_module_utils_basic_imports(self): realimport = builtins.__import__ def _mock_import(name, *args, **kwargs): if name == 'json': raise ImportError() realimport(name, *args, **kwargs) with patch.object(builtins, '__import__', _mock_import, create=True) as m: m('ansible.module_utils.basic') builtins.__import__('ansible.module_utils.basic')
def test_module_parameters(self, *args): arguments = dict( service_template="app-svcs-int-v2.0-default", connector="foo", name="bar", parameters=load_fixture('create_iworkflow_service.json'), tenant="tenant-foo", state="present") with patch.object(Parameters, '_get_connector_collection') as mo: mo.return_value = self.loaded_connectors p = Parameters(arguments) assert p.name == 'bar' # Check that tenant is correct assert 'link' in p.tenantTemplateReference assert p.tenantTemplateReference['link'] == \ 'https://localhost/mgmt/cm/cloud/tenant/templates/iapp/app-svcs-int-v2.0-default' # Check that cloud connector is correct assert len(p.connector) == 1 assert p.connector[0]['id'] == 'cloudConnectorReference' assert p.connector[0]['value'] == \ 'https://localhost/mgmt/cm/cloud/connectors/local/212301e6-6d01-4509-bfe3-8e372e792fb0' # Check that vars are correct assert len(p.vars) == 3 assert p.vars[0]['name'] == 'pool__addr' assert p.vars[0]['value'] == '172.27.1.10' assert p.vars[1]['name'] == 'pool__port' assert p.vars[1]['value'] == '900' assert p.vars[2]['name'] == 'vs__ProfileClientProtocol' assert p.vars[2]['value'] == 'tcp' # Check that tables are correct assert len(p.tables) == 1 assert 'name' in p.tables[0] assert 'section' in p.tables[0] assert 'columnNames' in p.tables[0] assert 'rows' in p.tables[0] assert p.tables[0]['name'] == 'pool__Members' assert p.tables[0]['section'] == 'pool' assert p.tables[0]['columnNames'] == ['IPAddress', 'Port'] assert len(p.tables[0]['rows']) == 2 assert len(p.tables[0]['rows'][0]) == 2 assert p.tables[0]['rows'][0] == ['20.0.1.11', '80'] assert p.tables[0]['rows'][1] == ['20.0.1.12'] assert p.tables[0]['rows'][0][0] == '20.0.1.11' assert p.tables[0]['rows'][0][1] == '80' assert p.tables[0]['rows'][1][0] == '20.0.1.12'
def test_enable_feature_with_check_mode(self): """Check that result is changed in check mode.""" set_module_args({ 'name': 'api', '_ansible_check_mode': True, }) with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.return_value = 0, '', '' # successful execution, no output with self.assertRaises(AnsibleExitJson) as result: icinga2_feature.main() self.assertTrue(result.exception.args[0]['changed']) self.assertEqual(run_command.call_count, 1)
def test_read_file_non_zero_return_code(self, mock_popen): stderr = b'That did not work for a random reason' rc = 37 self._mock_popen(mock_popen, return_code=rc, stderr=stderr) secret = vault.ScriptVaultSecret( filename='/dev/null/some_vault_secret') with patch.object(secret, 'loader') as mock_loader: mock_loader.is_executable = MagicMock(return_value=True) self.assertRaisesRegexp( errors.AnsibleError, r'Vault password script.*returned non-zero \(%s\): %s' % (rc, stderr), secret.load)
def test_password_already_created_no_encrypt(self, mock_get_paths, mock_write_file): mock_get_paths.return_value = ['/path/one', '/path/two', '/path/three'] password.os.path.exists = lambda x: True with patch.object( builtins, 'open', mock_open(read_data=b'hunter42 salt=87654321\n')) as m: results = self.password_lookup.run( [u'/path/to/somewhere chars=anything'], None) for result in results: self.assertEqual(result, u'hunter42')
def changed(self, changed=False): def exit_json(*args, **kwargs): if 'changed' not in kwargs: kwargs['changed'] = False raise AnsibleExitJson(kwargs) with patch.object(basic.AnsibleModule, 'exit_json', exit_json): with self.assertRaises(AnsibleExitJson) as exc: self.module.main() result = exc.exception.args[0] self.assertEqual(result['changed'], changed, result) return result
def test_lock_been_held(self): # pretend the lock file is here password.os.path.exists = lambda x: True try: with patch.object( builtins, 'open', mock_open(read_data=b'hunter42 salt=87654321\n')) as m: # should timeout here results = self.password_lookup.run( [u'/path/to/somewhere chars=anything'], None) self.fail("Lookup didn't timeout when lock already been held") except AnsibleError: pass
def setUp(self): self.module = rhn_register self.module.HAS_UP2DATE_CLIENT = True load_config_return = { 'serverURL': 'https://xmlrpc.rhn.redhat.com/XMLRPC', 'systemIdPath': '/etc/sysconfig/rhn/systemid' } self.mock_load_config = patch.object(rhn_register.Rhn, 'load_config', return_value=load_config_return) self.mock_load_config.start() self.addCleanup(self.mock_load_config.stop) self.mock_exit_fail = patch.multiple(basic.AnsibleModule, exit_json=exit_json, fail_json=fail_json) self.mock_exit_fail.start() self.addCleanup(self.mock_exit_fail.stop) enable_patcher = patch.object(rhn_register.Rhn, 'enable') self.mock_enable = enable_patcher.start() self.addCleanup(enable_patcher.stop)
def test_api_parameters(self): args = dict(name='somevlan', description='fakevlan', tag=213, tagged_interfaces=['1.2']) with patch.object(Parameters, '_get_interfaces_from_device') as obj: obj.return_value = self.loaded_ifcs p = Parameters(args) assert p.name == 'somevlan' assert p.tag == 213 assert p.interfaces == [{'tagged': True, 'name': '1.2'}] assert p.description == 'fakevlan'
def test_warn_region_not_specified(): set_module_args({ "name": "lambda_name", "state": "present", # Module is called without a region causing error # "region": "us-east-1", "zip_file": "test/units/modules/cloud/amazon/fixtures/thezip.zip", "runtime": 'python2.7', "role": 'arn:aws:iam::987654321012:role/lambda_basic_execution', "handler": 'lambda_python.my_handler' }) get_aws_connection_info_double = Mock(return_value=(None, None, None)) with patch.object(lda, 'get_aws_connection_info', get_aws_connection_info_double): with patch.object(basic.AnsibleModule, 'fail_json', fail_json_double): try: lda.main() except AnsibleFailJson as e: result = e.args[0] assert ("region must be specified" in result['msg'])
def test_flush_table_check_true(self): """Test flush without parameters and check == true""" set_module_args({ 'flush': True, '_ansible_check_mode': True, }) with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.return_value = 0, '', '' # successful execution, no output with self.assertRaises(AnsibleExitJson) as result: iptables.main() self.assertTrue(result.exception.args[0]['changed']) self.assertEqual(run_command.call_count, 0)
def test_insert_rule(self): """Test flush without parameters""" set_module_args({ 'chain': 'OUTPUT', 'source': '1.2.3.4/32', 'destination': '7.8.9.10/42', 'jump': 'ACCEPT', 'action': 'insert' }) commands_results = [ (1, '', ''), (0, '', '') ] with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.side_effect = commands_results with self.assertRaises(AnsibleExitJson) as result: iptables.main() self.assertTrue(result.exception.args[0]['changed']) self.assertEqual(run_command.call_count, 2) # import pdb # pdb.set_trace() self.assertEqual(run_command.call_args_list[0][0][0], [ '/sbin/iptables', '-t', 'filter', '-C', 'OUTPUT', '-s', '1.2.3.4/32', '-d', '7.8.9.10/42', '-j', 'ACCEPT' ]) self.assertEqual(run_command.call_args_list[1][0][0], [ '/sbin/iptables', '-t', 'filter', '-I', 'OUTPUT', '-s', '1.2.3.4/32', '-d', '7.8.9.10/42', '-j', 'ACCEPT' ])
def test_module_parameters(self): args = dict( name='somevlan', tag=213, description='fakevlan', untagged_interfaces=['1.1'], ) with patch.object(Parameters, '_get_interfaces_from_device') as obj: obj.return_value = self.loaded_ifcs p = Parameters(args) assert p.name == 'somevlan' assert p.tag == 213 assert p.description == 'fakevlan' assert p.untagged_interfaces == ['1.1']
def test_exit_without_ignore_with_flag(self): ''' tests that GalaxyCLI exits without the error specified if the --ignore-errors flag is used ''' # testing with --ignore-errors flag gc = GalaxyCLI(args=[ "ansible-galaxy", "install", "--server=None", "fake_role_name", "--ignore-errors" ]) gc.parse() with patch.object(ansible.utils.display.Display, "display", return_value=None) as mocked_display: gc.run() self.assertTrue( mocked_display.called_once_with( "- downloading role 'fake_role_name', owned by "))
def test_already_registered(self): """Register an host already registered, check that result is unchanged""" set_module_args({ 'activationkey': 'key', 'username': '******', 'password': '******', }) responses = [] with patch.object(basic.AnsibleModule, 'run_command') as run_command: with patch.object( rhn_register.Rhn, 'is_registered', PropertyMock(return_value=True)) as mock_systemid: with mock_request(responses) as req: with self.assertRaises(AnsibleExitJson) as result: self.module.main() self.assertFalse(result.exception.args[0]['changed']) self.assertFalse(req.called) self.assertEqual(mock_systemid.call_count, 1) self.assertEqual(self.mock_enable.call_count, 0) self.assertFalse(run_command.called)
def test_register_add_channel(self): """Register an unregistered host and add another channel""" set_module_args({ 'activationkey': 'key', 'username': '******', 'password': '******', 'channels': 'rhel-x86_64-server-6-debuginfo' }) responses = [ ('auth.login', ['X' * 43]), ('channel.software.listSystemChannels', [[{ 'channel_name': 'Red Hat Enterprise Linux Server (v. 6 for 64-bit x86_64)', 'channel_label': 'rhel-x86_64-server-6' }]]), ('channel.software.setSystemChannels', [1]), ('auth.logout', [1]), ] with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.return_value = 0, '', '' # successful execution, no output with patch.object(rhn_register.Rhn, 'systemid', PropertyMock(return_value=12345)): with mock_request(responses): with self.assertRaises(AnsibleExitJson) as result: self.module.main() self.assertTrue(result.exception.args[0]['changed']) self.assertFalse( responses) # all responses should have been consumed self.assertEqual(self.mock_enable.call_count, 1) self.mock_enable.reset_mock() self.assertEqual(run_command.call_count, 1) self.assertEqual(run_command.call_args[0][0][0], '/usr/sbin/rhnreg_ks')
def test_module_parameters_properties(self): params = dict(connector='foo') with patch.object(Parameters, '_get_connector_collection') as mo: mo.return_value = self.loaded_connectors p = Parameters() p.update(params) assert len(p.properties) == 1 assert 'id' in p.properties[0] assert 'isRequired' in p.properties[0] assert 'provider' in p.properties[0] assert p.properties[0]['id'] == 'cloudConnectorReference' assert p.properties[0]['isRequired'] is True assert p.properties[0][ 'provider'] == 'https://localhost/mgmt/cm/cloud/connectors/local/212301e6-6d01-4509-bfe3-8e372e792fb0'
def test_lock_not_been_held(self): # pretend now there is password file but no lock password.os.path.exists = lambda x: x == to_bytes('/path/to/somewhere') try: with patch.object( builtins, 'open', mock_open(read_data=b'hunter42 salt=87654321\n')) as m: # should not timeout here results = self.password_lookup.run( [u'/path/to/somewhere chars=anything'], None) except AnsibleError: self.fail('Lookup timeouts when lock is free') for result in results: self.assertEqual(result, u'hunter42')
def test_await_should_wait_till_not_pending(): sleeper_double = MagicMock() rds_client_double = MagicMock() rds_client_double.describe_db_instances.side_effect = [ simple_instance_list('rebooting', { "a": "b", "c": "d" }), simple_instance_list('available', { "c": "d", "e": "f" }), simple_instance_list('rebooting', {"a": "b"}), simple_instance_list('rebooting', { "e": "f", "g": "h" }), simple_instance_list('rebooting', {}), simple_instance_list('available', { "g": "h", "i": "j" }), simple_instance_list('rebooting', { "i": "j", "k": "l" }), simple_instance_list('available', {}), simple_instance_list('available', {}), ] mod_mock = MagicMock() # we need our wait timeout to always be bigger than current time so that we use the # above values to check that the correct state has been waited for. mod_mock.params.get.return_value.__add__.return_value.__gt__.return_value = True mod_mock.params.get.return_value.__add__.return_value.__lt__.return_value = False mod_mock.params.get.return_value.__add__.return_value.__le__.return_value = False with patch.object(time, 'sleep', sleeper_double): rds_i.await_resource(rds_client_double, "some-instance", "available", mod_mock, await_pending=1) print("dbinstance calls:\n" + str(rds_client_double.describe_db_instances.mock_calls)) assert (len(sleeper_double.mock_calls) > 5), "await_pending didn't wait enough" assert (len(rds_client_double.describe_db_instances.mock_calls) > 7), "await_pending waited more than needed"
def test_tcp_flags(self): """ Test various ways of inputting tcp_flags """ args = [ { 'chain': 'OUTPUT', 'protocol': 'tcp', 'jump': 'DROP', 'tcp_flags': 'flags=ALL flags_set="ACK,RST,SYN,FIN"' }, { 'chain': 'OUTPUT', 'protocol': 'tcp', 'jump': 'DROP', 'tcp_flags': { 'flags': 'ALL', 'flags_set': 'ACK,RST,SYN,FIN' } }, { 'chain': 'OUTPUT', 'protocol': 'tcp', 'jump': 'DROP', 'tcp_flags': { 'flags': ['ALL'], 'flags_set': ['ACK', 'RST', 'SYN', 'FIN'] } }, ] for item in args: set_module_args(item) commands_results = [ (0, '', ''), ] with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.side_effect = commands_results with self.assertRaises(AnsibleExitJson) as result: iptables.main() self.assertTrue(result.exception.args[0]['changed']) self.assertEqual(run_command.call_count, 1) self.assertEqual(run_command.call_args_list[0][0][0], [ '/sbin/iptables', '-t', 'filter', '-C', 'OUTPUT', '-p', 'tcp', '--tcp-flags', 'ALL', 'ACK,RST,SYN,FIN', '-j', 'DROP' ])
def test_password_already_created_encrypt(self, mock_get_paths, mock_write_file): mock_get_paths.return_value = ['/path/one', '/path/two', '/path/three'] password.os.path.exists = lambda x: True with patch.object( builtins, 'open', mock_open(read_data=b'hunter42 salt=87654321\n')) as m: results = self.password_lookup.run( [u'/path/to/somewhere chars=anything encrypt=pbkdf2_sha256'], None) for result in results: self.assertEqual( result, u'$pbkdf2-sha256$20000$ODc2NTQzMjE$Uikde0cv0BKaRaAXMrUQB.zvG4GmnjClwjghwIRf2gU' )
def test_append_rule_check_mode(self): """Test append a redirection rule in check mode""" set_module_args({ 'chain': 'PREROUTING', 'source': '1.2.3.4/32', 'destination': '7.8.9.10/42', 'jump': 'REDIRECT', 'table': 'nat', 'to_destination': '5.5.5.5/32', 'protocol': 'udp', 'destination_port': '22', 'to_ports': '8600', '_ansible_check_mode': True, }) commands_results = [ (1, '', ''), ] with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.side_effect = commands_results with self.assertRaises(AnsibleExitJson) as result: iptables.main() self.assertTrue(result.exception.args[0]['changed']) self.assertEqual(run_command.call_count, 1) self.assertEqual(run_command.call_args_list[0][0][0], [ '/sbin/iptables', '-t', 'nat', '-C', 'PREROUTING', '-p', 'udp', '-s', '1.2.3.4/32', '-d', '7.8.9.10/42', '-j', 'REDIRECT', '--to-destination', '5.5.5.5/32', '--destination-port', '22', '--to-ports', '8600' ])
def test_dont_update_lambda_if_nothing_changed(): set_module_args(base_module_args) (boto3_conn_double, lambda_client_double) = make_mock_connection(base_lambda_config) with patch.object(lda, 'boto3_conn', boto3_conn_double): try: lda.main() except SystemExit: pass # guard against calling other than for a lambda connection (e.g. IAM) assert(len(boto3_conn_double.mock_calls) > 0), "boto connections never used" assert(len(boto3_conn_double.mock_calls) < 2), "multiple boto connections used unexpectedly" assert(len(lambda_client_double.update_function_configuration.mock_calls) == 0), \ "updated lambda function when no configuration changed" assert(len(lambda_client_double.update_function_code.mock_calls) == 0), \ "updated lambda code when no change should have happened"
def test_flush_table_without_chain(self): """Test flush without chain, flush the table""" set_module_args({ 'flush': True, }) with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.return_value = 0, '', '' # successful execution, no output with self.assertRaises(AnsibleExitJson) as result: iptables.main() self.assertTrue(result.exception.args[0]['changed']) self.assertEqual(run_command.call_count, 1) self.assertEqual(run_command.call_args[0][0][0], '/sbin/iptables') self.assertEqual(run_command.call_args[0][0][1], '-t') self.assertEqual(run_command.call_args[0][0][2], 'filter') self.assertEqual(run_command.call_args[0][0][3], '-F')
def test_modify_should_retry_state_failures(): params = { "port": 342, "force_password_update": True, "db_instance_identifier": "fakedb-too", # should exist "allocated_storage": 5, "storage_type": "gp", } rds_client_double = MagicMock() rds_client_double.describe_db_instances.return_value = describe_rds_new_return mod_db_fn = rds_client_double.modify_db_instance error_response = { 'Error': { 'Code': 'InvalidDBInstanceState', 'Message': 'Fake Testing Error' } } operation_name = 'FakeOperation' db_instance_not_available_error = ClientError(error_response, operation_name) mod_db_fn.side_effect = [ db_instance_not_available_error, modify_rds_return ] module_double = MagicMock(ansible_module_template) module_double.params = params instance = describe_rds_new_return['DBInstances'][0] with patch.object(time, 'sleep', sleeper_double): mod_return = rds_i.modify_db_instance(module_double, rds_client_double, instance) print("rds calls:\n" + str(rds_client_double.mock_calls)) print("module calls:\n" + str(module_double.mock_calls)) mod_db_fn.assert_called_with(DBInstanceIdentifier='fakedb-too', DBPortNumber=342, StorageType='gp') module_double.fail_json.assert_not_called() module_double.fail_json_aws.assert_not_called() assert mod_return["changed"], "modify failed to return changed"
def test_botocore_exception_reports_nicely_via_fail_json_aws(self): basic._ANSIBLE_ARGS = to_bytes( json.dumps({ 'ANSIBLE_MODULE_ARGS': { '_ansible_tmpdir': '/tmp/ansible-abc' } })) module = AnsibleAWSModule(argument_spec=dict( fail_mode=dict(type='list', default=['success']))) fail_json_double = Mock() err_msg = {'Error': {'Code': 'FakeClass.FakeError'}} with patch.object(basic.AnsibleModule, 'fail_json', fail_json_double): try: raise botocore.exceptions.ClientError(err_msg, 'Could not find you') except Exception as e: print("exception is " + str(e)) module.fail_json_aws( e, msg="Fake failure for testing boto exception messages") assert (len(fail_json_double.mock_calls) > 0), "failed to call fail_json when should have" assert (len(fail_json_double.mock_calls) < 2), "called fail_json multiple times when once would do" assert("test_botocore_exception_reports_nicely" in fail_json_double.mock_calls[0][2]["exception"]), \ "exception traceback doesn't include correct function, fail call was actually: " \ + str(fail_json_double.mock_calls[0]) assert("Fake failure for testing boto exception messages:" in fail_json_double.mock_calls[0][2]["msg"]), \ "error message doesn't include the local message; was: " \ + str(fail_json_double.mock_calls[0]) assert("Could not find you" in fail_json_double.mock_calls[0][2]["msg"]), \ "error message doesn't include the botocore exception message; was: " \ + str(fail_json_double.mock_calls[0]) try: fail_json_double.mock_calls[0][2]["error"] except KeyError: raise Exception("error was missing; call was: " + str(fail_json_double.mock_calls[0])) assert("FakeClass.FakeError" == fail_json_double.mock_calls[0][2]["error"]["code"]), \ "Failed to find error/code; was: " + str(fail_json_double.mock_calls[0])
def test_remove_rule(self): """Test flush without parameters""" set_module_args({ 'chain': 'PREROUTING', 'source': '1.2.3.4/32', 'destination': '7.8.9.10/42', 'jump': 'SNAT', 'table': 'nat', 'to_source': '5.5.5.5/32', 'protocol': 'udp', 'source_port': '22', 'to_ports': '8600', 'state': 'absent', 'in_interface': 'eth0', 'out_interface': 'eth1', 'comment': 'this is a comment' }) commands_results = [ (0, '', ''), (0, '', ''), ] with patch.object(basic.AnsibleModule, 'run_command') as run_command: run_command.side_effect = commands_results with self.assertRaises(AnsibleExitJson) as result: iptables.main() self.assertTrue(result.exception.args[0]['changed']) self.assertEqual(run_command.call_count, 2) self.assertEqual(run_command.call_args_list[0][0][0], [ '/sbin/iptables', '-t', 'nat', '-C', 'PREROUTING', '-p', 'udp', '-s', '1.2.3.4/32', '-d', '7.8.9.10/42', '-j', 'SNAT', '--to-source', '5.5.5.5/32', '-i', 'eth0', '-o', 'eth1', '--source-port', '22', '--to-ports', '8600', '-m', 'comment', '--comment', 'this is a comment' ]) self.assertEqual(run_command.call_args_list[1][0][0], [ '/sbin/iptables', '-t', 'nat', '-D', 'PREROUTING', '-p', 'udp', '-s', '1.2.3.4/32', '-d', '7.8.9.10/42', '-j', 'SNAT', '--to-source', '5.5.5.5/32', '-i', 'eth0', '-o', 'eth1', '--source-port', '22', '--to-ports', '8600', '-m', 'comment', '--comment', 'this is a comment' ])