コード例 #1
0
    def test_config_file_error2(self):

        """ UT: nxos module:config method - Mandatory arg config_file not specified """

        config_file = None

        with patch(
            "salt.modules.nxos.show",
            autospec=True,
            side_effect=[initial_config_file, modified_config_file],
        ):
            mock_cmd = create_autospec(cp_module.get_file_str, return_value=False)
            with patch.dict(nxos_module.__salt__, {"cp.get_file_str": mock_cmd}):
                mock_cmd = create_autospec(
                    file_module.apply_template_on_contents,
                    return_value=template_engine_file_str_file,
                )
                with patch.dict(
                    nxos_module.__salt__, {"file.apply_template_on_contents": mock_cmd}
                ):
                    with patch(
                        "salt.modules.nxos._configure_device",
                        autospec=True,
                        return_value=config_result_file,
                    ):
                        with self.assertRaises(CommandExecutionError):
                            nxos_module.config(config_file=config_file)
コード例 #2
0
    def test_config_file(self):

        """ UT: nxos module:config method - Using config_file arg"""

        config_file = "salt://bgp_config.txt"
        expected_output = "COMMAND_LIST: feature bgp ; ! ; router bgp 55 ; address-family ipv4 unicast ; no client-to-client reflection ; additional-paths send\n\n--- \n+++ \n@@ -19,6 +19,7 @@\n feature bash-shell\n cfs eth distribute\n feature ngmvpn\n+feature bgp\n feature pim\n feature lldp\n \n@@ -233,6 +234,10 @@\n line console\n line vty\n boot nxos bootflash:/nxos.9.2.4.bin \n+router bgp 55\n+  address-family ipv4 unicast\n+    no client-to-client reflection\n+    additional-paths send\n \n no logging logfile\n no logging monitor\n"

        with patch(
            "salt.modules.nxos.show",
            autospec=True,
            side_effect=[initial_config_file, modified_config_file],
        ):
            mock_cmd = create_autospec(
                cp_module.get_file_str, return_value=config_input_file
            )
            with patch.dict(nxos_module.__salt__, {"cp.get_file_str": mock_cmd}):
                mock_cmd = create_autospec(
                    file_module.apply_template_on_contents,
                    return_value=template_engine_file_str_file,
                )
                with patch.dict(
                    nxos_module.__salt__, {"file.apply_template_on_contents": mock_cmd}
                ):
                    with patch(
                        "salt.modules.nxos._configure_device",
                        autospec=True,
                        return_value=config_result_file,
                    ):
                        result = nxos_module.config(config_file=config_file)
                        self.assertEqual(result, expected_output)
コード例 #3
0
ファイル: test_network.py プロジェクト: tqrg-bot/salt
 def test_dns_check(self):
     hosts = [
         {'host': '10.10.0.3',
          'port': '',
          'mocked': [(2, 1, 6, '', ('10.10.0.3', 0))],
          'ret': '10.10.0.3'},
         {'host': '10.10.0.3',
          'port': '1234',
          'mocked': [(2, 1, 6, '', ('10.10.0.3', 0))],
          'ret': '10.10.0.3'},
         {'host': '2001:0db8:85a3::8a2e:0370:7334',
          'port': '',
          'mocked': [(10, 1, 6, '', ('2001:db8:85a3::8a2e:370:7334', 0, 0, 0))],
          'ret': '[2001:db8:85a3::8a2e:370:7334]'},
         {'host': '2001:0db8:85a3::8a2e:370:7334',
          'port': '1234',
          'mocked': [(10, 1, 6, '', ('2001:db8:85a3::8a2e:370:7334', 0, 0, 0))],
          'ret': '[2001:db8:85a3::8a2e:370:7334]'},
         {'host': 'salt-master',
          'port': '1234',
          'mocked': [(2, 1, 6, '', ('127.0.0.1', 0))],
          'ret': '127.0.0.1'},
     ]
     for host in hosts:
         with patch.object(socket, 'getaddrinfo', create_autospec(socket.getaddrinfo, return_value=host['mocked'])):
             with patch('socket.socket', create_autospec(socket.socket)):
                 ret = network.dns_check(host['host'], host['port'])
                 self.assertEqual(ret, host['ret'])
コード例 #4
0
def fake_install(request):
    fake_install = create_autospec(npmmod.install, return_value=request.param)
    with patch.dict(
            npm.__salt__,
        {
            "npm.list": create_autospec(npmmod.list_, return_value={}),
            "npm.install": fake_install,
        },
    ):
        yield fake_install
