예제 #1
0
    def test_version(self, popen_mock):
        '''
        Test that salt.utils.systemd.booted() returns True when minion is
        systemd-booted.
        '''
        _version = 231
        output = 'systemd {0}\n-SYSVINIT'.format(_version)
        popen_mock.return_value = Mock(communicate=lambda *args, **kwargs:
                                       (output, None),
                                       pid=lambda: 12345,
                                       retcode=0)

        # Test without context dict passed
        self.assertEqual(_systemd.version(), _version)
        # Test that context key is set when context dict is passed
        context = {}
        self.assertTrue(_systemd.version(context))
        self.assertEqual(context, {'salt.utils.systemd.version': _version})
예제 #2
0
 def test_has_scope_version_parse_problem(self, popen_mock):
     '''
     Test the case where the system is systemd-booted, but we failed to
     parse the "systemctl --version" output.
     '''
     popen_mock.return_value = Mock(communicate=lambda *args, **kwargs:
                                    ('invalid', None),
                                    pid=lambda: 12345,
                                    retcode=0)
     with patch('os.stat', side_effect=_booted_effect):
         # Test without context dict passed
         self.assertFalse(_systemd.has_scope())
         # Test that context key is set when context dict is passed. A
         # failure to parse the systemctl output should not set a context
         # key, so it should not be present in the context dict.
         context = {}
         self.assertFalse(_systemd.has_scope(context))
         self.assertEqual(context, {'salt.utils.systemd.booted': True})
예제 #3
0
    def test_diskusage_windows_double_slash(self):
        """
        This tests original behavior (C:\\)
        """
        disk_usage_mock = Mock(return_value=WINDOWS_STUB_DISK_USAGE)
        with patch("salt.utils.platform.is_windows", MagicMock(return_value=True)):
            with patch(
                "psutil.disk_partitions",
                MagicMock(return_value=WINDOWS_STUB_DISK_PARTITION),
            ), patch("psutil.disk_usage", disk_usage_mock):
                config = [{"C:\\\\": "50%"}]

                ret = diskusage.validate(config)

                self.assertEqual(ret, (True, "Valid beacon configuration"))

                ret = diskusage.beacon(config)
                self.assertEqual(ret, [{"diskusage": 50, "mount": "C:\\"}])
예제 #4
0
    def test_device_no_repeat_with_not_found_state(self):
        config = {'states': ['offline'], 'battery_low': 30}

        out = [
            'List of devices attached\nHTC\tdevice', '25',
            'List of devices attached\nHTC\tdevice', '25'
        ]
        mock = Mock(side_effect=out)
        with patch.dict(adb.__salt__, {'cmd.run': mock}):
            ret = adb.beacon(config)
            self.assertEqual(ret, [{
                'device': 'HTC',
                'battery_level': 25,
                'tag': 'battery_low'
            }])

            ret = adb.beacon(config)
            self.assertEqual(ret, [])
예제 #5
0
    def test_diskusage_windows_double_slash(self):
        '''
        This tests original behavior (C:\\)
        '''
        disk_usage_mock = Mock(return_value=WINDOWS_STUB_DISK_USAGE)
        with patch('salt.utils.platform.is_windows',
                   MagicMock(return_value=True)):
            with patch('psutil.disk_partitions',
                       MagicMock(return_value=WINDOWS_STUB_DISK_PARTITION)), \
                    patch('psutil.disk_usage', disk_usage_mock):
                config = [{'C:\\\\': '50%'}]

                ret = diskusage.validate(config)

                self.assertEqual(ret, (True, 'Valid beacon configuration'))

                ret = diskusage.beacon(config)
                self.assertEqual(ret, [{'diskusage': 50, 'mount': 'C:\\'}])
예제 #6
0
    def test_diskusage_windows_lowercase(self):
        r'''
        This tests lowercase drive letter (c:\)
        '''
        disk_usage_mock = Mock(return_value=WINDOWS_STUB_DISK_USAGE)
        with patch('salt.utils.platform.is_windows',
                   MagicMock(return_value=True)):
            with patch('psutil.disk_partitions',
                       MagicMock(return_value=WINDOWS_STUB_DISK_PARTITION)), \
                 patch('psutil.disk_usage', disk_usage_mock):
                config = [{'c:\\': '50%'}]

                ret = diskusage.validate(config)

                self.assertEqual(ret, (True, 'Valid beacon configuration'))

                ret = diskusage.beacon(config)
                self.assertEqual(ret, [{'diskusage': 50, 'mount': 'C:\\'}])
