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-")
示例#2
0
    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
示例#3
0
    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])
示例#4
0
    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')
示例#5
0
    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)
示例#6
0
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function
__metaclass__ = type

import json
import os

import pytest

from ansible_collections.ansible_community.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'
        }
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_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
示例#9
0
 def _mock_getpwnam(*args, **kwargs):
     mock_pw = MagicMock()
     mock_pw.pw_uid = 0
     return mock_pw
示例#10
0
 def _mock_getgrnam(*args, **kwargs):
     mock_gr = MagicMock()
     mock_gr.gr_gid = 0
     return mock_gr
示例#11
0
    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')
示例#12
0
from ansible_collections.ansible_community.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)