コード例 #5
0
ファイル: test_network.py プロジェクト: tqrg-bot/salt
    def test_dns_check_errors(self):
        with patch.object(socket, 'getaddrinfo', create_autospec(socket.getaddrinfo, return_value=[])):
            with self.assertRaisesRegex(salt.exceptions.SaltSystemExit,
                                        "DNS lookup or connection check of 'foo' failed"):
                network.dns_check('foo', '1')

        with patch.object(socket, 'getaddrinfo', create_autospec(socket.getaddrinfo, side_effect=TypeError)):
            with self.assertRaisesRegex(salt.exceptions.SaltSystemExit,
                                        "Invalid or unresolveable address"):
                network.dns_check('foo', '1')
コード例 #6
0
ファイル: test_metadata_gce.py プロジェクト: whytewolf/salt
def test_metadata_virtual():
    with patch(
            "salt.utils.http.query",
            create_autospec(
                http.query,
                autospec=True,
                return_value={"error": "[Errno -2] Name or service not known"},
            ),
    ):
        assert metadata.__virtual__() is False
    with patch(
            "salt.utils.http.query",
            create_autospec(
                http.query,
                autospec=True,
                return_value={
                    "body": "test",
                    "headers": {
                        "Metadata-Flavor": "Google"
                    },
                    "status": 200,
                },
            ),
    ):
        assert metadata.__virtual__() is True
    with patch(
            "salt.utils.http.query",
            create_autospec(
                http.query,
                autospec=True,
                return_value={
                    "body": "test",
                    "headers": {
                        "Metadata-Flavor": "Google"
                    },
                    "status": 404,
                },
            ),
    ):
        assert metadata.__virtual__() is False
    with patch(
            "salt.utils.http.query",
            create_autospec(
                http.query,
                autospec=True,
                return_value={
                    "body": "test",
                    "headers": {},
                    "code": 200
                },
            ),
    ):
        assert metadata.__virtual__() is False
コード例 #7
0
def mocks():
    return {
        "postgres.role_get":
        create_autospec(postgres.role_get, return_value=None),
        "postgres.user_exists":
        create_autospec(postgres.user_exists, return_value=False),
        "postgres.group_create":
        create_autospec(postgres.group_create, return_value=True),
        "postgres.group_update":
        create_autospec(postgres.group_update, return_value=True),
        "postgres.group_remove":
        create_autospec(postgres.group_remove, return_value=True),
    }
コード例 #8
0
 def test_dns_check(self):
     hosts = [
         {
             "host": "10.10.0.3",
             "port": "",
             "mocked": [(2, 1, 6, "", ("10.10.0.3", 0))],
             "ret": "10.10.0.3",
         },
         {
             "host": "10.10.0.3",
             "port": "1234",
             "mocked": [(2, 1, 6, "", ("10.10.0.3", 0))],
             "ret": "10.10.0.3",
         },
         {
             "host":
             "2001:0db8:85a3::8a2e:0370:7334",
             "port":
             "",
             "mocked":
             [(10, 1, 6, "", ("2001:db8:85a3::8a2e:370:7334", 0, 0, 0))],
             "ret":
             "[2001:db8:85a3::8a2e:370:7334]",
         },
         {
             "host":
             "2001:0db8:85a3::8a2e:370:7334",
             "port":
             "1234",
             "mocked":
             [(10, 1, 6, "", ("2001:db8:85a3::8a2e:370:7334", 0, 0, 0))],
             "ret":
             "[2001:db8:85a3::8a2e:370:7334]",
         },
         {
             "host": "salt-master",
             "port": "1234",
             "mocked": [(2, 1, 6, "", ("127.0.0.1", 0))],
             "ret": "127.0.0.1",
         },
     ]
     for host in hosts:
         with patch.object(
                 socket,
                 "getaddrinfo",
                 create_autospec(socket.getaddrinfo,
                                 return_value=host["mocked"]),
         ):
             with patch("socket.socket", create_autospec(socket.socket)):
                 ret = network.dns_check(host["host"], host["port"])
                 self.assertEqual(ret, host["ret"])