예제 #7
0
    def test_weird_batteries(self):
        config = [{"states": ["device"], "battery_low": 25}]

        out = [
            "List of devices attached\nHTC\tdevice",
            "-9000",
        ]
        mock = Mock(side_effect=out)
        with patch.dict(adb.__salt__, {"cmd.run": mock}):
            ret = adb.validate(config)
            self.assertEqual(ret, (True, "Valid beacon configuration"))

            ret = adb.beacon(config)
            self.assertEqual(ret, [{
                "device": "HTC",
                "state": "device",
                "tag": "device"
            }])
예제 #8
0
    def test_device_battery_not_found(self):
        config = [{"states": ["device"], "battery_low": 25}]

        out = [
            "List of devices attached\nHTC\tdevice",
            "/system/bin/sh: cat: /sys/class/power_supply/*/capacity: No such file or directory",
        ]
        mock = Mock(side_effect=out)
        with patch.dict(adb.__salt__, {"cmd.run": mock}):
            ret = adb.validate(config)
            self.assertEqual(ret, (True, "Valid beacon configuration"))

            ret = adb.beacon(config)
            self.assertEqual(ret, [{
                "device": "HTC",
                "state": "device",
                "tag": "device"
            }])
예제 #9
0
    def test_repo_noadd_mod_noref(self):
        '''
        Test mod_repo detects the repository exists,
        calls modify to update 'autorefresh' but does not call refresh

        :return:
        '''
        url = self.new_repo_config['url']
        name = self.new_repo_config['name']
        self.zypper_patcher_config['_get_configured_repos'] = Mock(
            **{'return_value.sections.return_value': [name]})
        zypper_patcher = patch.multiple('salt.modules.zypper',
                                        **self.zypper_patcher_config)
        with zypper_patcher:
            zypper.mod_repo(name, **{'url': url, 'refresh': True})
            self.assertTrue(zypper.__zypper__.xml.call.call_count == 0)
            zypper.__zypper__.refreshable.xml.call.assert_called_once_with(
                'mr', '--refresh', name)
예제 #10
0
def test_services_need_restart():
    """
    Test that checkrestart output is parsed correctly
    """
    cr_output = """
PROCESSES: 24
PROGRAMS: 17
PACKAGES: 8
SERVICE:rsyslog,385,/usr/sbin/rsyslogd
SERVICE:cups-daemon,390,/usr/sbin/cupsd
    """

    with patch.dict(aptpkg.__salt__,
                    {"cmd.run_stdout": Mock(return_value=cr_output)}):
        assert sorted(aptpkg.services_need_restart()) == [
            "cups-daemon",
            "rsyslog",
        ]
예제 #11
0
 def test_version_parse_problem(self):
     '''
     Test with invalid context data. The context value must be a dict, so
     this should raise a SaltInvocationError.
     '''
     with patch('subprocess.Popen') as popen_mock:
         popen_mock.return_value = Mock(communicate=lambda *args, **kwargs:
                                        ('invalid', None),
                                        pid=lambda: 12345,
                                        retcode=0)
         # Test without context dict passed
         self.assertIsNone(_systemd.version())
         # Test that context key is set when context dict is passed. A failure
         # to parse the systemctl output should not set a context key, so it
         # should not be present in the context dict.
         context = {}
         self.assertIsNone(_systemd.version(context))
         self.assertEqual(context, {})
예제 #12
0
    def test_diskusage_windows_lowercase(self):
        r"""
        This tests lowercase drive letter (c:\)
        """
        disk_usage_mock = Mock(return_value=WINDOWS_STUB_DISK_USAGE)
        with patch("salt.utils.platform.is_windows", MagicMock(return_value=True)):
            with patch(
                "psutil.disk_partitions",
                MagicMock(return_value=WINDOWS_STUB_DISK_PARTITION),
            ), patch("psutil.disk_usage", disk_usage_mock):
                config = [{"c:\\": "50%"}]

                ret = diskusage.validate(config)

                self.assertEqual(ret, (True, "Valid beacon configuration"))

                ret = diskusage.beacon(config)
                self.assertEqual(ret, [{"diskusage": 50, "mount": "C:\\"}])
예제 #13
0
def test_device_state_change():
    config = [{"states": ["offline"]}]

    out = [
        "List of devices attached\nHTC\tdevice",
        "List of devices attached\nHTC\toffline",
    ]

    mock = Mock(side_effect=out)
    with patch.dict(adb.__salt__, {"cmd.run": mock}):
        ret = adb.validate(config)
        assert ret == (True, "Valid beacon configuration")

        ret = adb.beacon(config)
        assert ret == []

        ret = adb.beacon(config)
        assert ret == [{"device": "HTC", "state": "offline", "tag": "offline"}]
