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')
Beispiel #2
0
 def setUp(self):
     self.mock_run_command = (
         patch('ansible.module_utils.basic.AnsibleModule.run_command'))
     self.run_command = self.mock_run_command.start()
     self.mock_get_bin_path = (
         patch('ansible.module_utils.basic.AnsibleModule.get_bin_path'))
     self.get_bin_path = self.mock_get_bin_path.start()
Beispiel #3
0
    def test_add_host_key(self):

        # Copied
        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

        with swap_stdin_and_argv(stdin_data=args):
            ansible.module_utils.basic._ANSIBLE_ARGS = None
            self.module = ansible.module_utils.basic.AnsibleModule(argument_spec=dict())

            get_bin_path = Mock()
            get_bin_path.return_value = keyscan_cmd = "/custom/path/ssh-keyscan"
            self.module.get_bin_path = get_bin_path

            run_command = Mock()
            run_command.return_value = (0, "Needs output, otherwise thinks ssh-keyscan timed out'", "")
            self.module.run_command = run_command

            append_to_file = Mock()
            append_to_file.return_value = (None,)
            self.module.append_to_file = append_to_file

            with patch('os.path.isdir', return_value=True):
                with patch('os.path.exists', return_value=True):
                    for u in self.urls:
                        if self.urls[u]['is_ssh_url']:
                            known_hosts.add_host_key(self.module, self.urls[u]['get_fqdn'], port=self.urls[u]['port'])
                            run_command.assert_called_with(keyscan_cmd + self.urls[u]['add_host_key_cmd'])
Beispiel #4
0
    def test_module_utils_basic_ansible_module_set_mode_if_different(self):
        from ansible.module_utils import basic

        basic.MODULE_COMPLEX_ARGS = "{}"
        am = basic.AnsibleModule(argument_spec=dict())

        mock_stat1 = MagicMock()
        mock_stat1.st_mode = 0o444
        mock_stat2 = MagicMock()
        mock_stat2.st_mode = 0o660

        with patch("os.lstat", side_effect=[mock_stat1]):
            self.assertEqual(am.set_mode_if_different("/path/to/file", None, True), True)
        with patch("os.lstat", side_effect=[mock_stat1]):
            self.assertEqual(am.set_mode_if_different("/path/to/file", None, False), False)

        with patch("os.lstat") as m:
            with patch("os.lchmod", return_value=None, create=True) as m_os:
                m.side_effect = [mock_stat1, mock_stat2, mock_stat2]
                self.assertEqual(am.set_mode_if_different("/path/to/file", 0o660, False), True)
                m_os.assert_called_with("/path/to/file", 0o660)

                m.side_effect = [mock_stat1, mock_stat2, mock_stat2]
                am._symbolic_mode_to_octal = MagicMock(return_value=0o660)
                self.assertEqual(am.set_mode_if_different("/path/to/file", "o+w,g+w,a-r", False), True)
                m_os.assert_called_with("/path/to/file", 0o660)

                m.side_effect = [mock_stat1, mock_stat2, mock_stat2]
                am._symbolic_mode_to_octal = MagicMock(side_effect=Exception)
                self.assertRaises(SystemExit, am.set_mode_if_different, "/path/to/file", "o+w,g+w,a-r", False)

                m.side_effect = [mock_stat1, mock_stat2, mock_stat2]
                am.check_mode = True
                self.assertEqual(am.set_mode_if_different("/path/to/file", 0o660, False), True)
                am.check_mode = False
    def setUp(self):
        super(TestNxosBannerModule, self).setUp()
        self.mock_run_commands = patch('ansible.modules.network.nxos.nxos_banner.run_commands')
        self.run_commands = self.mock_run_commands.start()

        self.mock_load_config = patch('ansible.modules.network.nxos.nxos_banner.load_config')
        self.load_config = self.mock_load_config.start()
    def setUp(self):
        super(TestNxosOverlayGlobalModule, self).setUp()
        self.mock_load_config = patch('ansible.modules.network.nxos.nxos_overlay_global.load_config')
        self.load_config = self.mock_load_config.start()

        self.mock_get_config = patch('ansible.modules.network.nxos.nxos_overlay_global.get_config')
        self.get_config = self.mock_get_config.start()
    def test_module_utils_basic_ansible_module_find_mount_point(self):
        from ansible.module_utils import basic
        basic._ANSIBLE_ARGS = None

        am = basic.AnsibleModule(
            argument_spec=dict(),
        )

        def _mock_ismount(path):
            if path == b'/':
                return True
            return False

        with patch('os.path.ismount', side_effect=_mock_ismount):
            self.assertEqual(am.find_mount_point('/root/fs/../mounted/path/to/whatever'), '/')

        def _mock_ismount(path):
            if path == b'/subdir/mount':
                return True
            if path == b'/':
                return True
            return False

        with patch('os.path.ismount', side_effect=_mock_ismount):
            self.assertEqual(am.find_mount_point('/subdir/mount/path/to/whatever'), '/subdir/mount')
    def setUp(self):
        super(TestIosxrConfigModule, self).setUp()

        self.patcher_get_config = patch('ansible.modules.network.iosxr.iosxr_config.get_config')
        self.mock_get_config = self.patcher_get_config.start()
        self.patcher_exec_command = patch('ansible.modules.network.iosxr.iosxr_config.load_config')
        self.mock_exec_command = self.patcher_exec_command.start()
    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 test_module_utils_basic_get_distribution(self):
        from ansible.module_utils.basic import get_distribution

        with patch('platform.system', return_value='Foo'):
            self.assertEqual(get_distribution(), None)

        with patch('platform.system', return_value='Linux'):
            with patch('platform.linux_distribution', return_value=["foo"]):
                self.assertEqual(get_distribution(), "Foo")

            with patch('os.path.isfile', return_value=True):
                with patch('platform.linux_distribution', side_effect=[("AmazonFooBar",)]):
                    self.assertEqual(get_distribution(), "Amazonfoobar")

                with patch('platform.linux_distribution', side_effect=(("",), ("AmazonFooBam",))):
                    self.assertEqual(get_distribution(), "Amazon")

                with patch('platform.linux_distribution', side_effect=[("",),("",)]):
                    self.assertEqual(get_distribution(), "OtherLinux")

                def _dist(distname='', version='', id='', supported_dists=(), full_distribution_name=1):
                    if supported_dists != ():
                        return ("Bar", "2", "Two")
                    else:
                        return ("", "", "")
                
                with patch('platform.linux_distribution', side_effect=_dist):
                    self.assertEqual(get_distribution(), "Bar")
                
            with patch('platform.linux_distribution', side_effect=Exception("boo")):
                with patch('platform.dist', return_value=("bar", "2", "Two")):
                    self.assertEqual(get_distribution(), "Bar")