コード例 #9
0
    def test_config_nxos_error_ssh(self):

        """ UT: nxos module:config method - nxos device error over ssh transport """

        commands = ["feature bgp", "router bgp 57"]
        config_result = [
            ["feature bgp", "router bgp 57"],
            "bgp instance is already running; Tag is 55",
        ]
        expected_output = "COMMAND_LIST: feature bgp ; router bgp 57\nbgp instance is already running; Tag is 55\n--- \n+++ \n@@ -19,7 +19,6 @@\n feature bash-shell\n cfs eth distribute\n feature ngmvpn\n-feature ospf\n feature pim\n feature lldp\n \n"

        with patch(
            "salt.modules.nxos.show",
            autospec=True,
            side_effect=[initial_config[0], modified_config[0]],
        ):
            mock_cmd = create_autospec(
                file_module.apply_template_on_contents,
                return_value=template_engine_file_str,
            )
            with patch.dict(
                nxos_module.__salt__, {"file.apply_template_on_contents": mock_cmd}
            ):
                with patch(
                    "salt.modules.nxos._configure_device",
                    autospec=True,
                    return_value=config_result,
                ):
                    result = nxos_module.config(commands)
                    self.assertEqual(result, expected_output)
コード例 #10
0
    def test_config_commands_string(self):

        """ UT: nxos module:config method - Using commands arg and output is string"""

        commands = "no feature ospf"
        expected_output = "COMMAND_LIST: no feature ospf\n\n--- \n+++ \n@@ -19,7 +19,6 @@\n feature bash-shell\n cfs eth distribute\n feature ngmvpn\n-feature ospf\n feature pim\n feature lldp\n \n"

        with patch(
            "salt.modules.nxos.show",
            autospec=True,
            side_effect=[initial_config[0], modified_config[0]],
        ):
            mock_cmd = create_autospec(
                file_module.apply_template_on_contents,
                return_value=template_engine_file_str,
            )
            with patch.dict(
                nxos_module.__salt__, {"file.apply_template_on_contents": mock_cmd}
            ):
                with patch(
                    "salt.modules.nxos._configure_device",
                    autospec=True,
                    return_value=config_result,
                ):
                    result = nxos_module.config(commands)
                    self.assertEqual(result, expected_output)
コード例 #11
0
def mock_module(mod, sut=None):
    if sut is None:
        sut = [None]

    mock = create_autospec(mod)

    # we need to provide a '__globals__' so functions being tested behave correctly.
    mock_globals = {}

    # exclude the system under test
    for name in sut:
        attr = getattr(mod, name)
        if isinstance(attr, types.FunctionType):
            attr = copy_func(attr, mock_globals)
        setattr(mock, name, attr)

    # fully populate our mock_globals
    for name in mod.__dict__:
        if name in mock.__dict__:
            mock_globals[name] = mock.__dict__[name]
        elif type(getattr(mod, name)) is type(types):  # is a module
            mock_globals[name] = getattr(mock, name)
        else:
            mock_globals[name] = mod.__dict__[name]

    return mock
コード例 #12
0
ファイル: test_metadata_gce.py プロジェクト: whytewolf/salt
def test_metadata_gce_search():
    def mock_http(url="", headers=False, header_list=None):
        metadata_vals = {
            "http://169.254.169.254/computeMetadata/v1/": {
                "body": "instance/\nproject/",
                "headers": {
                    "Content-Type": "text/plain",
                    "Metadata-Flavor": "Google"
                },
            },
            "http://169.254.169.254/computeMetadata/v1/instance/": {
                "body": "test",
                "headers": {
                    "Content-Type": "text/plain",
                    "Metadata-Flavor": "Google"
                },
            },
            "http://169.254.169.254/computeMetadata/v1/instance/test": {
                "body": "fulltest",
                "headers": {
                    "Content-Type": "application/octet-stream",
                    "Metadata-Flavor": "Google",
                },
            },
        }

        return metadata_vals[url]

    with patch(
            "salt.utils.http.query",
            create_autospec(http.query, autospec=True, side_effect=mock_http),
    ):
        assert metadata.metadata() == {"instance": {"test": "fulltest"}}
