Beispiel #1
0
 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
Beispiel #2
0
    def test_find_bind_mounts_no_findmnts(self):
        module = Mock()
        module.get_bin_path = Mock(return_value=None)
        lh = hardware.linux.LinuxHardware(module=module, load_on_init=False)
        bind_mounts = lh._find_bind_mounts()

        self.assertIsInstance(bind_mounts, set)
        self.assertEqual(len(bind_mounts), 0)
Beispiel #3
0
    def test_lsblk_uuid_no_lsblk(self):
        module = Mock()
        module.get_bin_path = Mock(return_value=None)
        lh = hardware.linux.LinuxHardware(module=module, load_on_init=False)
        lsblk_uuids = lh._lsblk_uuid()

        self.assertIsInstance(lsblk_uuids, dict)
        self.assertEqual(len(lsblk_uuids), 0)
Beispiel #4
0
    def test_udevadm_uuid(self):
        module = Mock()
        module.run_command = Mock(return_value=(0, UDEVADM_OUTPUT,
                                                ''))  # (rc, out, err)
        lh = linux.LinuxHardware(module=module, load_on_init=False)
        udevadm_uuid = lh._udevadm_uuid('mock_device')

        self.assertEqual(udevadm_uuid, '57b1a3e7-9019-4747-9809-7ec52bba9179')
def mock_module():
    mock_module = Mock()
    mock_module.params = {
        'gather_subset': ['all'],
        'gather_timeout': 5,
        'filter': '*'
    }
    mock_module.get_bin_path = Mock(return_value=None)
    return mock_module
 def _mock_module(self):
     mock_module = Mock()
     mock_module.params = {
         'gather_subset': self.gather_subset,
         'gather_timeout': 5,
         'filter': '*'
     }
     mock_module.get_bin_path = Mock(return_value=None)
     return mock_module
Beispiel #7
0
def mock_module(gather_subset=None, filter=None):
    if gather_subset is None:
        gather_subset = ['all', '!facter', '!ohai']
    if filter is None:
        filter = '*'
    mock_module = Mock()
    mock_module.params = {
        'gather_subset': gather_subset,
        'gather_timeout': 5,
        'filter': filter
    }
    mock_module.get_bin_path = Mock(return_value=None)
    return mock_module
Beispiel #8
0
    def test_lsblk_uuid_non_zero(self, mock_run_lsblk):
        module = Mock()
        lh = hardware.linux.LinuxHardware(module=module, load_on_init=False)
        lsblk_uuids = lh._lsblk_uuid()

        self.assertIsInstance(lsblk_uuids, dict)
        self.assertEqual(len(lsblk_uuids), 0)
Beispiel #9
0
    def test_find_bind_mounts_non_zero(self, mock_run_findmnt):
        module = Mock()
        lh = hardware.linux.LinuxHardware(module=module, load_on_init=False)
        bind_mounts = lh._find_bind_mounts()

        self.assertIsInstance(bind_mounts, set)
        self.assertEqual(len(bind_mounts), 0)
Beispiel #10
0
    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')
Beispiel #11
0
 def test_new(self, mock_platform):
     if not self.fact_class:
         pytest.skip('This platform (%s) does not have a fact_class.' %
                     self.platform_id)
     mock_platform.return_value = self.platform_id
     inst = self.fact_class(module=Mock(), load_on_init=False)
     self.assertIsInstance(inst, self.fact_class)
     self.assertEqual(inst.platform, self.platform_id)
Beispiel #12
0
    def test_get_mtab_entries(self, mock_get_file_content):

        module = Mock()
        lh = hardware.linux.LinuxHardware(module=module, load_on_init=False)
        mtab_entries = lh._mtab_entries()
        self.assertIsInstance(mtab_entries, list)
        self.assertIsInstance(mtab_entries[0], list)
        self.assertEqual(len(mtab_entries), 38)