Beispiel #11
0
    def test_exception_unassign_member(self):
        set_module_args(args={
            'id': 'user-id',
            'type': 'User',
            'parent_id': 'group-id',
            'parent_type': 'Group',
            'state': 'absent'
        })

        def users_get(self, filter=None, order_by=None, group_by=None, page=None, page_size=None, query_parameters=None, commit=True,
                      callback=None, **kwargs):
            group_by = [] if group_by is None else group_by

            return [vsdk.NUUser(id='user-id'), vsdk.NUUser(id='user-id-2')]

        def group_assign(self, objects, nurest_object_type, callback=None, commit=True, **kwargs):
            raise BambouHTTPError(MockNuageConnection(status_code='500', reason='Server exception', errors={'description': 'Unable to remove member'}))

        with self.assertRaises(AnsibleFailJson) as exc:
            with patch('vspk.v5_0.fetchers.NUUsersFetcher.get', users_get):
                with patch('vspk.v5_0.NUGroup.assign', new=group_assign):
                    nuage_vspk.main()

        result = exc.exception.args[0]

        self.assertTrue(result['failed'])
        self.assertEqual(result['msg'], "Unable to remove entity as a member: [HTTP 500(Server exception)] {'description': 'Unable to remove member'}")
    def setUp(self):
        super(TestVyosSystemModule, self).setUp()

        self.mock_get_config = patch('ansible.modules.network.vyos.vyos_system.get_config')
        self.get_config = self.mock_get_config.start()

        self.mock_load_config = patch('ansible.modules.network.vyos.vyos_system.load_config')
        self.load_config = self.mock_load_config.start()