コード例 #13
0
    def test_system_info(self):

        """ UT: nxos module:system_info method """

        expected_grains = {
            "software": {
                "BIOS": "version 08.36",
                "NXOS": "version 9.2(1)",
                "BIOS compile time": "06/07/2019",
                "NXOS image file is": "bootflash:///nxos.9.2.1.bin",
                "NXOS compile time": "7/17/2018 16:00:00 [07/18/2018 00:21:19]",
            },
            "hardware": {"Device name": "n9k-device", "bootflash": "53298520 kB"},
            "plugins": ["Core Plugin", "Ethernet Plugin"],
        }
        with patch.dict(
            nxos_module.__salt__,
            {
                "utils.nxos.system_info": create_autospec(
                    nxos_utils.system_info, return_value=n9k_grains
                )
            },
        ):
            with patch(
                "salt.modules.nxos.show_ver", return_value=n9k_show_ver, autospec=True
            ):
                result = nxos_module.system_info()
                self.assertEqual(result, expected_grains)
コード例 #14
0
    def test_test_addrs(self):
        # subset of real data from getaddrinfo against saltstack.com
        addrinfo = [
            (30, 2, 17, "", ("2600:9000:21eb:a800:8:1031:abc0:93a1", 0, 0, 0)),
            (30, 1, 6, "", ("2600:9000:21eb:a800:8:1031:abc0:93a1", 0, 0, 0)),
            (30, 2, 17, "", ("2600:9000:21eb:b400:8:1031:abc0:93a1", 0, 0, 0)),
            (30, 1, 6, "", ("2600:9000:21eb:b400:8:1031:abc0:93a1", 0, 0, 0)),
            (2, 1, 6, "", ("13.35.99.52", 0)),
            (2, 2, 17, "", ("13.35.99.85", 0)),
            (2, 1, 6, "", ("13.35.99.85", 0)),
            (2, 2, 17, "", ("13.35.99.122", 0)),
        ]
        with patch("socket.socket", create_autospec(socket.socket)) as s:
            # we connect to the first address
            addrs = network._test_addrs(addrinfo, 80)
            self.assertTrue(len(addrs) == 1)
            self.assertTrue(addrs[0] == addrinfo[0][4][0])

            # the first lookup fails, succeeds on next check
            s.side_effect = [socket.error, MagicMock()]
            addrs = network._test_addrs(addrinfo, 80)
            self.assertTrue(len(addrs) == 1)
            self.assertTrue(addrs[0] == addrinfo[2][4][0])

            # nothing can connect, but we've eliminated duplicates
            s.side_effect = socket.error
            addrs = network._test_addrs(addrinfo, 80)
            self.assertTrue(len(addrs) == 5)
コード例 #15
0
    def test_config_commands_template_none(self):
        """UT: nxos module:config method - Template engine is None"""

        commands = ["no feature ospf", ["no feature ospf"]]
        expected_output = (
            "COMMAND_LIST: no feature ospf\n\n--- \n+++ \n@@ -19,7 +19,6 @@\n feature"
            " bash-shell\n cfs eth distribute\n feature ngmvpn\n-feature ospf\n feature"
            " pim\n feature lldp\n \n")

        for cmd_set in commands:
            with patch(
                    "salt.modules.nxos.show",
                    autospec=True,
                    side_effect=[initial_config, modified_config],
            ):
                mock_cmd = create_autospec(
                    file_module.apply_template_on_contents,
                    return_value=template_engine_file_str,
                )
                with patch.dict(nxos_module.__salt__,
                                {"file.apply_template_on_contents": mock_cmd}):
                    with patch(
                            "salt.modules.nxos._configure_device",
                            autospec=True,
                            return_value=config_result,
                    ):
                        result = nxos_module.config(cmd_set,
                                                    template_engine=None)
                        self.assertEqual(result, expected_output)
コード例 #16
0
ファイル: test_restartcheck.py プロジェクト: zhihuacui/salt
def test_when_nilinuxrt_and_not_kernel_modules_changed_or_sysapi_files_changed_and_reboot_required_witnessed_then_reboot_should_be_required(
):
    expected_result = "System restart required.\n\n"
    restart_required = True
    current_kernel = "fnord"

    patch_grains = patch.dict(restartcheck.__grains__,
                              {"os_family": "NILinuxRT"})
    patch_kernel_versions = patch(
        "salt.modules.restartcheck._kernel_versions_nilrt",
        autospec=True,
        return_value=[current_kernel],
    )
    patch_salt = patch.dict(
        restartcheck.__salt__,
        {
            "cmd.run":
            create_autospec(cmdmod.run, return_value=current_kernel),
            "system.get_reboot_required_witnessed":
            create_autospec(
                system.get_reboot_required_witnessed,
                return_value=restart_required,
            ),
            "service.get_running":
            create_autospec(service.get_running, return_value=[]),
        },
    )
    patch_kernel_mod_changed = patch(
        "salt.modules.restartcheck._kernel_modules_changed_nilrt",
        autospec=True,
        return_value=False,
    )
    patch_sysapi_changed = patch(
        "salt.modules.restartcheck._sysapi_changed_nilrt",
        autospec=True,
        return_value=False,
    )
    patch_del_files = patch(
        "salt.modules.restartcheck._deleted_files",
        autospec=True,
        return_value=[],
    )

    with patch_grains, patch_kernel_versions, patch_salt, patch_sysapi_changed, patch_kernel_mod_changed, patch_del_files:
        actual_result = restartcheck.restartcheck()
    assert actual_result == expected_result