예제 #14
0
def test_diskusage_windows_single_slash(windows_stub_disk_usage,
                                        windows_stub_disk_partition):
    r"""
    This tests new behavior (C:\)
    """
    disk_usage_mock = Mock(return_value=windows_stub_disk_usage)
    with patch("salt.utils.platform.is_windows", MagicMock(return_value=True)):
        with patch(
                "psutil.disk_partitions",
                MagicMock(return_value=windows_stub_disk_partition),
        ), patch("psutil.disk_usage", disk_usage_mock):
            config = [{"C:\\": "50%"}]

            ret = diskusage.validate(config)
            assert ret == (True, "Valid beacon configuration")

            ret = diskusage.beacon(config)
            assert ret == [{"diskusage": 50, "mount": "C:\\"}]
예제 #15
0
    def test_openscap_xccdf_eval_evaluation_error(self):
        with patch(
                'salt.modules.openscap.Popen',
                MagicMock(return_value=Mock(
                    **{
                        'returncode': 1,
                        'communicate.return_value': ('', 'evaluation error')
                    }))):
            response = openscap.xccdf('eval --profile Default {0}'.format(
                self.policy_file))

            self.assertEqual(
                response, {
                    'upload_dir': None,
                    'error': 'evaluation error',
                    'success': False,
                    'returncode': 1
                })
예제 #16
0
 def setup_loader_modules(self):
     module_globals = {
         "__salt__": {
             "config.get":
             MagicMock(
                 return_value={
                     "telegram": {
                         "chat_id": "123456789",
                         "token":
                         "000000000:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
                     }
                 }),
             "requests.put":
             Mock(),
         },
         "requests": RequestMock(),
     }
     return {telegram: module_globals}
예제 #17
0
 def test_absent_noremove(self):
     with patch.dict(
             postgres_schema.__salt__, {
                 'postgres.schema_exists': Mock(return_value=False),
                 'postgres.schema_remove': MagicMock()
             }):
         ret = postgres_schema.absent('dbname', 'foo')
         self.assertEqual(
             ret, {
                 'comment': 'Schema foo is not present in database dbname,'
                 ' so it cannot be removed',
                 'changes': {},
                 'dbname': 'dbname',
                 'name': 'foo',
                 'result': True
             })
         self.assertEqual(
             self.salt_stub['postgres.schema_remove'].call_count, 0)
예제 #18
0
 def test_push(self):
     """
     Test if push works with good posix path.
     """
     filename = "/saltines/test.file"
     if salt.utils.platform.is_windows():
         filename = "C:\\saltines\\test.file"
     with patch(
             "salt.modules.cp.os.path",
             MagicMock(isfile=Mock(return_value=True), wraps=cp.os.path),
     ), patch(
             "salt.modules.cp.os.path",
             MagicMock(getsize=MagicMock(return_value=10),
                       wraps=cp.os.path),
     ), patch.multiple(
             "salt.modules.cp",
             _auth=MagicMock(
                 **{"return_value.gen_token.return_value": "token"}),
             __opts__={
                 "id": "abc",
                 "file_buffer_size": 10
             },
     ), patch("salt.utils.files.fopen",
              mock_open(read_data=b"content")) as m_open, patch(
                  "salt.channel.client.ReqChannel.factory",
                  MagicMock()) as req_channel_factory_mock:
         response = cp.push(filename)
         assert response, response
         num_opens = len(m_open.filehandles[filename])
         assert num_opens == 1, num_opens
         fh_ = m_open.filehandles[filename][0]
         assert fh_.read.call_count == 2, fh_.read.call_count
         req_channel_factory_mock().__enter__(
         ).send.assert_called_once_with(
             dict(
                 loc=fh_.tell(),  # pylint: disable=resource-leakage
                 cmd="_file_recv",
                 tok="token",
                 path=["saltines", "test.file"],
                 size=10,
                 data=
                 b"",  # data is empty here because load['data'] is overwritten
                 id="abc",
             ))