Beispiel #13
0
    def test_find_bind_mounts(self, mock_run_findmnt):
        module = Mock()
        lh = hardware.linux.LinuxHardware(module=module, load_on_init=False)
        bind_mounts = lh._find_bind_mounts()

        # If bind_mounts becomes another seq type, feel free to change
        self.assertIsInstance(bind_mounts, set)
        self.assertEqual(len(bind_mounts), 1)
        self.assertIn('/not/a/real/bind_mount', bind_mounts)
 def test_no_proc1(self, mock_gfc):
     # no /proc/1/comm, ps returns non-0
     # should fallback to 'service'
     module = self._mock_module()
     module.run_command = Mock(return_value=(1, '', 'wat'))
     fact_collector = self.collector_class()
     facts_dict = fact_collector.collect(module=module)
     self.assertIsInstance(facts_dict, dict)
     self.assertEqual(facts_dict['service_mgr'], 'service')
 def test_no_proc1_ps_random_init(self, mock_gfc):
     # no /proc/1/comm, ps returns '/sbin/sys11' which we dont know
     # should end up return 'sys11'
     module = self._mock_module()
     module.run_command = Mock(return_value=(0, '/sbin/sys11', ''))
     fact_collector = self.collector_class()
     facts_dict = fact_collector.collect(module=module)
     self.assertIsInstance(facts_dict, dict)
     self.assertEqual(facts_dict['service_mgr'], 'sys11')
Beispiel #16
0
 def test_subclass(self):
     if not self.fact_class:
         pytest.skip('This platform (%s) does not have a fact_class.' %
                     self.platform_id)
     # 'Generic' will try to map to platform.system() that we are not mocking here
     if self.platform_id == 'Generic':
         return
     inst = self.fact_class(module=Mock(), load_on_init=False)
     self.assertIsInstance(inst, self.fact_class)
     self.assertEqual(inst.platform, self.platform_id)
Beispiel #17
0
    def test_lsblk_uuid(self, mock_run_lsblk):
        module = Mock()
        lh = hardware.linux.LinuxHardware(module=module, load_on_init=False)
        lsblk_uuids = lh._lsblk_uuid()

        self.assertIsInstance(lsblk_uuids, dict)
        self.assertIn(b'/dev/loop9', lsblk_uuids)
        self.assertIn(b'/dev/sda1', lsblk_uuids)
        self.assertEqual(lsblk_uuids[b'/dev/sda1'],
                         b'32caaec3-ef40-4691-a3b6-438c3f9bc1c0')
 def test_clowncar(self, mock_gfc):
     # no /proc/1/comm, ps fails, distro and system are clowncar
     # should end up return 'sys11'
     module = self._mock_module()
     module.run_command = Mock(return_value=(1, '', ''))
     collected_facts = {'distribution': 'clowncar', 'system': 'ClownCarOS'}
     fact_collector = self.collector_class()
     facts_dict = fact_collector.collect(module=module,
                                         collected_facts=collected_facts)
     self.assertIsInstance(facts_dict, dict)
     self.assertEqual(facts_dict['service_mgr'], 'service')
Beispiel #19
0
def test_get_fc_wwn_info(mocker):
    module = Mock()
    inst = fc_wwn.FcWwnInitiatorFactCollector()

    mocker.patch.object(module, 'get_bin_path', side_effect=mock_get_bin_path)
    mocker.patch.object(module, 'run_command', side_effect=mock_run_command)

    d = {'aix6': ['10000090FA551508'], 'sunos5': ['10000090fa1658de']}
    for key, value in d.items():
        mocker.patch('sys.platform', key)
        wwn_expected = {"fibre_channel_wwn": value}
        assert wwn_expected == inst.collect(module=module)
 def _mock_module(self):
     mock_module = Mock()
     mock_module.params = {
         'gather_subset': self.gather_subset,
         'gather_timeout': 10,
         'filter': '*'
     }
     mock_module.get_bin_path = Mock(return_value='/usr/sbin/capsh')
     mock_module.run_command = Mock(return_value=(0, 'Current: =ep', ''))
     return mock_module
Beispiel #21
0
 def test_lsblk_uuid_dev_with_space_in_name(self, mock_run_lsblk):
     module = Mock()
     lh = hardware.linux.LinuxHardware(module=module, load_on_init=False)
     lsblk_uuids = lh._lsblk_uuid()
     self.assertIsInstance(lsblk_uuids, dict)
     self.assertIn(b'/dev/loop0', lsblk_uuids)
     self.assertIn(b'/dev/sda1', lsblk_uuids)
     self.assertEqual(
         lsblk_uuids[
             b'/dev/mapper/an-example-mapper with a space in the name'],
         b'84639acb-013f-4d2f-9392-526a572b4373')
     self.assertEqual(lsblk_uuids[b'/dev/sda1'],
                      b'32caaec3-ef40-4691-a3b6-438c3f9bc1c0')
 def _mock_module(self):
     mock_module = Mock()
     mock_module.params = {
         'gather_subset': self.gather_subset,
         'gather_timeout': 10,
         'filter': '*'
     }
     mock_module.get_bin_path = Mock(return_value='/usr/bin/lsb_release')
     mock_module.run_command = Mock(
         return_value=(0, lsb_release_a_fedora_output, ''))
     return mock_module
 def _mock_module(self):
     mock_module = Mock()
     mock_module.params = {
         'gather_subset': self.gather_subset,
         'gather_timeout': 10,
         'filter': '*'
     }
     mock_module.get_bin_path = Mock(return_value='/not/actually/facter')
     mock_module.run_command = Mock(return_value=(0, facter_json_output,
                                                  ''))
     return mock_module