コード例 #17
0
ファイル: test_commands.py プロジェクト: auchytil/dnf
    def test_makecache_timer_battery(self, _on_ac_power):
        cmd = dnf.cli.commands.MakeCacheCommand(self.cli)
        cmd.base.logger = mock.create_autospec(cmd.base.logger)
        self.yumbase.conf.metadata_timer_sync = 5

        self.assertFalse(self._do_makecache(cmd))
        msg = u'Metadata timer caching disabled when running on a battery.'
        self.assertLastInfo(cmd, msg)
コード例 #18
0
ファイル: test_history.py プロジェクト: MattSturgeon/dnf
    def test_close(self):
        """Test close."""
        yum_history = mock.create_autospec(dnf.yum.history.YumHistory)
        history = self._create_wrapper(yum_history)

        history.close()

        self.assertEqual(yum_history.close.mock_calls, [mock.call()])
コード例 #19
0
ファイル: test_update.py プロジェクト: mavit/dnf
    def test_update_not_found(self):
        self.base._sack = tests.support.mock_sack('updates')
        self.base._goal = goal = mock.create_autospec(dnf.goal.Goal)

        with self.assertRaises(dnf.exceptions.MarkingError) as context:
            self.base.upgrade('non-existent')
        self.assertEqual(context.exception.pkg_spec, 'non-existent')
        self.assertEqual(goal.mock_calls, [])
コード例 #20
0
ファイル: test_history.py プロジェクト: yavor-atanasov/dnf
    def test_close(self):
        """Test close."""
        yum_history = mock.create_autospec(dnf.yum.history.YumHistory)
        history = self._create_wrapper(yum_history)

        history.close()

        self.assertEqual(yum_history.close.mock_calls, [mock.call()])
コード例 #21
0
ファイル: test_update.py プロジェクト: zhengrq-fnst/dnf
    def test_update_not_found(self):
        self.base._sack = tests.support.mock_sack('updates')
        self.base._goal = goal = mock.create_autospec(dnf.goal.Goal)

        with self.assertRaises(dnf.exceptions.MarkingError) as context:
            self.base.upgrade('non-existent')
        self.assertEqual(context.exception.pkg_spec, 'non-existent')
        self.assertEqual(goal.mock_calls, [])
コード例 #22
0
    def test_makecache_timer_battery(self, _on_ac_power):
        cmd = dnf.cli.commands.MakeCacheCommand(self.cli)
        cmd.base.logger = mock.create_autospec(cmd.base.logger)
        self.base.conf.metadata_timer_sync = 5

        self.assertFalse(self._do_makecache(cmd))
        msg = u'Metadata timer caching disabled when running on a battery.'
        self.assertLastInfo(cmd, msg)
コード例 #23
0
ファイル: test_args.py プロジェクト: yvwulei/salt
    def test_argspec_report(self):
        def _test_spec(arg1, arg2, kwarg1=None):
            pass

        sys_mock = create_autospec(_test_spec)
        test_functions = {'test_module.test_spec': sys_mock}
        ret = salt.utils.args.argspec_report(test_functions, 'test_module.test_spec')
        self.assertDictEqual(ret, {'test_module.test_spec':
                                       {'kwargs': True, 'args': None, 'defaults': None, 'varargs': True}})
コード例 #24
0
ファイル: test_update.py プロジェクト: mavit/dnf
 def test_update_not_installed(self, logger):
     """ Updating an uninstalled package is a not valid operation. """
     self.base._goal = goal = mock.create_autospec(dnf.goal.Goal)
     # no "mrkite" installed:
     with self.assertRaises(dnf.exceptions.MarkingError) as context:
         self.base.upgrade("mrkite")
     self.assertEqual(logger.mock_calls, [
         mock.call(u'Package %s available, but not installed.', u'mrkite')])
     self.assertEqual(context.exception.pkg_spec, 'mrkite')
     self.assertEqual(goal.mock_calls, [])