예제 #19
0
    def test_openscap_xccdf_eval_success_with_failing_rules(self):
        with patch(
                "salt.modules.openscap.Popen",
                MagicMock(return_value=Mock(
                    **{
                        "returncode": 2,
                        "communicate.return_value": ("", "some error")
                    })),
        ):
            response = openscap.xccdf("eval --profile Default {}".format(
                self.policy_file))

            self.assertEqual(openscap.tempfile.mkdtemp.call_count, 1)
            expected_cmd = [
                "oscap",
                "xccdf",
                "eval",
                "--oval-results",
                "--results",
                "results.xml",
                "--report",
                "report.html",
                "--profile",
                "Default",
                self.policy_file,
            ]
            openscap.Popen.assert_called_once_with(
                expected_cmd,
                cwd=openscap.tempfile.mkdtemp.return_value,
                stderr=subprocess.PIPE,
                stdout=subprocess.PIPE,
            )
            openscap.__salt__["cp.push_dir"].assert_called_once_with(
                self.random_temp_dir)
            self.assertEqual(openscap.shutil.rmtree.call_count, 1)
            self.assertEqual(
                response,
                {
                    "upload_dir": self.random_temp_dir,
                    "error": "some error",
                    "success": True,
                    "returncode": 2,
                },
            )
예제 #20
0
 def test_upgrade(self):
     '''
     Test if it upgrade all of the packages to the latest available version.
     '''
     mock_run = MagicMock(return_value='A\t B\t SAME')
     mock_ret = MagicMock(return_value=0)
     mock_pkg = MagicMock(return_value='')
     with patch.dict(
             pkgutil.__salt__, {
                 'cmd.run_stdout': mock_run,
                 'cmd.retcode': mock_ret,
                 'pkg_resource.stringify': mock_pkg,
                 'pkg_resource.sort_pkglist': mock_pkg,
                 'cmd.run_all': mock_ret,
                 'cmd.run': mock_run
             }):
         with patch.dict(pkgutil.__context__, {'pkg.list_pkgs': mock_ret}):
             with patch.object(salt.utils.pkg, 'clear_rtag', Mock()):
                 self.assertDictEqual(pkgutil.upgrade(), {})
예제 #21
0
def test_absent_noremove():
    with patch.dict(
        postgres_schema.__salt__,
        {
            "postgres.schema_exists": Mock(return_value=False),
            "postgres.schema_remove": MagicMock(),
        },
    ):
        ret = postgres_schema.absent("dbname", "foo")
        assert ret == {
            "comment": (
                "Schema foo is not present in database dbname, so it cannot be removed"
            ),
            "changes": {},
            "dbname": "dbname",
            "name": "foo",
            "result": True,
        }
        assert postgres_schema.__salt__["postgres.schema_remove"].call_count == 0
예제 #22
0
def test_present_nocreation():
    with patch.dict(
        postgres_schema.__salt__,
        {
            "postgres.schema_get": Mock(
                return_value={"foo": {"acl": "", "owner": "postgres"}}
            ),
            "postgres.schema_create": MagicMock(),
        },
    ):
        ret = postgres_schema.present("dbname", "foo")
        assert ret == {
            "comment": "Schema foo already exists in database dbname",
            "changes": {},
            "dbname": "dbname",
            "name": "foo",
            "result": True,
        }
        assert postgres_schema.__salt__["postgres.schema_create"].call_count == 0
예제 #23
0
def test_render_without_cache():
    key_dir = "/etc/salt/gpgkeys"
    secret = "Use more salt."
    expected = "\n".join([secret] * 3)
    crypted = dedent("""\
        -----BEGIN PGP MESSAGE-----
        !@#$%^&*()_+
        -----END PGP MESSAGE-----
        -----BEGIN PGP MESSAGE-----
        !@#$%^&*()_+
        -----END PGP MESSAGE-----
        -----BEGIN PGP MESSAGE-----
        !@#$%^&*()_+
        -----END PGP MESSAGE-----
    """)

    with patch("salt.renderers.gpg.Popen") as popen_mock:
        popen_mock.return_value = Mock(communicate=lambda *args, **kwargs:
                                       (secret, None),
                                       )
        with patch(
                "salt.renderers.gpg._get_gpg_exec",
                MagicMock(return_value="/usr/bin/gpg"),
        ):
            with patch("salt.renderers.gpg._get_key_dir",
                       MagicMock(return_value=key_dir)):
                assert gpg.render(crypted) == expected
                gpg_call = call(
                    [
                        "/usr/bin/gpg",
                        "--homedir",
                        "/etc/salt/gpgkeys",
                        "--status-fd",
                        "2",
                        "--no-tty",
                        "-d",
                    ],
                    shell=False,
                    stderr=PIPE,
                    stdin=PIPE,
                    stdout=PIPE,
                )
                popen_mock.assert_has_calls([gpg_call] * 3)
예제 #24
0
    def test_get_dns_servers(self):
        """
        Test if it return a list of the configured DNS servers
        of the specified interface.
        """
        with patch("salt.utils.winapi.Com",
                   MagicMock()), patch.object(
                       self.WMI,
                       "Win32_NetworkAdapter",
                       return_value=[Mockwmi()]), patch.object(
                           self.WMI,
                           "Win32_NetworkAdapterConfiguration",
                           return_value=[Mockwmi()]), patch.object(
                               wmi, "WMI", Mock(return_value=self.WMI)):
            self.assertListEqual(
                win_dns_client.get_dns_servers("Local Area Connection"),
                ["10.1.1.10"])

            self.assertFalse(win_dns_client.get_dns_servers("Ethernet"))
