def test_module_utils_basic_ansible_module_selinux_enabled(self): from ansible.module_utils import basic basic.MODULE_COMPLEX_ARGS = '{}' am = basic.AnsibleModule(argument_spec=dict(), ) # we first test the cases where the python selinux lib is # not installed, which has two paths: one in which the system # does have selinux installed (and the selinuxenabled command # is present and returns 0 when run), or selinux is not installed basic.HAVE_SELINUX = False am.get_bin_path = MagicMock() am.get_bin_path.return_value = '/path/to/selinuxenabled' am.run_command = MagicMock() am.run_command.return_value = (0, '', '') self.assertRaises(SystemExit, am.selinux_enabled) am.get_bin_path.return_value = None self.assertEqual(am.selinux_enabled(), False) # finally we test the case where the python selinux lib is installed, # and both possibilities there (enabled vs. disabled) basic.HAVE_SELINUX = True basic.selinux = Mock() with patch.dict('sys.modules', {'selinux': basic.selinux}): with patch('selinux.is_selinux_enabled', return_value=0): self.assertEqual(am.selinux_enabled(), False) with patch('selinux.is_selinux_enabled', return_value=1): self.assertEqual(am.selinux_enabled(), True) delattr(basic, 'selinux')
def setUpClass(cls): class MockException(Exception): pass cls.MockException = MockException m = MagicMock() nssrc_modules_mock = { 'nssrc.com.citrix.netscaler.nitro.resource.config.gslb': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbvserver': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbvserver.gslbvserver': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbvserver_gslbservice_binding': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbvserver_gslbservice_binding.gslbvserver_gslbservice_binding': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbvserver_domain_binding': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbvserver_domain_binding.gslbvserver_domain_binding': m, } cls.nitro_specific_patcher = patch.dict(sys.modules, nssrc_modules_mock) cls.nitro_base_patcher = nitro_base_patcher
def setUp(self): args = json.dumps(dict(ANSIBLE_MODULE_ARGS={})) # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually self.stdin_swap = swap_stdin_and_argv(stdin_data=args) self.stdin_swap.__enter__() ansible.module_utils.basic._ANSIBLE_ARGS = None self.am = ansible.module_utils.basic.AnsibleModule( argument_spec=dict(), ) self.am._name = 'unittest' self.has_journal = ansible.module_utils.basic.has_journal ansible.module_utils.basic.has_journal = True self.module_patcher = None # In case systemd-python is not installed if not self.has_journal: self.module_patcher = patch.dict('sys.modules', {'systemd': MagicMock(), 'systemd.journal': MagicMock()}) self.module_patcher.start() try: reload(ansible.module_utils.basic) except NameError: self._fake_out_reload(ansible.module_utils.basic)
def setUpClass(cls): class MockException(Exception): pass cls.MockException = MockException m = MagicMock() nssrc_modules_mock = { 'nssrc.com.citrix.netscaler.nitro.resource.config.gslb': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice.gslbservice': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice_lbmonitor_binding': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.gslb.gslbservice_lbmonitor_binding.gslbservice_lbmonitor_binding': m, # The following are needed because of monkey_patch_nitro_api() 'nssrc.com.citrix.netscaler.nitro.resource.base': m, 'nssrc.com.citrix.netscaler.nitro.resource.base.Json': m, 'nssrc.com.citrix.netscaler.nitro.resource.base.Json.Json': m, 'nssrc.com.citrix.netscaler.nitro.util': m, 'nssrc.com.citrix.netscaler.nitro.util.nitro_util': m, 'nssrc.com.citrix.netscaler.nitro.util.nitro_util.nitro_util': m, } cls.nitro_specific_patcher = patch.dict(sys.modules, nssrc_modules_mock) cls.nitro_base_patcher = nitro_base_patcher
def setUpClass(cls): class MockException(Exception): pass cls.MockException = MockException m = MagicMock() cls.cs_vserver_mock = MagicMock() cls.cs_vserver_mock.__class__ = MagicMock(add=Mock()) nssrc_modules_mock = { 'nssrc.com.citrix.netscaler.nitro.resource.config.cs': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.cs.csvserver': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.cs.csvserver.csvserver': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.cs.csvserver_cspolicy_binding': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.cs.csvserver_cspolicy_binding.csvserver_cspolicy_binding': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.ssl': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.ssl.sslvserver_sslcertkey_binding': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.ssl.sslvserver_sslcertkey_binding.sslvserver_sslcertkey_binding': m, } cls.nitro_specific_patcher = patch.dict(sys.modules, nssrc_modules_mock) cls.nitro_base_patcher = nitro_base_patcher
def test_module_utils_basic_ansible_module_selinux_default_context(self): from ansible.module_utils import basic basic.MODULE_COMPLEX_ARGS = '{}' am = basic.AnsibleModule( argument_spec = dict(), ) am.selinux_initial_context = MagicMock(return_value=[None, None, None, None]) am.selinux_enabled = MagicMock(return_value=True) # we first test the cases where the python selinux lib is not installed basic.HAVE_SELINUX = False self.assertEqual(am.selinux_default_context(path='/foo/bar'), [None, None, None, None]) # all following tests assume the python selinux bindings are installed basic.HAVE_SELINUX = True basic.selinux = Mock() with patch.dict('sys.modules', {'selinux': basic.selinux}): # next, we test with a mocked implementation of selinux.matchpathcon to simulate # an actual context being found with patch('selinux.matchpathcon', return_value=[0, 'unconfined_u:object_r:default_t:s0']): self.assertEqual(am.selinux_default_context(path='/foo/bar'), ['unconfined_u', 'object_r', 'default_t', 's0']) # we also test the case where matchpathcon returned a failure with patch('selinux.matchpathcon', return_value=[-1, '']): self.assertEqual(am.selinux_default_context(path='/foo/bar'), [None, None, None, None]) # finally, we test where an OSError occurred during matchpathcon's call with patch('selinux.matchpathcon', side_effect=OSError): self.assertEqual(am.selinux_default_context(path='/foo/bar'), [None, None, None, None]) delattr(basic, 'selinux')
def test_module_utils_basic_ansible_module_selinux_enabled(self): from ansible.module_utils import basic basic.MODULE_COMPLEX_ARGS = '{}' am = basic.AnsibleModule( argument_spec = dict(), ) # we first test the cases where the python selinux lib is # not installed, which has two paths: one in which the system # does have selinux installed (and the selinuxenabled command # is present and returns 0 when run), or selinux is not installed basic.HAVE_SELINUX = False am.get_bin_path = MagicMock() am.get_bin_path.return_value = '/path/to/selinuxenabled' am.run_command = MagicMock() am.run_command.return_value=(0, '', '') self.assertRaises(SystemExit, am.selinux_enabled) am.get_bin_path.return_value = None self.assertEqual(am.selinux_enabled(), False) # finally we test the case where the python selinux lib is installed, # and both possibilities there (enabled vs. disabled) basic.HAVE_SELINUX = True basic.selinux = Mock() with patch.dict('sys.modules', {'selinux': basic.selinux}): with patch('selinux.is_selinux_enabled', return_value=0): self.assertEqual(am.selinux_enabled(), False) with patch('selinux.is_selinux_enabled', return_value=1): self.assertEqual(am.selinux_enabled(), True) delattr(basic, 'selinux')
def setUpClass(cls): m = MagicMock() cls.service_mock = MagicMock() cls.service_mock.__class__ = MagicMock() cls.service_lbmonitor_binding_mock = MagicMock() cls.lbmonitor_service_binding_mock = MagicMock() nssrc_modules_mock = { 'nssrc.com.citrix.netscaler.nitro.resource.config.basic': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.basic.service': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.basic.service.service': cls.service_mock, 'nssrc.com.citrix.netscaler.nitro.resource.config.basic.service_lbmonitor_binding': cls.service_lbmonitor_binding_mock, 'nssrc.com.citrix.netscaler.nitro.resource.config.basic.service_lbmonitor_binding.service_lbmonitor_binding': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.lb': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.lb.lbmonitor_service_binding': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.lb.lbmonitor_service_binding.lbmonitor_service_binding': cls.lbmonitor_service_binding_mock, } cls.nitro_specific_patcher = patch.dict(sys.modules, nssrc_modules_mock) cls.nitro_base_patcher = nitro_base_patcher
def setUp(self): args = json.dumps( dict(ANSIBLE_MODULE_ARGS={}, ANSIBLE_MODULE_CONSTANTS={})) self.real_stdin = sys.stdin if PY3: sys.stdin = StringIO(args) sys.stdin.buffer = BytesIO(to_bytes(args)) else: sys.stdin = BytesIO(to_bytes(args)) self.am = basic.AnsibleModule(argument_spec=dict(), ) self.has_journal = basic.has_journal basic.has_journal = True self.module_patcher = None # In case systemd-python is not installed if not self.has_journal: self.module_patcher = patch.dict('sys.modules', { 'systemd': MagicMock(), 'systemd.journal': MagicMock() }) self.module_patcher.start() try: reload(basic) except NameError: self._fake_out_reload(basic)
def setUpClass(cls): class MockException(Exception): pass cls.MockException = MockException m = MagicMock() cls.servicegroup_mock = MagicMock() cls.servicegroup_mock.__class__ = MagicMock() nssrc_modules_mock = { 'nssrc.com.citrix.netscaler.nitro.resource.config.basic': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.basic.servicegroup': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.basic.servicegroup.servicegroup': cls.servicegroup_mock, 'nssrc.com.citrix.netscaler.nitro.resource.config.basic.servicegroup_servicegroupmember_binding': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.basic.servicegroup_servicegroupmember_binding.servicegroup_servicegroupmember_binding': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.basic.servicegroup_lbmonitor_binding': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.basic.servicegroup_lbmonitor_binding.servicegroup_lbmonitor_binding': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.lb': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.lb.lbmonitor_servicegroup_binding': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.lb.lbmonitor_servicegroup_binding.lbmonitor_servicegroup_binding': m } cls.nitro_specific_patcher = patch.dict(sys.modules, nssrc_modules_mock) cls.nitro_base_patcher = nitro_base_patcher
def test_validate_runnable_exists(self, *args): with patch.dict( 'sys.modules', **{ 'vdirect_client': self.module_mock, 'vdirect_client.rest_client': self.module_mock, }): from ansible.modules.network.radware import vdirect_runnable Runnable.set_runnable_objects_result(RUNNABLE_OBJECTS_RESULT) BASE_PARAMS.update(RUNNABLE_PARAMS) vdirectRunnable = vdirect_runnable.VdirectRunnable(BASE_PARAMS) vdirectRunnable.client.runnable = Runnable(vdirectRunnable.client) vdirectRunnable._validate_runnable_exists() assert True BASE_PARAMS.update(RUNNABLE_PARAMS) BASE_PARAMS['runnable_name'] = "missing" vdirectRunnable = vdirect_runnable.VdirectRunnable(BASE_PARAMS) vdirectRunnable.client.runnable = Runnable(vdirectRunnable.client) try: vdirectRunnable._validate_runnable_exists() self.fail( "MissingRunnableException was not thrown for missing runnable name" ) except vdirect_runnable.MissingRunnableException: assert True
def test_set_options(self, play, options, direct, expected, kerb): if kerb: kerberos_mock = MagicMock() modules = {'kerberos': kerberos_mock} else: modules = {'kerberos': None} module_patcher = patch.dict(sys.modules, modules) module_patcher.start() pc = PlayContext() for attr, value in play.items(): setattr(pc, attr, value) new_stdin = StringIO() # ensure we get a fresh connection plugin by clearing the cache connection_loader._module_cache = {} conn = connection_loader.get('winrm', pc, new_stdin) conn.set_options(var_options=options, direct=direct) for attr, expected in expected.items(): actual = getattr(conn, attr) assert actual == expected, \ "winrm attr '%s', actual '%s' != expected '%s'"\ % (attr, actual, expected) module_patcher.stop()
def test_kinit_with_missing_executable(self, use_pexpect): expected_err = "[Errno 2] No such file or directory: " \ "'/fake/kinit': '/fake/kinit'" mock_subprocess = MagicMock() mock_subprocess.Popen = MagicMock(side_effect=OSError(expected_err)) mock_pexpect = None if use_pexpect: expected_err = "The command was not found or was not " \ "executable: /fake/kinit" mock_pexpect = MagicMock() mock_pexpect.ExceptionPexpect = Exception mock_pexpect.spawn = MagicMock(side_effect=Exception(expected_err)) modules = { 'pexpect': mock_pexpect, 'subprocess': mock_subprocess, } with patch.dict(sys.modules, modules): pc = PlayContext() new_stdin = StringIO() connection_loader._module_cache = {} conn = connection_loader.get('winrm', pc, new_stdin) options = {"_extras": {}, "ansible_winrm_kinit_cmd": "/fake/kinit"} conn.set_options(var_options=options) with pytest.raises(AnsibleConnectionFailure) as err: conn._kerb_auth("user@domain", "pass") assert str(err.value) == "Kerberos auth failure when calling " \ "kinit cmd '/fake/kinit': %s" % expected_err
def test_validate_action_name(self, *args): with patch.dict('sys.modules', **{ 'vdirect_client': self.module_mock, 'vdirect_client.rest_client': self.module_mock, }): from ansible.modules.network.radware import vdirect_runnable Runnable.set_runnable_objects_result(RUNNABLE_OBJECTS_RESULT) BASE_PARAMS.update(RUNNABLE_PARAMS) vdirectRunnable = vdirect_runnable.VdirectRunnable(BASE_PARAMS) vdirectRunnable._validate_action_name() assert vdirectRunnable.action_name == vdirect_runnable.VdirectRunnable.RUN_ACTION BASE_PARAMS['runnable_type'] = vdirect_runnable.WORKFLOW_TEMPLATE_RUNNABLE_TYPE vdirectRunnable = vdirect_runnable.VdirectRunnable(BASE_PARAMS) vdirectRunnable._validate_action_name() assert vdirectRunnable.action_name == vdirect_runnable.VdirectRunnable.CREATE_WORKFLOW_ACTION BASE_PARAMS['runnable_type'] = vdirect_runnable.WORKFLOW_RUNNABLE_TYPE BASE_PARAMS['action_name'] = 'a' vdirectRunnable = vdirect_runnable.VdirectRunnable(BASE_PARAMS) vdirectRunnable.client.runnable = Runnable(vdirectRunnable.client) Runnable.set_available_actions_result(AVAILABLE_ACTIONS_RESULT) vdirectRunnable._validate_action_name() assert vdirectRunnable.action_name == 'a' BASE_PARAMS['action_name'] = 'c' vdirectRunnable = vdirect_runnable.VdirectRunnable(BASE_PARAMS) vdirectRunnable.client.runnable = Runnable(vdirectRunnable.client) Runnable.set_available_actions_result(AVAILABLE_ACTIONS_RESULT) try: vdirectRunnable._validate_action_name() self.fail("WrongActionNameException was not thrown for wrong action name") except vdirect_runnable.WrongActionNameException: assert True
def test_module_utils_basic_ansible_module_selinux_default_context(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule( argument_spec = dict(), ) am.selinux_initial_context = MagicMock(return_value=[None, None, None, None]) am.selinux_enabled = MagicMock(return_value=True) # we first test the cases where the python selinux lib is not installed basic.HAVE_SELINUX = False self.assertEqual(am.selinux_default_context(path='/foo/bar'), [None, None, None, None]) # all following tests assume the python selinux bindings are installed basic.HAVE_SELINUX = True basic.selinux = Mock() with patch.dict('sys.modules', {'selinux': basic.selinux}): # next, we test with a mocked implementation of selinux.matchpathcon to simulate # an actual context being found with patch('selinux.matchpathcon', return_value=[0, 'unconfined_u:object_r:default_t:s0']): self.assertEqual(am.selinux_default_context(path='/foo/bar'), ['unconfined_u', 'object_r', 'default_t', 's0']) # we also test the case where matchpathcon returned a failure with patch('selinux.matchpathcon', return_value=[-1, '']): self.assertEqual(am.selinux_default_context(path='/foo/bar'), [None, None, None, None]) # finally, we test where an OSError occurred during matchpathcon's call with patch('selinux.matchpathcon', side_effect=OSError): self.assertEqual(am.selinux_default_context(path='/foo/bar'), [None, None, None, None]) delattr(basic, 'selinux')
def setUp(self): args = json.dumps(dict(ANSIBLE_MODULE_ARGS={})) # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually self.stdin_swap = swap_stdin_and_argv(stdin_data=args) self.stdin_swap.__enter__() ansible.module_utils.basic._ANSIBLE_ARGS = None self.am = ansible.module_utils.basic.AnsibleModule( argument_spec=dict(), ) self.has_journal = ansible.module_utils.basic.has_journal ansible.module_utils.basic.has_journal = True self.module_patcher = None # In case systemd-python is not installed if not self.has_journal: self.module_patcher = patch.dict('sys.modules', { 'systemd': MagicMock(), 'systemd.journal': MagicMock() }) self.module_patcher.start() try: reload(ansible.module_utils.basic) except NameError: self._fake_out_reload(ansible.module_utils.basic)
def setUpClass(cls): class MockException(Exception): pass cls.MockException = MockException m = MagicMock() nssrc_modules_mock = { 'nssrc.com.citrix.netscaler.nitro.resource.config.cs': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.cs.cspolicy': m, } cls.nitro_specific_patcher = patch.dict(sys.modules, nssrc_modules_mock) cls.nitro_base_patcher = nitro_base_patcher
def test_module_utils_basic_ansible_module_set_context_if_different(self): from ansible.module_utils import basic basic.MODULE_COMPLEX_ARGS = "{}" am = basic.AnsibleModule(argument_spec=dict()) basic.HAS_SELINUX = False am.selinux_enabled = MagicMock(return_value=False) self.assertEqual(am.set_context_if_different("/path/to/file", ["foo_u", "foo_r", "foo_t", "s0"], True), True) self.assertEqual(am.set_context_if_different("/path/to/file", ["foo_u", "foo_r", "foo_t", "s0"], False), False) basic.HAS_SELINUX = True am.selinux_enabled = MagicMock(return_value=True) am.selinux_context = MagicMock(return_value=["bar_u", "bar_r", None, None]) am.is_special_selinux_path = MagicMock(return_value=(False, None)) basic.selinux = Mock() with patch.dict("sys.modules", {"selinux": basic.selinux}): with patch("selinux.lsetfilecon", return_value=0) as m: self.assertEqual( am.set_context_if_different("/path/to/file", ["foo_u", "foo_r", "foo_t", "s0"], False), True ) m.assert_called_with("/path/to/file", "foo_u:foo_r:foo_t:s0") m.reset_mock() am.check_mode = True self.assertEqual( am.set_context_if_different("/path/to/file", ["foo_u", "foo_r", "foo_t", "s0"], False), True ) self.assertEqual(m.called, False) am.check_mode = False with patch("selinux.lsetfilecon", return_value=1) as m: self.assertRaises( SystemExit, am.set_context_if_different, "/path/to/file", ["foo_u", "foo_r", "foo_t", "s0"], True ) with patch("selinux.lsetfilecon", side_effect=OSError) as m: self.assertRaises( SystemExit, am.set_context_if_different, "/path/to/file", ["foo_u", "foo_r", "foo_t", "s0"], True ) am.is_special_selinux_path = MagicMock(return_value=(True, ["sp_u", "sp_r", "sp_t", "s0"])) with patch("selinux.lsetfilecon", return_value=0) as m: self.assertEqual( am.set_context_if_different("/path/to/file", ["foo_u", "foo_r", "foo_t", "s0"], False), True ) m.assert_called_with("/path/to/file", "sp_u:sp_r:sp_t:s0") delattr(basic, "selinux")
def test_missing_parameter(self, *args): with patch.dict('sys.modules', **{ 'vdirect_client': self.module_mock, 'vdirect_client.rest_client': self.module_mock, }): from ansible.modules.network.radware import vdirect_runnable try: params = BASE_PARAMS.copy() vdirect_runnable.VdirectRunnable(params) self.fail("KeyError was not thrown for missing parameter") except KeyError: assert True
def test_missing_parameter(self, *args): with patch.dict('sys.modules', **{ 'vdirect_client': self.module_mock, 'vdirect_client.rest_client.RestClient': self.module_mock, }): from ansible.modules.network.radware import vdirect_commit try: params = BASE_PARAMS.copy() vdirect_commit.VdirectCommit(params) self.fail("KeyError was not thrown for missing parameter") except KeyError: assert True
def test_module_utils_basic_ansible_module_selinux_mls_enabled(self): from ansible.module_utils import basic am = basic.AnsibleModule(argument_spec=dict(), ) basic.HAVE_SELINUX = False self.assertEqual(am.selinux_mls_enabled(), False) basic.HAVE_SELINUX = True basic.selinux = Mock() with patch.dict('sys.modules', {'selinux': basic.selinux}): with patch('selinux.is_selinux_mls_enabled', return_value=0): self.assertEqual(am.selinux_mls_enabled(), False) with patch('selinux.is_selinux_mls_enabled', return_value=1): self.assertEqual(am.selinux_mls_enabled(), True) delattr(basic, 'selinux')
def test_module_utils_basic_ansible_module_selinux_mls_enabled(self): from ansible.module_utils import basic basic.MODULE_COMPLEX_ARGS = "{}" am = basic.AnsibleModule(argument_spec=dict()) basic.HAVE_SELINUX = False self.assertEqual(am.selinux_mls_enabled(), False) basic.HAVE_SELINUX = True basic.selinux = Mock() with patch.dict("sys.modules", {"selinux": basic.selinux}): with patch("selinux.is_selinux_mls_enabled", return_value=0): self.assertEqual(am.selinux_mls_enabled(), False) with patch("selinux.is_selinux_mls_enabled", return_value=1): self.assertEqual(am.selinux_mls_enabled(), True) delattr(basic, "selinux")
def setUpClass(cls): class MockException(Exception): pass cls.MockException = MockException m = MagicMock() cls.server_mock = MagicMock() cls.server_mock.__class__ = MagicMock(add=Mock()) nssrc_modules_mock = { 'nssrc.com.citrix.netscaler.nitro.resource.config.ssl': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.ssl.sslcertkey': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.ssl.sslcertkey.sslcertkey': m, } cls.nitro_specific_patcher = patch.dict(sys.modules, nssrc_modules_mock) cls.nitro_base_patcher = nitro_base_patcher
def test_validate_required_action_params(self, *args): with patch.dict( 'sys.modules', **{ 'vdirect_client': self.module_mock, 'vdirect_client.rest_client': self.module_mock, }): from ansible.modules.network.radware import vdirect_runnable Runnable.set_runnable_objects_result(RUNNABLE_OBJECTS_RESULT) BASE_PARAMS.update(RUNNABLE_PARAMS) BASE_PARAMS[ 'runnable_type'] = vdirect_runnable.WORKFLOW_RUNNABLE_TYPE BASE_PARAMS['action_name'] = 'a' BASE_PARAMS['parameters'] = {"alteon": "x"} vdirectRunnable = vdirect_runnable.VdirectRunnable(BASE_PARAMS) vdirectRunnable.client.runnable = Runnable(vdirectRunnable.client) Runnable.set_available_actions_result(AVAILABLE_ACTIONS_RESULT) Runnable.set_action_info_result(ACTIONS_PARAMS_RESULT) vdirectRunnable._validate_action_name() try: vdirectRunnable._validate_required_action_params() self.fail( "MissingActionParametersException was not thrown for missing parameters" ) except vdirect_runnable.MissingActionParametersException: assert True BASE_PARAMS['parameters'] = {"alteon": "x"} vdirectRunnable = vdirect_runnable.VdirectRunnable(BASE_PARAMS) vdirectRunnable._validate_action_name() try: vdirectRunnable._validate_required_action_params() self.fail( "MissingActionParametersException was not thrown for missing parameters" ) except vdirect_runnable.MissingActionParametersException: assert True BASE_PARAMS['parameters'] = {"pin": "x", "alteon": "x"} vdirectRunnable = vdirect_runnable.VdirectRunnable(BASE_PARAMS) vdirectRunnable._validate_action_name() vdirectRunnable._validate_required_action_params() assert True
def test_module_utils_basic_ansible_module_set_context_if_different(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule( argument_spec = dict(), ) basic.HAVE_SELINUX = False am.selinux_enabled = MagicMock(return_value=False) self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], True), True) self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), False) basic.HAVE_SELINUX = True am.selinux_enabled = MagicMock(return_value=True) am.selinux_context = MagicMock(return_value=['bar_u', 'bar_r', None, None]) am.is_special_selinux_path = MagicMock(return_value=(False, None)) basic.selinux = Mock() with patch.dict('sys.modules', {'selinux': basic.selinux}): with patch('selinux.lsetfilecon', return_value=0) as m: self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), True) m.assert_called_with(b'/path/to/file', 'foo_u:foo_r:foo_t:s0') m.reset_mock() am.check_mode = True self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), True) self.assertEqual(m.called, False) am.check_mode = False with patch('selinux.lsetfilecon', return_value=1) as m: self.assertRaises(SystemExit, am.set_context_if_different, '/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], True) with patch('selinux.lsetfilecon', side_effect=OSError) as m: self.assertRaises(SystemExit, am.set_context_if_different, '/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], True) am.is_special_selinux_path = MagicMock(return_value=(True, ['sp_u', 'sp_r', 'sp_t', 's0'])) with patch('selinux.lsetfilecon', return_value=0) as m: self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), True) m.assert_called_with(b'/path/to/file', 'sp_u:sp_r:sp_t:s0') delattr(basic, 'selinux')
def test_commit(self, *args): with patch.dict('sys.modules', **{ 'vdirect_client': self.module_mock, 'vdirect_client.rest_client.RestClient': self.module_mock, }): from ansible.modules.network.radware import vdirect_commit BASE_PARAMS.update(COMMIT_PARAMS) vdirectcommit = vdirect_commit.VdirectCommit(BASE_PARAMS) vdirectcommit.client.adc = DeviceMock('adc', vdirectcommit.client) vdirectcommit.client.container = DeviceMock('vx', vdirectcommit.client) vdirectcommit.client.appWall = DeviceMock('appwall', vdirectcommit.client) vdirectcommit.client.defensePro = DeviceMock('defensepro', vdirectcommit.client) res = vdirectcommit.commit() assert res == MODULE_RESULT vdirectcommit.sync = False for detail in MODULE_RESULT['details']: if 'sync' in detail: detail['sync'] = vdirect_commit.NOT_PERFORMED res = vdirectcommit.commit() assert res == MODULE_RESULT vdirectcommit.client.adc.control_result = COMMIT_RESULT_204 vdirectcommit.client.adc.control_result[self.module_mock.rest_client.RESP_STATUS] = 500 vdirectcommit.client.adc.control_result[self.module_mock.rest_client.RESP_STR] = 'Some Failure' MODULE_RESULT['msg'] = 'Failure occurred while performing requested actions on devices. See details' for detail in MODULE_RESULT['details']: if detail['device_name'] == 'adc': detail['apply'] = vdirect_commit.FAILED detail['failure_description'] = 'Some Failure' detail['save'] = vdirect_commit.NOT_PERFORMED detail['sync'] = vdirect_commit.NOT_PERFORMED res = vdirectcommit.commit() assert res == MODULE_RESULT vdirectcommit.client.adc.throw_exception(control_throw=True) for detail in MODULE_RESULT['details']: if detail['device_name'] == 'adc': detail['failure_description'] = 'Exception occurred while performing apply action. ' \ 'Exception: exception message' res = vdirectcommit.commit() assert res == MODULE_RESULT
def test_module_utils_basic_ansible_module_set_context_if_different(self): from ansible.module_utils import basic basic.MODULE_COMPLEX_ARGS = '{}' am = basic.AnsibleModule( argument_spec = dict(), ) basic.HAS_SELINUX = False am.selinux_enabled = MagicMock(return_value=False) self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], True), True) self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), False) basic.HAS_SELINUX = True am.selinux_enabled = MagicMock(return_value=True) am.selinux_context = MagicMock(return_value=['bar_u', 'bar_r', None, None]) am.is_special_selinux_path = MagicMock(return_value=(False, None)) basic.selinux = Mock() with patch.dict('sys.modules', {'selinux': basic.selinux}): with patch('selinux.lsetfilecon', return_value=0) as m: self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), True) m.assert_called_with(b'/path/to/file', 'foo_u:foo_r:foo_t:s0') m.reset_mock() am.check_mode = True self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), True) self.assertEqual(m.called, False) am.check_mode = False with patch('selinux.lsetfilecon', return_value=1) as m: self.assertRaises(SystemExit, am.set_context_if_different, '/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], True) with patch('selinux.lsetfilecon', side_effect=OSError) as m: self.assertRaises(SystemExit, am.set_context_if_different, '/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], True) am.is_special_selinux_path = MagicMock(return_value=(True, ['sp_u', 'sp_r', 'sp_t', 's0'])) with patch('selinux.lsetfilecon', return_value=0) as m: self.assertEqual(am.set_context_if_different('/path/to/file', ['foo_u', 'foo_r', 'foo_t', 's0'], False), True) m.assert_called_with(b'/path/to/file', 'sp_u:sp_r:sp_t:s0') delattr(basic, 'selinux')
def setUp(self): self.complex_args_token = basic.MODULE_COMPLEX_ARGS basic.MODULE_COMPLEX_ARGS = '{}' self.am = basic.AnsibleModule( argument_spec = dict(), ) self.has_journal = basic.has_journal basic.has_journal = True self.module_patcher = None # In case systemd-python is not installed if not self.has_journal: self.module_patcher = patch.dict('sys.modules', {'systemd': MagicMock(), 'systemd.journal': MagicMock()}) self.module_patcher.start() try: reload(basic) except NameError: self._fake_out_reload(basic)
def test_module_utils_basic_ansible_module_selinux_mls_enabled(self): from ansible.module_utils import basic reload(basic) am = basic.AnsibleModule( argument_spec = dict(), ) basic.HAVE_SELINUX = False self.assertEqual(am.selinux_mls_enabled(), False) basic.HAVE_SELINUX = True basic.selinux = Mock() with patch.dict('sys.modules', {'selinux': basic.selinux}): with patch('selinux.is_selinux_mls_enabled', return_value=0): self.assertEqual(am.selinux_mls_enabled(), False) with patch('selinux.is_selinux_mls_enabled', return_value=1): self.assertEqual(am.selinux_mls_enabled(), True) delattr(basic, 'selinux')
def test_kinit_error(self, use_pexpect): mechanism = "subprocess" expected_err = "kinit: krb5_parse_name: " \ "Configuration file does not specify default realm" def mock_popen_communicate(input=None, timeout=None): return b"", to_bytes(expected_err) mock_subprocess = MagicMock() mock_subprocess.Popen.return_value.communicate = mock_popen_communicate mock_subprocess.Popen.return_value.returncode = 1 mock_pexpect = None if use_pexpect: mechanism = "pexpect" expected_err = "Configuration file does not specify default realm" mock_pexpect = MagicMock() mock_pexpect.spawn.return_value.expect = MagicMock( side_effect=OSError) mock_pexpect.spawn.return_value.read.return_value = to_bytes( expected_err) mock_pexpect.spawn.return_value.exitstatus = 1 modules = { 'pexpect': mock_pexpect, 'subprocess': mock_subprocess, } with patch.dict(sys.modules, modules): pc = PlayContext() new_stdin = StringIO() connection_loader._module_cache = {} conn = connection_loader.get('winrm', pc, new_stdin) conn.set_options(var_options={"_extras": {}}) with pytest.raises(AnsibleConnectionFailure) as err: conn._kerb_auth("invaliduser", "pass") assert str(err.value) == "Kerberos auth failure for principal " \ "invaliduser with %s: %s" % (mechanism, expected_err)
def setUpClass(cls): class MockException(Exception): pass cls.MockException = MockException m = MagicMock() cls.server_mock = MagicMock() cls.server_mock.__class__ = MagicMock(add=Mock()) nssrc_modules_mock = { 'nssrc.com.citrix.netscaler.nitro.resource.config.basic': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.basic.server': m, 'nssrc.com.citrix.netscaler.nitro.resource.config.basic.server.server': cls.server_mock, } cls.nitro_specific_patcher = patch.dict(sys.modules, nssrc_modules_mock) cls.nitro_base_patcher = nitro_base_patcher
def test_validate_devices(self, *args): with patch.dict('sys.modules', **{ 'vdirect_client': self.module_mock, 'vdirect_client.rest_client.RestClient': self.module_mock, }): from ansible.modules.network.radware import vdirect_commit BASE_PARAMS.update(COMMIT_PARAMS) vdirectcommit = vdirect_commit.VdirectCommit(BASE_PARAMS) vdirectcommit.client.adc = DeviceMock('adc', vdirectcommit.client) vdirectcommit.client.container = DeviceMock('vx', vdirectcommit.client) vdirectcommit.client.appWall = DeviceMock('appwall', vdirectcommit.client) vdirectcommit.client.defensePro = DeviceMock('defensepro', vdirectcommit.client) vdirectcommit._validate_devices() assert True vdirectcommit.client.adc.throw_exception(True) try: vdirectcommit._validate_devices() self.fail("CommitException was not thrown for device communication failure") except vdirect_commit.CommitException: assert True vdirectcommit.client.adc.throw_exception(False) vdirectcommit.client.defensePro.throw_exception(True) try: vdirectcommit._validate_devices() self.fail("CommitException was not thrown for device communication failure") except vdirect_commit.CommitException: assert True vdirectcommit.client.defensePro.throw_exception(False) vdirectcommit.client.adc.name = 'wrong' try: vdirectcommit._validate_devices() self.fail("MissingDeviceException was not thrown for missing device") except vdirect_commit.MissingDeviceException: assert True
def test_module_utils_basic_ansible_module_selinux_context(self): from ansible.module_utils import basic basic.MODULE_COMPLEX_ARGS = "{}" am = basic.AnsibleModule(argument_spec=dict()) am.selinux_initial_context = MagicMock(return_value=[None, None, None, None]) am.selinux_enabled = MagicMock(return_value=True) # we first test the cases where the python selinux lib is not installed basic.HAVE_SELINUX = False self.assertEqual(am.selinux_context(path="/foo/bar"), [None, None, None, None]) # all following tests assume the python selinux bindings are installed basic.HAVE_SELINUX = True basic.selinux = Mock() with patch.dict("sys.modules", {"selinux": basic.selinux}): # next, we test with a mocked implementation of selinux.lgetfilecon_raw to simulate # an actual context being found with patch("selinux.lgetfilecon_raw", return_value=[0, "unconfined_u:object_r:default_t:s0"]): self.assertEqual(am.selinux_context(path="/foo/bar"), ["unconfined_u", "object_r", "default_t", "s0"]) # we also test the case where matchpathcon returned a failure with patch("selinux.lgetfilecon_raw", return_value=[-1, ""]): self.assertEqual(am.selinux_context(path="/foo/bar"), [None, None, None, None]) # finally, we test where an OSError occurred during matchpathcon's call e = OSError() e.errno = errno.ENOENT with patch("selinux.lgetfilecon_raw", side_effect=e): self.assertRaises(SystemExit, am.selinux_context, path="/foo/bar") e = OSError() with patch("selinux.lgetfilecon_raw", side_effect=e): self.assertRaises(SystemExit, am.selinux_context, path="/foo/bar") delattr(basic, "selinux")
def test_kinit_success(self, options, expected, pexpect): def mock_popen_communicate(input=None, timeout=None): return b"", b"" mock_pexpect = None if pexpect: mock_pexpect = MagicMock() mock_pexpect.spawn.return_value.exitstatus = 0 mock_subprocess = MagicMock() mock_subprocess.Popen.return_value.communicate = mock_popen_communicate mock_subprocess.Popen.return_value.returncode = 0 modules = { 'pexpect': mock_pexpect, 'subprocess': mock_subprocess, } with patch.dict(sys.modules, modules): pc = PlayContext() new_stdin = StringIO() connection_loader._module_cache = {} conn = connection_loader.get('winrm', pc, new_stdin) conn.set_options(var_options=options) conn._kerb_auth("user@domain", "pass") if pexpect: assert len(mock_pexpect.method_calls) == 1 assert mock_pexpect.method_calls[0][1] == expected actual_env = mock_pexpect.method_calls[0][2]['env'] else: assert len(mock_subprocess.method_calls) == 1 assert mock_subprocess.method_calls[0][1] == expected actual_env = mock_subprocess.method_calls[0][2]['env'] assert list(actual_env.keys()) == ['KRB5CCNAME'] assert actual_env['KRB5CCNAME'].startswith("FILE:/")
base_modules_mock, 'nssrc.com.citrix.netscaler.nitro.exception': base_modules_mock, 'nssrc.com.citrix.netscaler.nitro.exception.nitro_exception': base_modules_mock, 'nssrc.com.citrix.netscaler.nitro.exception.nitro_exception.nitro_exception': nitro_exception_mock, 'nssrc.com.citrix.netscaler.nitro.service': base_modules_mock, 'nssrc.com.citrix.netscaler.nitro.service.nitro_service': base_modules_mock, 'nssrc.com.citrix.netscaler.nitro.service.nitro_service.nitro_service': nitro_service_mock, } nitro_base_patcher = patch.dict(sys.modules, base_modules_to_mock) class TestModule(ModuleTestCase): def failed(self): with self.assertRaises(AnsibleFailJson) as exc: self.module.main() result = exc.exception.args[0] self.assertTrue(result['failed'], result) return result def exited(self, changed=False): with self.assertRaises(AnsibleExitJson) as exc: self.module.main()
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.compat.tests.mock import patch, MagicMock from units.modules.utils import set_module_args from .junos_module import TestJunosModule jnpr_mock = MagicMock() modules = { 'jnpr': jnpr_mock, 'jnpr.junos': jnpr_mock.junos, 'jnpr.junos.utils': jnpr_mock.junos.utils, 'jnpr.junos.utils.sw': jnpr_mock.junos.utils.sw, 'jnpr.junos.exception': jnpr_mock.junos.execption } module_patcher = patch.dict('sys.modules', modules) module_patcher.start() from ansible.modules.network.junos import junos_package class TestJunosCommandModule(TestJunosModule): module = junos_package def setUp(self): super(TestJunosCommandModule, self).setUp() def tearDown(self): super(TestJunosCommandModule, self).tearDown()
'nssrc': base_modules_mock, 'nssrc.com': base_modules_mock, 'nssrc.com.citrix': base_modules_mock, 'nssrc.com.citrix.netscaler': base_modules_mock, 'nssrc.com.citrix.netscaler.nitro': base_modules_mock, 'nssrc.com.citrix.netscaler.nitro.resource': base_modules_mock, 'nssrc.com.citrix.netscaler.nitro.resource.config': base_modules_mock, 'nssrc.com.citrix.netscaler.nitro.exception': base_modules_mock, 'nssrc.com.citrix.netscaler.nitro.exception.nitro_exception': base_modules_mock, 'nssrc.com.citrix.netscaler.nitro.exception.nitro_exception.nitro_exception': nitro_exception_mock, 'nssrc.com.citrix.netscaler.nitro.service': base_modules_mock, 'nssrc.com.citrix.netscaler.nitro.service.nitro_service': base_modules_mock, 'nssrc.com.citrix.netscaler.nitro.service.nitro_service.nitro_service': nitro_service_mock, } nitro_base_patcher = patch.dict(sys.modules, base_modules_to_mock) class TestModule(ModuleTestCase): def failed(self): with self.assertRaises(AnsibleFailJson) as exc: self.module.main() result = exc.exception.args[0] self.assertTrue(result['failed'], result) return result def exited(self, changed=False): with self.assertRaises(AnsibleExitJson) as exc: self.module.main()
def test_run(self, *args): with patch.dict( 'sys.modules', **{ 'vdirect_client': self.module_mock, 'vdirect_client.rest_client': self.module_mock, }): from ansible.modules.network.radware import vdirect_runnable Runnable.set_runnable_objects_result(RUNNABLE_OBJECTS_RESULT) BASE_PARAMS.update(RUNNABLE_PARAMS) BASE_PARAMS[ 'runnable_type'] = vdirect_runnable.CONFIGURATION_TEMPLATE_RUNNABLE_TYPE BASE_PARAMS['parameters'] = {"pin": "x", "alteon": "x"} vdirectRunnable = vdirect_runnable.VdirectRunnable(BASE_PARAMS) vdirectRunnable.client.runnable = Runnable(vdirectRunnable.client) Runnable.set_available_actions_result(AVAILABLE_ACTIONS_RESULT) Runnable.set_action_info_result(ACTIONS_PARAMS_RESULT) Runnable.set_run_result(RUN_RESULT) res = vdirectRunnable.run() assert res == MODULE_RESULT BASE_PARAMS[ 'runnable_type'] = vdirect_runnable.WORKFLOW_TEMPLATE_RUNNABLE_TYPE MODULE_RESULT['msg'] = "Workflow created." vdirectRunnable = vdirect_runnable.VdirectRunnable(BASE_PARAMS) vdirectRunnable.client.runnable = Runnable(vdirectRunnable.client) res = vdirectRunnable.run() assert res == MODULE_RESULT BASE_PARAMS[ 'runnable_type'] = vdirect_runnable.WORKFLOW_RUNNABLE_TYPE BASE_PARAMS['action_name'] = 'a' MODULE_RESULT['msg'] = "Workflow action run completed." vdirectRunnable = vdirect_runnable.VdirectRunnable(BASE_PARAMS) vdirectRunnable.client.runnable = Runnable(vdirectRunnable.client) Runnable.set_available_actions_result(AVAILABLE_ACTIONS_RESULT) Runnable.set_action_info_result(ACTIONS_PARAMS_RESULT) res = vdirectRunnable.run() assert res == MODULE_RESULT result_parameters = {"param1": "value1", "param2": "value2"} RUN_RESULT[self.module_mock.rest_client. RESP_DATA]['parameters'] = result_parameters MODULE_RESULT['parameters'] = result_parameters res = vdirectRunnable.run() assert res == MODULE_RESULT RUN_RESULT[self.module_mock.rest_client.RESP_STATUS] = 400 RUN_RESULT[self.module_mock.rest_client.RESP_REASON] = "Reason" RUN_RESULT[self.module_mock.rest_client.RESP_STR] = "Details" try: vdirectRunnable.run() self.fail("RunnableException was not thrown for failed run.") except vdirect_runnable.RunnableException as e: assert str(e) == "Reason: Reason. Details:Details." RUN_RESULT[self.module_mock.rest_client.RESP_STATUS] = 200 RUN_RESULT[self.module_mock.rest_client.RESP_DATA]["status"] = 400 RUN_RESULT[ self.module_mock.rest_client.RESP_DATA]["success"] = False RUN_RESULT[self.module_mock.rest_client.RESP_DATA]["exception"] = { "message": "exception message" } try: vdirectRunnable.run() self.fail("RunnableException was not thrown for failed run.") except vdirect_runnable.RunnableException as e: assert str(e) == "Reason: exception message. Details:Details."
from ansible.module_utils import basic from ansible.module_utils._text import to_bytes jnpr_mock = MagicMock() jxmlease_mock = MagicMock() modules = { 'jnpr': jnpr_mock, 'jnpr.junos': jnpr_mock.junos, 'jnpr.junos.utils': jnpr_mock.junos.utils, 'jnpr.junos.utils.config': jnpr_mock.junos.utils.config, 'jnpr.junos.version': jnpr_mock.junos.version, 'jnpr.junos.exception': jnpr_mock.junos.execption, 'jxmlease': jxmlease_mock } setattr(jnpr_mock.junos.version, 'VERSION', '2.0.0') module_patcher = patch.dict('sys.modules', modules) module_patcher.start() from ansible.modules.network.junos import junos_command def set_module_args(args): args = json.dumps({'ANSIBLE_MODULE_ARGS': args}) basic._ANSIBLE_ARGS = to_bytes(args) fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') fixture_data = {} def load_fixture(name): path = os.path.join(fixture_path, name)
pass fixture_data[path] = data return data class AnsibleExitJson(Exception): pass class AnsibleFailJson(Exception): pass mock_modules = {'ncclient': Mock(), 'ncclient.xml_': Mock()} patch_import = patch.dict('sys.modules', mock_modules) patch_import.start() class TestJunosModule(unittest.TestCase): def execute_module(self, failed=False, changed=False, commands=None, sort=True, defaults=False): self.load_fixtures(commands) if failed: result = self.failed()