コード例 #25
0
ファイル: test_history.py プロジェクト: yavor-atanasov/dnf
    def test_context_manager(self):
        """Test whether _HistoryWrapper can be used as a context manager."""
        yum_history = mock.create_autospec(dnf.yum.history.YumHistory)
        history = self._create_wrapper(yum_history)

        with history as instance:
            pass

        self.assertIs(instance, history)
        self.assertEqual(yum_history.close.mock_calls, [mock.call()])
コード例 #26
0
ファイル: test_history.py プロジェクト: MattSturgeon/dnf
    def test_context_manager(self):
        """Test whether _HistoryWrapper can be used as a context manager."""
        yum_history = mock.create_autospec(dnf.yum.history.YumHistory)
        history = self._create_wrapper(yum_history)

        with history as instance:
            pass

        self.assertIs(instance, history)
        self.assertEqual(yum_history.close.mock_calls, [mock.call()])
コード例 #27
0
 def test_update_not_installed(self, logger):
     """ Updating an uninstalled package is a not valid operation. """
     base = support.MockBase("main")
     base._goal = goal = mock.create_autospec(dnf.goal.Goal)
     # no "mrkite" installed:
     with self.assertRaises(dnf.exceptions.MarkingError) as context:
         base.upgrade("mrkite")
     self.assertEqual(logger.mock_calls, [
         mock.call(u'Package %s available, but not installed.', u'mrkite')])
     self.assertEqual(context.exception.pkg_spec, 'mrkite')
     self.assertEqual(goal.mock_calls, [])
コード例 #28
0
    def test_nxapi_request_proxy(self):
        """UT: nxos module:_nxapi_request method - proxy"""

        with patch("salt.utils.platform.is_proxy",
                   autospec=True,
                   return_value=True):
            mock_request = create_autospec(nxos_utils.nxapi_request,
                                           return_value="router_data")
            with patch.dict(nxos_module.__proxy__,
                            {"nxos._nxapi_request": mock_request}):
                result = nxos_module._nxapi_request("show version")
                self.assertEqual(result, "router_data")
コード例 #29
0
ファイル: test_network.py プロジェクト: tqrg-bot/salt
 def test_dns_check_ipv6_filter(self):
     # raise exception to skip everything after the getaddrinfo call
     with patch.object(socket, 'getaddrinfo',
                       create_autospec(socket.getaddrinfo, side_effect=Exception)) as getaddrinfo:
         for ipv6, param in [
             (None, socket.AF_UNSPEC),
             (True, socket.AF_INET6),
             (False, socket.AF_INET),
         ]:
             with self.assertRaises(Exception):
                 network.dns_check('foo', '1', ipv6=ipv6)
             getaddrinfo.assert_called_with('foo', '1', param, socket.SOCK_STREAM)
コード例 #30
0
ファイル: test_cli.py プロジェクト: xiongchiamiov/dnf
    def setUp(self):
        self._base = dnf.cli.cli.BaseCli()
        self._base._sack = support.mock_sack('main', 'updates')
        self._base._goal = dnf.goal.Goal(self._base.sack)

        main_repo = support.MockRepo('main', None)
        main_repo.metadata = mock.Mock(comps_fn=support.COMPS_PATH)
        main_repo.enable()
        self._base.repos.add(main_repo)

        self._base.logger = mock.create_autospec(self._base.logger)
        self._base.output.term = support.MockTerminal()
        self._base.downgrade = mock.Mock(wraps=self._base.downgrade)
コード例 #31
0
ファイル: test_cli.py プロジェクト: hutarova/dnf
    def setUp(self):
        self._base = dnf.cli.cli.BaseCli()
        self._base._sack = support.mock_sack("main", "updates")
        self._base._goal = dnf.goal.Goal(self._base.sack)

        main_repo = support.MockRepo("main", None)
        main_repo.metadata = mock.Mock(comps_fn=support.COMPS_PATH)
        main_repo.enable()
        self._base.repos.add(main_repo)

        self._base.logger = mock.create_autospec(self._base.logger)
        self._base.output.term = support.MockTerminal()
        self._base.downgrade = mock.Mock(wraps=self._base.downgrade)