예제 #25
0
    def test_setup_client_key_file(self):
        '''
        Test that the `kubernetes.client-key-file` configuration isn't overwritten
        :return:
        '''
        def settings(name, value=None):
            data = {
                'kubernetes.client-key-file':
                '/home/testuser/.minikube/client.key',
            }
            return data.get(name, value)

        with patch.dict(kubernetes.__salt__,
                        {'config.option': Mock(side_effect=settings)}):
            config = kubernetes._setup_conn()
            self.assertEqual(
                settings('kubernetes.client-key-file'),
                config['key_file'],
            )
예제 #26
0
 def test_unjoin_domain(self):
     """
     Test unjoining a computer from an Active Directory domain
     """
     with patch("salt.utils.winapi.Com", MagicMock()), patch.object(
             self.WMI,
             "Win32_ComputerSystem",
             return_value=[MockWMI_ComputerSystem()]), patch.object(
                 wmi, "WMI", Mock(return_value=self.WMI)), patch(
                     "salt.modules.win_system.get_domain_workgroup",
                     MagicMock(return_value={"Domain": "contoso.com"}),
                 ):
         self.assertDictEqual(
             win_system.unjoin_domain(),
             {
                 "Workgroup": "WORKGROUP",
                 "Restart": False
             },
         )
예제 #27
0
    def test_multiple_low_batteries(self):
        config = {'states': ['device'], 'battery_low': 30}

        out = [
            'List of devices attached\nHTC\tdevice',
            '25\n14',
        ]
        mock = Mock(side_effect=out)
        with patch.dict(adb.__salt__, {'cmd.run': mock}):
            ret = adb.beacon(config)
            self.assertEqual(ret, [{
                'device': 'HTC',
                'state': 'device',
                'tag': 'device'
            }, {
                'device': 'HTC',
                'battery_level': 25,
                'tag': 'battery_low'
            }])
예제 #28
0
    def test_diskusage_windows_match_regex(self):
        disk_usage_mock = Mock(return_value=WINDOWS_STUB_DISK_USAGE)
        with patch("salt.utils.platform.is_windows", MagicMock(return_value=True)):
            with patch(
                "psutil.disk_partitions",
                MagicMock(return_value=WINDOWS_STUB_DISK_PARTITION),
            ), patch("psutil.disk_usage", disk_usage_mock):
                config = [{"^[a-zA-Z]:\\": "50%"}]

                ret = diskusage.validate(config)

                self.assertEqual(ret, (True, "Valid beacon configuration"))

                ret = diskusage.beacon(config)
                _expected = [
                    {u"diskusage": 50, u"mount": "C:\\"},
                    {u"diskusage": 50, u"mount": "D:\\"},
                ]
                self.assertEqual(ret, _expected)
예제 #29
0
 def test_failed_login(self):
     '''
     Check that when docker.login failed a retcode other then 0
     is part of the return.
     '''
     client = Mock()
     get_client_mock = MagicMock(return_value=client)
     ref_out = {
         'stdout': '',
         'stderr': 'login failed',
         'retcode': 1
     }
     with patch.dict(docker_mod.__pillar__, {'docker-registries': {'portus.example.com:5000':
             {'username': '******', 'password': '******', 'email': '*****@*****.**'}}}):
         with patch.object(docker_mod, '_get_client', get_client_mock):
             with patch.dict(docker_mod.__salt__, {'cmd.run_all': MagicMock(return_value=ref_out)}):
                 ret = docker_mod.login('portus.example.com:5000')
                 self.assertIn('retcode', ret)
                 self.assertNotEqual(ret['retcode'], 0)
예제 #30
0
    def test_screen_state_change(self):
        config = [{'screen_event': True, 'user': '******'}]

        mock = Mock(side_effect=[255, 0])
        with patch.dict(glxinfo.__salt__, {'cmd.retcode': mock}):
            ret = glxinfo.validate(config)
            self.assertEqual(ret, (True, 'Valid beacon configuration'))

            ret = glxinfo.beacon(config)
            self.assertEqual(ret, [{
                'tag': 'screen_event',
                'screen_available': False
            }])

            ret = glxinfo.beacon(config)
            self.assertEqual(ret, [{
                'tag': 'screen_event',
                'screen_available': True
            }])