Beispiel #13
0
    def setUp(self):
        super(TestIosBannerModule, self).setUp()

        self.mock_exec_command = patch('ansible.modules.network.ios.ios_banner.exec_command')
        self.exec_command = self.mock_exec_command.start()

        self.mock_load_config = patch('ansible.modules.network.ios.ios_banner.load_config')
        self.load_config = self.mock_load_config.start()
    def setUp(self):
        super(TestNxosInterfaceOspfModule, self).setUp()

        self.mock_get_config = patch('ansible.modules.network.nxos.nxos_interface_ospf.get_config')
        self.get_config = self.mock_get_config.start()

        self.mock_load_config = patch('ansible.modules.network.nxos.nxos_interface_ospf.load_config')
        self.load_config = self.mock_load_config.start()
def _check_mode_changed_to_0660(self, mode):
    # Note: This is for checking that all the different ways of specifying
    # 0660 mode work.  It cannot be used to check that setting a mode that is
    # not equivalent to 0660 works.
    with patch('os.lstat', side_effect=[self.mock_stat1, self.mock_stat2, self.mock_stat2]) as m_lstat:
        with patch('os.lchmod', return_value=None, create=True) as m_lchmod:
            self.assertEqual(self.am.set_mode_if_different('/path/to/file', mode, False), True)
            m_lchmod.assert_called_with(b'/path/to/file', 0o660)
    def setUp(self):
        super(TestNxosAclInterfaceModule, self).setUp()

        self.mock_run_commands = patch('ansible.modules.network.nxos.nxos_acl_interface.run_commands')
        self.run_commands = self.mock_run_commands.start()

        self.mock_load_config = patch('ansible.modules.network.nxos.nxos_acl_interface.load_config')
        self.load_config = self.mock_load_config.start()
    def setUp(self):
        super(TestNxosBgpNeighborAfModule, self).setUp()

        self.mock_load_config = patch('ansible.modules.network.nxos.nxos_bgp_neighbor_af.load_config')
        self.load_config = self.mock_load_config.start()

        self.mock_get_config = patch('ansible.modules.network.nxos.nxos_bgp_neighbor_af.get_config')
        self.get_config = self.mock_get_config.start()
    def setUp(self):
        super(TestVyosStaticRouteModule, self).setUp()

        self.mock_get_config = patch('ansible.modules.network.vyos.vyos_static_route.get_config')
        self.get_config = self.mock_get_config.start()

        self.mock_load_config = patch('ansible.modules.network.vyos.vyos_static_route.load_config')
        self.load_config = self.mock_load_config.start()
    def setUp(self):
        super(TestIosxrNetconfModule, self).setUp()

        self.mock_get_config = patch('ansible.modules.network.iosxr.iosxr_netconf.get_config')
        self.get_config = self.mock_get_config.start()

        self.mock_load_config = patch('ansible.modules.network.iosxr.iosxr_netconf.load_config')
        self.load_config = self.mock_load_config.start()
Beispiel #20
0
    def setUp(self):
        super(TestNxosBgp32BitsAS, self).setUp()

        self.mock_load_config = patch('ansible.modules.network.nxos.nxos_bgp.load_config')
        self.load_config = self.mock_load_config.start()

        self.mock_get_config = patch('ansible.modules.network.nxos.nxos_bgp.get_config')
        self.get_config = self.mock_get_config.start()
    def setUp(self):
        super(TestNxosOspfVrfModule, self).setUp()

        self.mock_load_config = patch('ansible.modules.network.nxos.nxos_ospf_vrf.load_config')
        self.load_config = self.mock_load_config.start()

        self.mock_get_config = patch('ansible.modules.network.nxos.nxos_ospf_vrf.get_config')
        self.get_config = self.mock_get_config.start()
    def setUp(self):
        super(TestNxosVxlanVtepVniModule, self).setUp()

        self.mock_load_config = patch('ansible.modules.network.nxos.nxos_vxlan_vtep_vni.load_config')
        self.load_config = self.mock_load_config.start()

        self.mock_get_config = patch('ansible.modules.network.nxos.nxos_vxlan_vtep_vni.get_config')
        self.get_config = self.mock_get_config.start()