Beispiel #24
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 test_etc_lsb_release_no_decimal_release(self):
        module = self._mock_module()
        module.get_bin_path = Mock(return_value=None)
        with patch('ansible.module_utils.facts.system.lsb.os.path.exists',
                   return_value=True):
            with patch('ansible.module_utils.facts.system.lsb.get_file_lines',
                       return_value=etc_lsb_release_no_decimal.splitlines()):
                fact_collector = self.collector_class()
                facts_dict = fact_collector.collect(module=module)

        self.assertIsInstance(facts_dict, dict)
        self.assertEqual(facts_dict['lsb']['release'], '11')
        self.assertEqual(facts_dict['lsb']['id'], 'AwesomeOS')
        self.assertEqual(facts_dict['lsb']['description'], 'AwesomeÖS 11')
        self.assertEqual(facts_dict['lsb']['codename'], 'stonehenge')
    def test_etc_lsb_release(self):
        module = self._mock_module()
        module.get_bin_path = Mock(return_value=None)
        with patch('ansible.module_utils.facts.system.lsb.os.path.exists',
                   return_value=True):
            with patch('ansible.module_utils.facts.system.lsb.get_file_lines',
                       return_value=etc_lsb_release_ubuntu14.splitlines()):
                fact_collector = self.collector_class()
                facts_dict = fact_collector.collect(module=module)

        self.assertIsInstance(facts_dict, dict)
        self.assertEqual(facts_dict['lsb']['release'], '14.04')
        self.assertEqual(facts_dict['lsb']['id'], 'Ubuntu')
        self.assertEqual(facts_dict['lsb']['description'],
                         'Ubuntu 14.04.3 LTS')
        self.assertEqual(facts_dict['lsb']['codename'], 'trusty')
Beispiel #27
0
    def test_module_utils_basic_ansible_module_selinux_mls_enabled(self):
        from ansible.module_utils import basic
        basic._ANSIBLE_ARGS = None

        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_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])
Beispiel #29
0
    def test_get_mount_facts(self, mock_lsblk_uuid, mock_find_bind_mounts,
                             mock_mtab_entries, mock_udevadm_uuid):
        module = Mock()
        # Returns a LinuxHardware-ish
        lh = hardware.linux.LinuxHardware(module=module, load_on_init=False)

        # Nothing returned, just self.facts modified as a side effect
        mount_facts = lh.get_mount_facts()
        self.assertIsInstance(mount_facts, dict)
        self.assertIn('mounts', mount_facts)
        self.assertIsInstance(mount_facts['mounts'], list)
        self.assertIsInstance(mount_facts['mounts'][0], dict)

        # Find mounts with space in the mountpoint path
        mounts_with_space = [
            x for x in mount_facts['mounts'] if ' ' in x['mount']
        ]
        self.assertEqual(len(mounts_with_space), 1)
        self.assertEqual(mounts_with_space[0]['mount'], '/mnt/foo bar')
Beispiel #30
0
def test_get_iscsi_info(mocker):
    module = Mock()
    inst = iscsi.IscsiInitiatorNetworkCollector()

    mocker.patch('sys.platform', 'aix6')
    mocker.patch('ansible.module_utils.facts.network.iscsi.get_bin_path',
                 return_value='/usr/sbin/lsattr')
    mocker.patch.object(module,
                        'run_command',
                        return_value=(0, LSATTR_OUTPUT, ''))
    aix_iscsi_expected = {"iscsi_iqn": "iqn.localhost.hostid.7f000002"}
    assert aix_iscsi_expected == inst.collect(module=module)

    mocker.patch('sys.platform', 'hp-ux')
    mocker.patch('ansible.module_utils.facts.network.iscsi.get_bin_path',
                 return_value='/opt/iscsi/bin/iscsiutil')
    mocker.patch.object(module,
                        'run_command',
                        return_value=(0, ISCSIUTIL_OUTPUT, ''))
    hpux_iscsi_expected = {"iscsi_iqn": " iqn.2001-04.com.hp.stor:svcio"}
    assert hpux_iscsi_expected == inst.collect(module=module)