def test_module_utils_basic_ansible_module_selinux_enabled(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None 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 test_smoketest_load_file_common_args(self, am): """With no file arguments, an empty dict is returned""" am.selinux_mls_enabled = MagicMock() am.selinux_mls_enabled.return_value = True am.selinux_default_context = MagicMock() am.selinux_default_context.return_value = 'unconfined_u:object_r:default_t:s0'.split(':', 3) assert am.load_file_common_arguments(params={}) == {}
def setUp(self): super(TestNiosApi, self).setUp() self.module = MagicMock(name='AnsibleModule') self.module.check_mode = False self.module.params = {'provider': None} self.mock_connector = patch('ansible.module_utils.net_tools.nios.api.get_connector') self.mock_connector.start()
def test_module_utils_basic_ansible_module_is_special_selinux_path(self): from ansible.module_utils import basic args = json.dumps( dict( ANSIBLE_MODULE_ARGS={ '_ansible_selinux_special_fs': "nfs,nfsd,foos", '_ansible_remote_tmp': "/tmp", '_ansible_keep_remote_files': False })) with swap_stdin_and_argv(stdin_data=args): basic._ANSIBLE_ARGS = None am = basic.AnsibleModule(argument_spec=dict(), ) def _mock_find_mount_point(path): if path.startswith('/some/path'): return '/some/path' elif path.startswith('/weird/random/fstype'): return '/weird/random/fstype' return '/' am.find_mount_point = MagicMock(side_effect=_mock_find_mount_point) am.selinux_context = MagicMock( return_value=['foo_u', 'foo_r', 'foo_t', 's0']) m = mock_open() m.side_effect = OSError with patch.object(builtins, 'open', m, create=True): self.assertEqual( am.is_special_selinux_path( '/some/path/that/should/be/nfs'), (False, None)) mount_data = [ '/dev/disk1 / ext4 rw,seclabel,relatime,data=ordered 0 0\n', '1.1.1.1:/path/to/nfs /some/path nfs ro 0 0\n', 'whatever /weird/random/fstype foos rw 0 0\n', ] # mock_open has a broken readlines() implementation apparently... # this should work by default but doesn't, so we fix it m = mock_open(read_data=''.join(mount_data)) m.return_value.readlines.return_value = mount_data with patch.object(builtins, 'open', m, create=True): self.assertEqual( am.is_special_selinux_path('/some/random/path'), (False, None)) self.assertEqual( am.is_special_selinux_path( '/some/path/that/should/be/nfs'), (True, ['foo_u', 'foo_r', 'foo_t', 's0'])) self.assertEqual( am.is_special_selinux_path('/weird/random/fstype/path'), (True, ['foo_u', 'foo_r', 'foo_t', 's0']))
def test_module_utils_basic_ansible_module_user_and_group(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule(argument_spec=dict(), ) mock_stat = MagicMock() mock_stat.st_uid = 0 mock_stat.st_gid = 0 with patch('os.lstat', return_value=mock_stat): self.assertEqual(am.user_and_group('/path/to/file'), (0, 0))
def test_module_utils_basic_ansible_module_selinux_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_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 mock_response(self): mock_response = MagicMock() mock_response.getcode.return_value = 200 mock_response.headers = mock_response.getheaders.return_value = { 'X-Auth-Token': 'token_id' } mock_response.read.return_value = json.dumps({"value": "data"}) return mock_response
def test_tmpdir_makedirs_failure(self, am, monkeypatch): mock_mkdtemp = MagicMock(return_value="/tmp/path") mock_makedirs = MagicMock(side_effect=OSError("Some OS Error here")) monkeypatch.setattr(tempfile, 'mkdtemp', mock_mkdtemp) monkeypatch.setattr(os.path, 'exists', lambda x: False) monkeypatch.setattr(os, 'makedirs', mock_makedirs) actual = am.tmpdir assert actual == "/tmp/path" assert mock_makedirs.call_args[0] == (os.path.expanduser(os.path.expandvars("$HOME/.test")),) assert mock_makedirs.call_args[1] == {"mode": 0o700} # because makedirs failed the dir should be None so it uses the System tmp assert mock_mkdtemp.call_args[1]['dir'] is None assert mock_mkdtemp.call_args[1]['prefix'].startswith("ansible-moduletmp-")
def test_module_utils_basic_ansible_module_selinux_initial_context(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule(argument_spec=dict(), ) am.selinux_mls_enabled = MagicMock() am.selinux_mls_enabled.return_value = False self.assertEqual(am.selinux_initial_context(), [None, None, None]) am.selinux_mls_enabled.return_value = True self.assertEqual(am.selinux_initial_context(), [None, None, None, None])
def test_load_file_common_args(self, am, mocker): am.selinux_mls_enabled = MagicMock() am.selinux_mls_enabled.return_value = True am.selinux_default_context = MagicMock() am.selinux_default_context.return_value = 'unconfined_u:object_r:default_t:s0'.split(':', 3) base_params = dict( path='/path/to/file', mode=0o600, owner='root', group='root', seuser='******', serole='_default', setype='_default', selevel='_default', ) extended_params = base_params.copy() extended_params.update(dict( follow=True, foo='bar', )) final_params = base_params.copy() final_params.update(dict( path='/path/to/real_file', secontext=['unconfined_u', 'object_r', 'default_t', 's0'], attributes=None, )) # with the proper params specified, the returned dictionary should represent # only those params which have something to do with the file arguments, excluding # other params and updated as required with proper values which may have been # massaged by the method mocker.patch('os.path.islink', return_value=True) mocker.patch('os.path.realpath', return_value='/path/to/real_file') res = am.load_file_common_arguments(params=extended_params) assert res == final_params
def test_module_utils_basic_ansible_module_set_owner_if_different(self): from ansible.module_utils import basic basic._ANSIBLE_ARGS = None am = basic.AnsibleModule(argument_spec=dict(), ) self.assertEqual( am.set_owner_if_different('/path/to/file', None, True), True) self.assertEqual( am.set_owner_if_different('/path/to/file', None, False), False) am.user_and_group = MagicMock(return_value=(500, 500)) with patch('os.lchown', return_value=None) as m: self.assertEqual( am.set_owner_if_different('/path/to/file', 0, False), True) m.assert_called_with(b'/path/to/file', 0, -1) def _mock_getpwnam(*args, **kwargs): mock_pw = MagicMock() mock_pw.pw_uid = 0 return mock_pw m.reset_mock() with patch('pwd.getpwnam', side_effect=_mock_getpwnam): self.assertEqual( am.set_owner_if_different('/path/to/file', 'root', False), True) m.assert_called_with(b'/path/to/file', 0, -1) with patch('pwd.getpwnam', side_effect=KeyError): self.assertRaises(SystemExit, am.set_owner_if_different, '/path/to/file', 'root', False) m.reset_mock() am.check_mode = True self.assertEqual( am.set_owner_if_different('/path/to/file', 0, False), True) self.assertEqual(m.called, False) am.check_mode = False with patch('os.lchown', side_effect=OSError) as m: self.assertRaises(SystemExit, am.set_owner_if_different, '/path/to/file', 'root', False)
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('/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')
from __future__ import absolute_import, division, print_function __metaclass__ = type import json import os import pytest from ansible_collections.database.postgresql.tests.unit.compat.mock import MagicMock from ansible.module_utils import basic from ansible.module_utils.six import integer_types from ansible.module_utils.six.moves import builtins MOCK_VALIDATOR_FAIL = MagicMock(side_effect=TypeError("bad conversion")) # Data is argspec, argument, expected VALID_SPECS = ( # Simple type=int ({'arg': {'type': 'int'}}, {'arg': 42}, 42), # Simple type=int with a large value (will be of type long under Python 2) ({'arg': {'type': 'int'}}, {'arg': 18765432109876543210}, 18765432109876543210), # Simple type=list, elements=int ({'arg': {'type': 'list', 'elements': 'int'}}, {'arg': [42, 32]}, [42, 32]), # Type=int with conversion from string ({'arg': {'type': 'int'}}, {'arg': '42'}, 42), # Type=list elements=int with conversion from string ({'arg': {'type': 'list', 'elements': 'int'}}, {'arg': ['42', '32']}, [42, 32]), # Simple type=float ({'arg': {'type': 'float'}}, {'arg': 42.0}, 42.0), # Simple type=list, elements=float
class TestNiosApi(unittest.TestCase): def setUp(self): super(TestNiosApi, self).setUp() self.module = MagicMock(name='AnsibleModule') self.module.check_mode = False self.module.params = {'provider': None} self.mock_connector = patch('ansible.module_utils.net_tools.nios.api.get_connector') self.mock_connector.start() def tearDown(self): super(TestNiosApi, self).tearDown() self.mock_connector.stop() def test_get_provider_spec(self): provider_options = ['host', 'username', 'password', 'validate_certs', 'silent_ssl_warnings', 'http_request_timeout', 'http_pool_connections', 'http_pool_maxsize', 'max_retries', 'wapi_version', 'max_results'] res = api.WapiBase.provider_spec self.assertIsNotNone(res) self.assertIn('provider', res) self.assertIn('options', res['provider']) returned_options = res['provider']['options'] self.assertEqual(sorted(provider_options), sorted(returned_options.keys())) def _get_wapi(self, test_object): wapi = api.WapiModule(self.module) wapi.get_object = Mock(name='get_object', return_value=test_object) wapi.create_object = Mock(name='create_object') wapi.update_object = Mock(name='update_object') wapi.delete_object = Mock(name='delete_object') return wapi def test_wapi_no_change(self): self.module.params = {'provider': None, 'state': 'present', 'name': 'default', 'comment': 'test comment', 'extattrs': None} test_object = [ { "comment": "test comment", "_ref": "networkview/ZG5zLm5ldHdvcmtfdmlldyQw:default/true", "name": self.module._check_type_dict().__getitem__(), "extattrs": {} } ] test_spec = { "name": {"ib_req": True}, "comment": {}, "extattrs": {} } wapi = self._get_wapi(test_object) res = wapi.run('testobject', test_spec) self.assertFalse(res['changed']) def test_wapi_change(self): self.module.params = {'provider': None, 'state': 'present', 'name': 'default', 'comment': 'updated comment', 'extattrs': None} test_object = [ { "comment": "test comment", "_ref": "networkview/ZG5zLm5ldHdvcmtfdmlldyQw:default/true", "name": "default", "extattrs": {} } ] test_spec = { "name": {"ib_req": True}, "comment": {}, "extattrs": {} } wapi = self._get_wapi(test_object) res = wapi.run('testobject', test_spec) self.assertTrue(res['changed']) wapi.update_object.called_once_with(test_object) def test_wapi_change_false(self): self.module.params = {'provider': None, 'state': 'present', 'name': 'default', 'comment': 'updated comment', 'extattrs': None, 'fqdn': 'foo'} test_object = [ { "comment": "test comment", "_ref": "networkview/ZG5zLm5ldHdvcmtfdmlldyQw:default/true", "name": "default", "extattrs": {} } ] test_spec = { "name": {"ib_req": True}, "fqdn": {"ib_req": True, 'update': False}, "comment": {}, "extattrs": {} } wapi = self._get_wapi(test_object) res = wapi.run('testobject', test_spec) self.assertTrue(res['changed']) wapi.update_object.called_once_with(test_object) def test_wapi_extattrs_change(self): self.module.params = {'provider': None, 'state': 'present', 'name': 'default', 'comment': 'test comment', 'extattrs': {'Site': 'update'}} ref = "networkview/ZG5zLm5ldHdvcmtfdmlldyQw:default/true" test_object = [{ "comment": "test comment", "_ref": ref, "name": "default", "extattrs": {'Site': {'value': 'test'}} }] test_spec = { "name": {"ib_req": True}, "comment": {}, "extattrs": {} } kwargs = copy.deepcopy(test_object[0]) kwargs['extattrs']['Site']['value'] = 'update' kwargs['name'] = self.module._check_type_dict().__getitem__() del kwargs['_ref'] wapi = self._get_wapi(test_object) res = wapi.run('testobject', test_spec) self.assertTrue(res['changed']) wapi.update_object.assert_called_once_with(ref, kwargs) def test_wapi_extattrs_nochange(self): self.module.params = {'provider': None, 'state': 'present', 'name': 'default', 'comment': 'test comment', 'extattrs': {'Site': 'test'}} test_object = [{ "comment": "test comment", "_ref": "networkview/ZG5zLm5ldHdvcmtfdmlldyQw:default/true", "name": self.module._check_type_dict().__getitem__(), "extattrs": {'Site': {'value': 'test'}} }] test_spec = { "name": {"ib_req": True}, "comment": {}, "extattrs": {} } wapi = self._get_wapi(test_object) res = wapi.run('testobject', test_spec) self.assertFalse(res['changed']) def test_wapi_create(self): self.module.params = {'provider': None, 'state': 'present', 'name': 'ansible', 'comment': None, 'extattrs': None} test_object = None test_spec = { "name": {"ib_req": True}, "comment": {}, "extattrs": {} } wapi = self._get_wapi(test_object) res = wapi.run('testobject', test_spec) self.assertTrue(res['changed']) wapi.create_object.assert_called_once_with('testobject', {'name': self.module._check_type_dict().__getitem__()}) def test_wapi_delete(self): self.module.params = {'provider': None, 'state': 'absent', 'name': 'ansible', 'comment': None, 'extattrs': None} ref = "networkview/ZG5zLm5ldHdvcmtfdmlldyQw:ansible/false" test_object = [{ "comment": "test comment", "_ref": ref, "name": "ansible", "extattrs": {'Site': {'value': 'test'}} }] test_spec = { "name": {"ib_req": True}, "comment": {}, "extattrs": {} } wapi = self._get_wapi(test_object) res = wapi.run('testobject', test_spec) self.assertTrue(res['changed']) wapi.delete_object.assert_called_once_with(ref) def test_wapi_strip_network_view(self): self.module.params = {'provider': None, 'state': 'present', 'name': 'ansible', 'comment': 'updated comment', 'extattrs': None, 'network_view': 'default'} test_object = [{ "comment": "test comment", "_ref": "view/ZG5zLm5ldHdvcmtfdmlldyQw:ansible/true", "name": "ansible", "extattrs": {}, "network_view": "default" }] test_spec = { "name": {"ib_req": True}, "network_view": {"ib_req": True}, "comment": {}, "extattrs": {} } kwargs = test_object[0].copy() ref = kwargs.pop('_ref') kwargs['comment'] = 'updated comment' kwargs['name'] = self.module._check_type_dict().__getitem__() del kwargs['network_view'] del kwargs['extattrs'] wapi = self._get_wapi(test_object) res = wapi.run('testobject', test_spec) self.assertTrue(res['changed']) wapi.update_object.assert_called_once_with(ref, kwargs)
def _mock_getpwnam(*args, **kwargs): mock_pw = MagicMock() mock_pw.pw_uid = 0 return mock_pw
from ansible_collections.database.postgresql.tests.unit.compat.mock import MagicMock from ansible.utils.path import unfrackpath mock_unfrackpath_noop = MagicMock(spec_set=unfrackpath, side_effect=lambda x, *args, **kwargs: x)
def _mock_getgrnam(*args, **kwargs): mock_gr = MagicMock() mock_gr.gr_gid = 0 return mock_gr