Beispiel #23
0
    def setUp(self):
        super(TestEosUserModule, self).setUp()

        self.mock_get_config = patch('ansible.modules.network.eos.eos_user.get_config')
        self.get_config = self.mock_get_config.start()

        self.mock_load_config = patch('ansible.modules.network.eos.eos_user.load_config')
        self.load_config = self.mock_load_config.start()
Beispiel #24
0
    def setUp(self):
        super(TestEosConfigModule, self).setUp()
        self.mock_get_config = patch('ansible.modules.network.eos.eos_config.get_config')
        self.get_config = self.mock_get_config.start()

        self.mock_load_config = patch('ansible.modules.network.eos.eos_config.load_config')
        self.load_config = self.mock_load_config.start()
        self.mock_run_commands = patch('ansible.modules.network.eos.eos_config.run_commands')
        self.run_commands = self.mock_run_commands.start()
    def setUp(self):
        self.mock_get_config = patch('ansible.modules.network.nxos.nxos_pim_interface.get_config')
        self.get_config = self.mock_get_config.start()

        self.mock_load_config = patch('ansible.modules.network.nxos.nxos_pim_interface.load_config')
        self.load_config = self.mock_load_config.start()

        self.mock_run_commands = patch('ansible.modules.network.nxos.nxos_pim_interface.run_commands')
        self.run_commands = self.mock_run_commands.start()
Beispiel #26
0
    def setUp(self):
        self.mock_get_config = patch('ansible.modules.network.vyos.vyos_config.get_config')
        self.get_config = self.mock_get_config.start()

        self.mock_load_config = patch('ansible.modules.network.vyos.vyos_config.load_config')
        self.load_config = self.mock_load_config.start()

        self.mock_run_commands = patch('ansible.modules.network.vyos.vyos_config.run_commands')
        self.run_commands = self.mock_run_commands.start()
    def setUp(self):
        super(TestOpenVSwitchDBModule, self).setUp()

        self.mock_run_command = (
            patch('ansible.module_utils.basic.AnsibleModule.run_command'))
        self.run_command = self.mock_run_command.start()
        self.mock_get_bin_path = (
            patch('ansible.module_utils.basic.AnsibleModule.get_bin_path'))
        self.get_bin_path = self.mock_get_bin_path.start()
    def test_module_utils_basic_ansible_module_set_mode_if_different(self):
        with patch('os.lstat') as m:
            with patch('os.lchmod', return_value=None, create=True) as m_os:
                m.side_effect = [self.mock_stat1, self.mock_stat2, self.mock_stat2]
                self.am._symbolic_mode_to_octal = MagicMock(side_effect=Exception)
                self.assertRaises(SystemExit, self.am.set_mode_if_different, '/path/to/file', 'o+w,g+w,a-r', False)

        original_hasattr = hasattr
        def _hasattr(obj, name):
            if obj == os and name == 'lchmod':
                return False
            return original_hasattr(obj, name)

        # FIXME: this isn't working yet
        with patch('os.lstat', side_effect=[self.mock_stat1, self.mock_stat2]):
            with patch.object(builtins, 'hasattr', side_effect=_hasattr):
                with patch('os.path.islink', return_value=False):
                    with patch('os.chmod', return_value=None) as m_chmod:
                        self.assertEqual(self.am.set_mode_if_different('/path/to/file/no_lchmod', 0o660, False), True)
        with patch('os.lstat', side_effect=[self.mock_stat1, self.mock_stat2]):
            with patch.object(builtins, 'hasattr', side_effect=_hasattr):
                with patch('os.path.islink', return_value=True):
                    with patch('os.chmod', return_value=None) as m_chmod:
                        with patch('os.stat', return_value=self.mock_stat2):
                            self.assertEqual(self.am.set_mode_if_different('/path/to/file', 0o660, False), True)
    def setUp(self):
        super(TestSlxosLinkaggModule, self).setUp()
        self._patch_get_config = patch(
            'ansible.modules.network.slxos.slxos_linkagg.get_config'
        )
        self._patch_load_config = patch(
            'ansible.modules.network.slxos.slxos_linkagg.load_config'
        )

        self._get_config = self._patch_get_config.start()
        self._load_config = self._patch_load_config.start()
    def setUp(self):
        super(TestNxosEvpnGlobalModule, self).setUp()
        self.mock_get_config = patch('ansible.modules.network.nxos.nxos_evpn_global.get_config')
        self.get_config = self.mock_get_config.start()

        self.mock_load_config = patch('ansible.modules.network.nxos.nxos_evpn_global.load_config')
        self.load_config = self.mock_load_config.start()

        self.mock_get_capabilities = patch('ansible.modules.network.nxos.nxos_evpn_global.get_capabilities')
        self.get_capabilities = self.mock_get_capabilities.start()
        self.get_capabilities.return_value = {'network_api': 'cliconf'}