コード例 #32
0
ファイル: test_nxos.py プロジェクト: steverweber/salt
    def test_bad__init_nxapi(self):
        class NXAPIException(Exception):
            pass

        nxapi_request = create_autospec(nxos_utils.nxapi_request,
                                        side_effect=NXAPIException)

        with patch("salt.proxy.nxos.__utils__",
                   {"nxos.nxapi_request": nxapi_request}):
            with patch("salt.proxy.nxos.log", autospec=True) as log:
                with self.assertRaises(NXAPIException):
                    nxos_proxy._init_nxapi({"proxy": {"host": "HOST"}})
                log.error.assert_called()
コード例 #33
0
    def test_nxapi_request_no_proxy(self):
        """UT: nxos module:_nxapi_request method - no proxy"""

        with patch("salt.utils.platform.is_proxy",
                   autospec=True,
                   return_value=False):
            mock_cmd = MagicMock(return_value={"nxos": {"save_config": False}})
            with patch.dict(nxos_module.__salt__, {"config.get": mock_cmd}):
                mock_request = create_autospec(nxos_utils.nxapi_request)
                with patch.dict(nxos_module.__utils__,
                                {"nxos.nxapi_request": mock_request}):
                    result = nxos_module._nxapi_request("show version")
                    self.assertEqual(result, mock_request.return_value)
                    mock_request.assert_called_with("show version", "cli_conf",
                                                    **mock_cmd.return_value)
コード例 #34
0
    def test_cmd_any_function(self):
        """UT: nxos module:cmd method - check_role function"""

        with patch.dict(
                nxos_module.__salt__,
            {
                "nxos.check_role":
                create_autospec(nxos_module.check_role, return_value=True)
            },
        ):
            result = nxos_module.cmd(
                "check_role",
                "salt_test",
                "network-admin",
                encrypted=True,
                __pub_fun="nxos.cmd",
            )
            self.assertTrue(result)
コード例 #35
0
ファイル: test_output.py プロジェクト: DNIWE-Systems/dnf
    def test_mode_nontty(self):
        """Test whether all modes are properly set if the stream is not a tty.

        It also ensures that all the values are unicode strings.

        """
        nontty = mock.create_autospec(io.IOBase)
        nontty.isatty.return_value = False

        term = dnf.cli.output.Term(nontty)

        self.assertEqual(term.MODE,
                         {u'blink': u'',
                          u'bold': u'',
                          u'dim': u'',
                          u'normal': u'',
                          u'reverse': u'',
                          u'underline': u''})
コード例 #36
0
ファイル: test_nxos.py プロジェクト: steverweber/salt
    def test__init_nxapi(self):
        """ UT: nxos module:_init_nxapi method - successful connectinon """

        opts = {"proxy": {"arg1": None}}
        nxapi_request = create_autospec(nxos_utils.nxapi_request,
                                        return_value="data")

        with patch("salt.proxy.nxos.DEVICE_DETAILS", {}) as device_details:
            with patch("salt.proxy.nxos.__utils__",
                       {"nxos.nxapi_request": nxapi_request}):
                result = nxos_proxy._init_nxapi(opts)

                self.assertTrue(device_details["initialized"])
                self.assertTrue(device_details["up"])
                self.assertTrue(device_details["save_config"])
                self.assertTrue(result)

                nxapi_request.assert_called_with("show clock", **opts["proxy"])
コード例 #37
0
ファイル: test_nxos.py プロジェクト: steverweber/salt
    def test__nxapi_request_connect(self):
        """ UT: nxos module:_nxapi_request method """

        commands = "show version"
        nxapi_request = create_autospec(nxos_utils.nxapi_request,
                                        return_value="data")

        with patch("salt.proxy.nxos.DEVICE_DETAILS",
                   {"conn_args": {
                       "arg1": None
                   }}):
            with patch("salt.proxy.nxos.__utils__",
                       {"nxos.nxapi_request": nxapi_request}):
                result = nxos_proxy._nxapi_request(commands)
                self.assertEqual("data", result)
                nxapi_request.assert_called_with(commands,
                                                 method="cli_conf",
                                                 arg1=None)
コード例 #38
0
ファイル: test_output.py プロジェクト: DNIWE-Systems/dnf
    def test_mode_tty_incapable(self):
        """Test whether modes correct if the stream is an incapable tty.

        It also ensures that all the values are unicode strings.

        """
        tty = mock.create_autospec(io.IOBase)
        tty.isatty.return_value = True

        with mock.patch('curses.tigetstr', autospec=True, return_value=None):
            term = dnf.cli.output.Term(tty)

        self.assertEqual(term.MODE,
                         {u'blink': u'',
                          u'bold': u'',
                          u'dim': u'',
                          u'normal': u'',
                          u'reverse': u'',
                          u'underline': u''})