Beispiel #31
0
    def setUp(self):
        super(TestMlnxosLinkaggModule, self).setUp()
        self.mock_get_config = patch.object(mlnxos_linkagg.MlnxosLinkAggModule,
                                            "_get_port_channels")
        self.get_config = self.mock_get_config.start()

        self.mock_load_config = patch(
            'ansible.module_utils.network.mlnxos.mlnxos.load_config')
        self.load_config = self.mock_load_config.start()
Beispiel #32
0
 def test_remove_partition_number_1(self):
     set_module_args({
         'device': '/dev/sdb',
         'number': 1,
         'state': 'absent',
     })
     with patch('ansible.modules.system.parted.get_device_info',
                return_value=parted_dict1):
         self.execute_module(changed=True, script='rm 1')
    def setUp(self):
        super(TestCiscoWlcConfigModule, self).setUp()

        self.mock_get_config = patch(
            'ansible.modules.network.aireos.aireos_config.get_config')
        self.get_config = self.mock_get_config.start()

        self.mock_load_config = patch(
            'ansible.modules.network.aireos.aireos_config.load_config')
        self.load_config = self.mock_load_config.start()

        self.mock_run_commands = patch(
            'ansible.modules.network.aireos.aireos_config.run_commands')
        self.run_commands = self.mock_run_commands.start()

        self.mock_save_config = patch(
            'ansible.modules.network.aireos.aireos_config.save_config')
        self.save_config = self.mock_save_config.start()
Beispiel #34
0
 def test_partition_already_exists(self):
     set_module_args({
         'device': '/dev/sdb',
         'number': 1,
         'state': 'present',
     })
     with patch('ansible.modules.system.parted.get_device_info',
                return_value=parted_dict1):
         self.execute_module(changed=False)
Beispiel #35
0
    def setUp(self):
        super(TestMlnxosMagpModule, self).setUp()
        self.mock_get_config = patch.object(mlnxos_magp.MlnxosMagpModule,
                                            "_get_magp_config")
        self.get_config = self.mock_get_config.start()

        self.mock_load_config = patch(
            'ansible.module_utils.network.mlnxos.mlnxos.load_config')
        self.load_config = self.mock_load_config.start()
    def test_module_utils_basic_ansible_module_set_owner_if_different(self):
        from ansible.module_utils import basic
        reload(basic)

        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('/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('/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)
Beispiel #37
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(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')
Beispiel #38
0
    def test_module_utils_basic_ansible_module_set_group_if_different(self):
        from ansible.module_utils import basic

        basic.MODULE_COMPLEX_ARGS = '{}'
        am = basic.AnsibleModule(argument_spec=dict(), )

        self.assertEqual(
            am.set_group_if_different('/path/to/file', None, True), True)
        self.assertEqual(
            am.set_group_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_group_if_different('/path/to/file', 0, False), True)
            m.assert_called_with('/path/to/file', -1, 0)

            def _mock_getgrnam(*args, **kwargs):
                mock_gr = MagicMock()
                mock_gr.gr_gid = 0
                return mock_gr

            m.reset_mock()
            with patch('grp.getgrnam', side_effect=_mock_getgrnam):
                self.assertEqual(
                    am.set_group_if_different('/path/to/file', 'root', False),
                    True)
                m.assert_called_with('/path/to/file', -1, 0)

            with patch('grp.getgrnam', side_effect=KeyError):
                self.assertRaises(SystemExit, am.set_group_if_different,
                                  '/path/to/file', 'root', False)

            m.reset_mock()
            am.check_mode = True
            self.assertEqual(
                am.set_group_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_group_if_different,
                              '/path/to/file', 'root', False)
Beispiel #39
0
    def setUp(self):

        self.cmd_out = {
            # os.read() is returning 'bytes', not strings
            sentinel.stdout: BytesIO(),
            sentinel.stderr: BytesIO(),
        }

        def mock_os_read(fd, nbytes):
            return self.cmd_out[fd].read(nbytes)

        def mock_select(rlist, wlist, xlist, timeout=1):
            return (rlist, [], [])

        def mock_os_chdir(path):
            if path == '/inaccessible':
                raise OSError(errno.EPERM, "Permission denied: '/inaccessible'")

        basic.MODULE_COMPLEX_ARGS = '{}'
        basic.MODULE_CONSTANTS = '{}'
        self.module = AnsibleModule(argument_spec=dict())
        self.module.fail_json = MagicMock(side_effect=SystemExit)

        self.os = patch('ansible.module_utils.basic.os').start()
        self.os.path.expandvars.side_effect = lambda x: x
        self.os.path.expanduser.side_effect = lambda x: x
        self.os.environ = {'PATH': '/bin'}
        self.os.getcwd.return_value = '/home/foo'
        self.os.path.isdir.return_value = True
        self.os.chdir.side_effect = mock_os_chdir
        self.os.read.side_effect = mock_os_read

        self.subprocess = patch('ansible.module_utils.basic.subprocess').start()
        self.cmd = Mock()
        self.cmd.returncode = 0
        self.cmd.stdin = OpenBytesIO()
        self.cmd.stdout.fileno.return_value = sentinel.stdout
        self.cmd.stderr.fileno.return_value = sentinel.stderr
        self.subprocess.Popen.return_value = self.cmd

        self.select = patch('ansible.module_utils.basic.select').start()
        self.select.select.side_effect = mock_select

        self.addCleanup(patch.stopall)
Beispiel #40
0
    def test_module_utils_basic_ansible_module_set_mode_if_different(self):
        from ansible.module_utils import basic

        basic.MODULE_COMPLEX_ARGS = '{}'
        am = basic.AnsibleModule(argument_spec=dict(), )

        mock_stat1 = MagicMock()
        mock_stat1.st_mode = 0o444
        mock_stat2 = MagicMock()
        mock_stat2.st_mode = 0o660

        with patch('os.lstat', side_effect=[mock_stat1]):
            self.assertEqual(
                am.set_mode_if_different('/path/to/file', None, True), True)
        with patch('os.lstat', side_effect=[mock_stat1]):
            self.assertEqual(
                am.set_mode_if_different('/path/to/file', None, False), False)

        with patch('os.lstat') as m:
            with patch('os.lchmod', return_value=None, create=True) as m_os:
                m.side_effect = [mock_stat1, mock_stat2, mock_stat2]
                self.assertEqual(
                    am.set_mode_if_different('/path/to/file', 0o660, False),
                    True)
                m_os.assert_called_with('/path/to/file', 0o660)

                m.side_effect = [mock_stat1, mock_stat2, mock_stat2]
                am._symbolic_mode_to_octal = MagicMock(return_value=0o660)
                self.assertEqual(
                    am.set_mode_if_different('/path/to/file', 'o+w,g+w,a-r',
                                             False), True)
                m_os.assert_called_with('/path/to/file', 0o660)

                m.side_effect = [mock_stat1, mock_stat2, mock_stat2]
                am._symbolic_mode_to_octal = MagicMock(side_effect=Exception)
                self.assertRaises(SystemExit, am.set_mode_if_different,
                                  '/path/to/file', 'o+w,g+w,a-r', False)

                m.side_effect = [mock_stat1, mock_stat2, mock_stat2]
                am.check_mode = True
                self.assertEqual(
                    am.set_mode_if_different('/path/to/file', 0o660, False),
                    True)
                am.check_mode = False
    def test_get_config_on_demand_capable_false(self):
        """Ensure we fail correctly if ASUP is not available on this platform"""
        self._set_args()

        expected = dict(asupCapable=True, onDemandCapable=False)
        asup = Asup()
        # Expecting an update
        with self.assertRaisesRegexp(AnsibleFailJson, r"not supported"):
            with mock.patch(self.REQ_FUNC, return_value=(200, expected)):
                asup.get_configuration()
Beispiel #42
0
    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()
Beispiel #43
0
    def test_output_matches(self):
        if sys.version_info >= (3, ):
            output_data = self.py3_output_data
        else:
            output_data = self.py2_output_data

        for msg, param in output_data.items():
            with patch('syslog.syslog', autospec=True) as mock_func:
                self.am.log(msg)
                mock_func.assert_called_once_with(syslog.LOG_INFO, param)
    def test_get_config(self):
        """Validate retrieving the ASUP configuration"""
        self._set_args()

        expected = dict(asupCapable=True, onDemandCapable=True)
        asup = Asup()

        with mock.patch(self.REQ_FUNC, return_value=(200, expected)):
            config = asup.get_configuration()
            self.assertEquals(config, expected)
Beispiel #45
0
 def test_create_new_partition(self):
     set_module_args({
         'device': '/dev/sdb',
         'number': 4,
         'state': 'present',
     })
     with patch('ansible.modules.system.parted.get_device_info',
                return_value=parted_dict1):
         self.execute_module(changed=True,
                             script='unit KiB mkpart primary 0% 100%')
    def setUp(self):
        super(TestIosLoggingModule, self).setUp()

        self.mock_get_config = patch(
            'ansible.modules.network.ios.ios_logging.get_config')
        self.get_config = self.mock_get_config.start()

        self.mock_load_config = patch(
            'ansible.modules.network.ios.ios_logging.load_config')
        self.load_config = self.mock_load_config.start()

        self.mock_get_capabilities = patch(
            'ansible.modules.network.ios.ios_logging.get_capabilities')
        self.get_capabilities = self.mock_get_capabilities.start()
        self.get_capabilities.return_value = {
            'device_info': {
                'network_os_version': '15.6(2)T'
            }
        }
 def test_no_selinux(self):
     with patch('ansible.module_utils.facts.system.selinux.HAVE_SELINUX',
                False):
         module = self._mock_module()
         fact_collector = self.collector_class()
         facts_dict = fact_collector.collect(module=module)
         self.assertIsInstance(facts_dict, dict)
         self.assertEqual(facts_dict['selinux']['status'],
                          'Missing selinux Python library')
         return facts_dict
Beispiel #48
0
    def setUp(self):
        self.enabled = False
        super(TestOnyxIgmpModule, self).setUp()
        self.mock_get_config = patch.object(onyx_igmp.OnyxIgmpModule,
                                            "_show_igmp")
        self.get_config = self.mock_get_config.start()

        self.mock_load_config = patch(
            'ansible.module_utils.network.onyx.onyx.load_config')
        self.load_config = self.mock_load_config.start()
Beispiel #49
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')
Beispiel #50
0
    def test_task_result_basic(self):
        mock_host = MagicMock()
        mock_task = MagicMock()

        # test loading a result with a dict
        tr = TaskResult(mock_host, mock_task, dict())

        # test loading a result with a JSON string
        with patch('ansible.parsing.dataloader.DataLoader.load') as p:
            tr = TaskResult(mock_host, mock_task, '{}')
    def setUp(self):
        super(TestMlnxosInterfaceModule, self).setUp()
        self.mock_get_config = patch.object(
            mlnxos_l2_interface.MlnxosL2InterfaceModule,
            "_get_switchport_config")
        self.get_config = self.mock_get_config.start()

        self.mock_load_config = patch(
            'ansible.module_utils.network.mlnxos.mlnxos.load_config')
        self.load_config = self.mock_load_config.start()
Beispiel #52
0
    def test_download_file(self):
        self.connection_mock.send.return_value = self._connection_response(
            'File content')

        open_mock = mock_open()
        with patch('%s.open' % BUILTINS_NAME, open_mock):
            self.ftd_plugin.download_file('/files/1', '/tmp/test.txt')

        open_mock.assert_called_once_with('/tmp/test.txt', 'wb')
        open_mock().write.assert_called_once_with(b'File content')
Beispiel #53
0
    def setUp(self):
        super(TestParted, self).setUp()

        self.module = parted_module
        self.mock_check_parted_label = (patch(
            'ansible.modules.system.parted.check_parted_label',
            return_value=False))
        self.check_parted_label = self.mock_check_parted_label.start()

        self.mock_parted = (patch('ansible.modules.system.parted.parted'))
        self.parted = self.mock_parted.start()

        self.mock_run_command = (
            patch('ansible.module_utils.basic.AnsibleModule.run_command'))
        self.run_command = self.mock_run_command.start()

        self.mock_get_bin_path = (
            patch('ansible.module_utils.basic.AnsibleModule.get_bin_path'))
        self.get_bin_path = self.mock_get_bin_path.start()
Beispiel #54
0
 def test_plugins__get_package_paths_with_package(self):
     # the _get_package_paths() call uses __import__ to load a
     # python library, and then uses the __file__ attribute of
     # the result for that to get the library path, so we mock
     # that here and patch the builtin to use our mocked result
     m = MagicMock()
     m.return_value.__file__ = '/path/to/my/test.py'
     pl = PluginLoader('test', 'foo.bar.bam', 'test', 'test_plugin')
     with patch('{0}.__import__'.format(BUILTINS), m):
         self.assertEqual(pl._get_package_paths(), ['/path/to/my/bar/bam'])
    def setUp(self):
        super(TestMlnxosMlagIplModule, self).setUp()
        self._mlag_enabled = True
        self.mock_get_config = patch.object(
            mlnxos_mlag_ipl.MlnxosMlagIplModule, "_show_mlag_data")
        self.get_config = self.mock_get_config.start()

        self.mock_load_config = patch(
            'ansible.module_utils.network.mlnxos.mlnxos.load_config')
        self.load_config = self.mock_load_config.start()
    def test_get_name(self):
        """Ensure we can successfully set the name"""
        self._set_args()

        expected = dict(name='y', status='online')
        namer = GlobalSettings()

        with mock.patch(self.REQ_FUNC, return_value=(200, expected)) as req:
            name = namer.get_name()
            self.assertEquals(name, expected['name'])
Beispiel #57
0
    def test_send_test_email_fail(self):
        """Ensure we fail if the test returned a failure status"""
        self._set_args(test=True)
        alerts = Alerts()

        ret_msg = 'fail'
        with self.assertRaisesRegexp(AnsibleFailJson, ret_msg):
            with mock.patch(self.REQ_FUNC, return_value=(200, dict(response=ret_msg))) as req:
                alerts.send_test_email()
                self.assertTrue(req.called)
    def setUp(self):
        super(TestOnyxPfcInterfaceModule, self).setUp()
        self._pfc_enabled = True
        self.mock_get_config = patch.object(
            onyx_pfc_interface.OnyxPfcInterfaceModule, "_get_pfc_config")
        self.get_config = self.mock_get_config.start()

        self.mock_load_config = patch(
            'ansible.module_utils.network.onyx.onyx.load_config')
        self.load_config = self.mock_load_config.start()
Beispiel #59
0
    def setUp(self):
        super(TestNxosConfigModule, self).setUp()

        self.mock_get_config = patch(
            'ansible.modules.network.nxos.nxos_config.get_config')
        self.get_config = self.mock_get_config.start()

        self.mock_load_config = patch(
            'ansible.modules.network.nxos.nxos_config.load_config')
        self.load_config = self.mock_load_config.start()

        self.mock_get_capabilities = patch(
            'ansible.modules.network.nxos.nxos_config.get_capabilities')
        self.get_capabilities = self.mock_get_capabilities.start()
        self.get_capabilities.return_value = {
            'device_info': {
                'network_os_platform': 'N9K-NXOSV'
            }
        }
Beispiel #60
0
    def test_upload_file_raises_exception_when_invalid_response(self):
        self.connection_mock.send.return_value = self._connection_response(
            'invalidJsonResponse')

        open_mock = mock_open()
        with patch('%s.open' % BUILTINS_NAME, open_mock):
            with self.assertRaises(ConnectionError) as res:
                self.ftd_plugin.upload_file('/tmp/test.txt', '/files')

        assert 'Invalid JSON response' in str(res.exception)