コード例 #39
0
ファイル: test_output.py プロジェクト: DNIWE-Systems/dnf
    def test_mode_tty(self):
        """Test whether all modes are properly set if the stream is a tty.

        It also ensures that all the values are unicode strings.

        """
        tty = mock.create_autospec(io.IOBase)
        tty.isatty.return_value = True

        tigetstr = lambda name: '<cap_%(name)s>' % locals()
        with mock.patch('curses.tigetstr', autospec=True, side_effect=tigetstr):
            term = dnf.cli.output.Term(tty)

        self.assertEqual(term.MODE,
                         {u'blink': tigetstr(u'blink'),
                          u'bold': tigetstr(u'bold'),
                          u'dim': tigetstr(u'dim'),
                          u'normal': tigetstr(u'sgr0'),
                          u'reverse': tigetstr(u'rev'),
                          u'underline': tigetstr(u'smul')})
コード例 #40
0
ファイル: test_commands.py プロジェクト: auchytil/dnf
    def test_makecache_timer(self, _on_ac_power):
        cmd = dnf.cli.commands.MakeCacheCommand(self.cli)
        cmd.base.logger = mock.create_autospec(cmd.base.logger)

        self.yumbase.conf.metadata_timer_sync = 0
        self.assertFalse(self._do_makecache(cmd))
        self.assertLastInfo(cmd, u'Metadata timer caching disabled.')

        self.yumbase.conf.metadata_timer_sync = 5 # resync after 5 seconds
        self.yumbase._persistor.since_last_makecache = mock.Mock(return_value=3)
        self.assertFalse(self._do_makecache(cmd))
        self.assertLastInfo(cmd, u'Metadata cache refreshed recently.')

        self.yumbase._persistor.since_last_makecache = mock.Mock(return_value=10)
        self.yumbase._sack = 'nonempty'
        r = support.MockRepo("glimpse", None)
        self.yumbase.repos.add(r)

        # regular case 1: metadata is already expired:
        r.metadata_expire_in = mock.Mock(return_value=(False, 0))
        r.sync_strategy = dnf.repo.SYNC_TRY_CACHE
        self.assertTrue(self._do_makecache(cmd))
        self.assertLastInfo(cmd, u'Metadata cache created.')
        self.assertEqual(r.sync_strategy, dnf.repo.SYNC_EXPIRED)

        # regular case 2: metadata is cached and will expire later than
        # metadata_timer_sync:
        r.metadata_expire_in = mock.Mock(return_value=(True, 100))
        r.sync_strategy = dnf.repo.SYNC_TRY_CACHE
        self.assertTrue(self._do_makecache(cmd))
        self.assertLastInfo(cmd, u'Metadata cache created.')
        self.assertEqual(r.sync_strategy, dnf.repo.SYNC_TRY_CACHE)

        # regular case 3: metadata is cached but will eqpire before
        # metadata_timer_sync:
        r.metadata_expire_in = mock.Mock(return_value=(True, 4))
        r.sync_strategy = dnf.repo.SYNC_TRY_CACHE
        self.assertTrue(self._do_makecache(cmd))
        self.assertLastInfo(cmd, u'Metadata cache created.')
        self.assertEqual(r.sync_strategy, dnf.repo.SYNC_EXPIRED)
コード例 #41
0
ファイル: test_downgrade.py プロジェクト: mavit/dnf
 def setUp(self):
     super(DowngradeTest2, self).setUp()
     self.base._goal = mock.create_autospec(dnf.goal.Goal)
コード例 #42
0
ファイル: test_downgrade.py プロジェクト: edynox/dnf
 def setUp(self):
     self._base = support.MockBase()
     self._base._sack = support.mock_sack('main')
     self._base._goal = self._goal = mock.create_autospec(dnf.goal.Goal)
コード例 #43
0
ファイル: test_distsync.py プロジェクト: DNIWE-Systems/dnf
 def setUp(self):
     self._base = support.BaseCliStub()
     self._base._sack = support.mock_sack('main', 'updates')
     self._base._goal = dnf.goal.Goal(self._base.sack)
     self._base.logger = mock.create_autospec(self._base.logger)