예제 #1
0
    def test_installed_cert_hash_different(self):
        '''
            Test installing a certificate into the macOS keychain when it's
            already installed but the certificate has changed
        '''
        expected = {
            'changes': {'installed': 'Friendly Name', 'uninstalled': 'Friendly Name'},
            'comment': 'Found a certificate with the same name but different hash, removing it.\n',
            'name': '/path/to/cert.p12',
            'result': True
        }

        list_mock = MagicMock(side_effect=[['Friendly Name'], []])
        friendly_mock = MagicMock(return_value='Friendly Name')
        install_mock = MagicMock(return_value='1 identity imported.')
        uninstall_mock = MagicMock(return_value='removed.')
        hash_mock = MagicMock(side_effect=['ABCD', 'XYZ'])
        with patch.dict(keychain.__salt__, {'keychain.list_certs': list_mock,
                                            'keychain.get_friendly_name': friendly_mock,
                                            'keychain.install': install_mock,
                                            'keychain.uninstall': uninstall_mock,
                                            'keychain.get_hash': hash_mock}):
            out = keychain.installed('/path/to/cert.p12', 'passw0rd')
            list_mock.assert_has_calls(calls=[call('/Library/Keychains/System.keychain'),
                                              call('/Library/Keychains/System.keychain')])
            friendly_mock.assert_called_once_with('/path/to/cert.p12', 'passw0rd')
            install_mock.assert_called_once_with('/path/to/cert.p12', 'passw0rd', '/Library/Keychains/System.keychain')
            uninstall_mock.assert_called_once_with('Friendly Name', '/Library/Keychains/System.keychain',
                                                   keychain_password=None)
            self.assertEqual(out, expected)
예제 #2
0
    def test_get_pkg_id_with_files(self, pkg_id_pkginfo_mock):
        '''
            Test getting a the id for a package
        '''
        expected = ['com.apple.this']
        cmd_mock = MagicMock(side_effect=[
            '/path/to/PackageInfo\n/path/to/some/other/fake/PackageInfo',
            '',
            ''
        ])
        pkg_id_pkginfo_mock.side_effect = [['com.apple.this'], []]
        temp_mock = MagicMock(return_value='/tmp/dmg-ABCDEF')
        remove_mock = MagicMock()

        with patch.dict(macpackage.__salt__, {'cmd.run': cmd_mock,
                                              'temp.dir': temp_mock,
                                              'file.remove': remove_mock}):
            out = macpackage.get_pkg_id('/path/to/file.pkg')

            temp_mock.assert_called_once_with(prefix='pkg-')
            cmd_calls = [
                call('xar -t -f /path/to/file.pkg | grep PackageInfo', python_shell=True, output_loglevel='quiet'),
                call('xar -x -f /path/to/file.pkg /path/to/PackageInfo /path/to/some/other/fake/PackageInfo',
                     cwd='/tmp/dmg-ABCDEF', output_loglevel='quiet')
            ]
            cmd_mock.assert_has_calls(cmd_calls)

            pkg_id_pkginfo_calls = [
                call('/path/to/PackageInfo'),
                call('/path/to/some/other/fake/PackageInfo')
            ]
            pkg_id_pkginfo_mock.assert_has_calls(pkg_id_pkginfo_calls)
            remove_mock.assert_called_once_with('/tmp/dmg-ABCDEF')

            self.assertEqual(out, expected)
예제 #3
0
    def test_set_proxy_windows_no_ftp(self):
        '''
            Test to make sure that we correctly set the proxy info
            on Windows
        '''
        proxy.__grains__['os'] = 'Windows'
        mock_reg = MagicMock()
        mock_cmd = MagicMock()

        with patch.dict(proxy.__salt__, {'reg.set_value': mock_reg, 'cmd.run': mock_cmd}):
            out = proxy.set_proxy_win('192.168.0.1', 3128, types=['http', 'https'],
                                      bypass_hosts=['.moo.com', '.salt.com'])

            calls = [
                call('HKEY_CURRENT_USER',
                     'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings',
                     'ProxyServer',
                     'http=192.168.0.1:3128;https=192.168.0.1:3128;'),
                call('HKEY_CURRENT_USER',
                     'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings',
                     'ProxyEnable',
                     1,
                     vtype='REG_DWORD'),
                call('HKEY_CURRENT_USER',
                     'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings',
                     'ProxyOverride',
                     '<local>;.moo.com;.salt.com')
            ]
            mock_reg.assert_has_calls(calls)
            mock_cmd.assert_called_once_with('netsh winhttp import proxy source=ie')
            self.assertTrue(out)
예제 #4
0
    def _runner(self,
                expected_ret,
                test=False,
                check=False,
                add=False,
                add_assertion=False):
        mock_check = MagicMock(return_value=check)
        mock_add = MagicMock(return_value=add)
        with patch.dict(ipset.__opts__, {'test': test}):
            with patch.dict(ipset.__salt__, {
                    'ipset.check': mock_check,
                    'ipset.add': mock_add
            }):
                actual_ret = ipset.present(self.fake_name,
                                           self.fake_entries,
                                           set_name=self.fake_name)

        mock_check.assert_has_calls(
            [call(self.fake_name, e, 'ipv4') for e in self.fake_entries],
            any_order=True)
        if add_assertion:
            expected_calls = [
                call(self.fake_name, e, 'ipv4', set_name=self.fake_name)
                for e in self.fake_entries
            ]
            if add is not True:
                # if the add fails, then it will only get called once.
                expected_calls = expected_calls[:1]
            mock_add.assert_has_calls(expected_calls, any_order=True)
        else:
            self.assertTrue(mock_add.call_count == 0)
        self.assertDictEqual(actual_ret, expected_ret)
예제 #5
0
 def _runner(self,
             expected_ret,
             test=False,
             check=False,
             delete=False,
             delete_assertion=False):
     mock_check = MagicMock(return_value=check)
     mock_delete = MagicMock(return_value=delete)
     with patch.dict(ipset.__opts__, {'test': test}):
         with patch.dict(ipset.__salt__, {
                 'ipset.check': mock_check,
                 'ipset.delete': mock_delete
         }):
             actual_ret = ipset.absent(self.fake_name,
                                       self.fake_entries,
                                       set_name=self.fake_name)
     mock_check.assert_has_calls(
         [call(self.fake_name, e, 'ipv4') for e in self.fake_entries],
         any_order=True)
     if delete_assertion:
         expected_calls = [
             call(self.fake_name, e, 'ipv4', set_name=self.fake_name)
             for e in self.fake_entries
         ]
         if delete is not True:
             expected_calls = expected_calls[:1]
         mock_delete.assert_has_calls(expected_calls, any_order=True)
     else:
         self.assertTrue(mock_delete.call_count == 0)
     self.assertDictEqual(actual_ret, expected_ret)
예제 #6
0
    def test_get_pkg_id_with_files(self, pkg_id_pkginfo_mock):
        '''
            Test getting a the id for a package
        '''
        expected = ['com.apple.this']
        cmd_mock = MagicMock(side_effect=[
            '/path/to/PackageInfo\n/path/to/some/other/fake/PackageInfo',
            '',
            ''
        ])
        pkg_id_pkginfo_mock.side_effect = [['com.apple.this'], []]
        temp_mock = MagicMock(return_value='/tmp/dmg-ABCDEF')
        remove_mock = MagicMock()

        with patch.dict(macpackage.__salt__, {'cmd.run': cmd_mock,
                                              'temp.dir': temp_mock,
                                              'file.remove': remove_mock}):
            out = macpackage.get_pkg_id('/path/to/file.pkg')

            temp_mock.assert_called_once_with(prefix='pkg-')
            cmd_calls = [
                call('xar -t -f /path/to/file.pkg | grep PackageInfo', python_shell=True, output_loglevel='quiet'),
                call('xar -x -f /path/to/file.pkg /path/to/PackageInfo /path/to/some/other/fake/PackageInfo',
                     cwd='/tmp/dmg-ABCDEF', output_loglevel='quiet')
            ]
            cmd_mock.assert_has_calls(cmd_calls)

            pkg_id_pkginfo_calls = [
                call('/path/to/PackageInfo'),
                call('/path/to/some/other/fake/PackageInfo')
            ]
            pkg_id_pkginfo_mock.assert_has_calls(pkg_id_pkginfo_calls)
            remove_mock.assert_called_once_with('/tmp/dmg-ABCDEF')

            self.assertEqual(out, expected)
예제 #7
0
    def test_installed_cert_hash_different(self):
        '''
            Test installing a certificate into the OSX keychain when it's already installed but
            the certificate has changed
        '''
        expected = {
            'changes': {'installed': 'Friendly Name', 'uninstalled': 'Friendly Name'},
            'comment': 'Found a certificate with the same name but different hash, removing it.\n',
            'name': '/path/to/cert.p12',
            'result': True
        }

        list_mock = MagicMock(side_effect=[['Friendly Name'], []])
        friendly_mock = MagicMock(return_value='Friendly Name')
        install_mock = MagicMock(return_value='1 identity imported.')
        uninstall_mock = MagicMock(return_value='removed.')
        hash_mock = MagicMock(side_effect=['ABCD', 'XYZ'])
        with patch.dict(keychain.__salt__, {'keychain.list_certs': list_mock,
                                            'keychain.get_friendly_name': friendly_mock,
                                            'keychain.install': install_mock,
                                            'keychain.uninstall': uninstall_mock,
                                            'keychain.get_hash': hash_mock}):
            out = keychain.installed('/path/to/cert.p12', 'passw0rd')
            list_mock.assert_has_calls(calls=[call('/Library/Keychains/System.keychain'),
                                              call('/Library/Keychains/System.keychain')])
            friendly_mock.assert_called_once_with('/path/to/cert.p12', 'passw0rd')
            install_mock.assert_called_once_with('/path/to/cert.p12', 'passw0rd', '/Library/Keychains/System.keychain')
            uninstall_mock.assert_called_once_with('Friendly Name', '/Library/Keychains/System.keychain',
                                                   keychain_password=None)
            self.assertEqual(out, expected)
예제 #8
0
파일: mysql_test.py 프로젝트: tligda/salt
 def _test_call(self, function, expected_sql, *args, **kwargs):
     connect_mock = MagicMock()
     mysql._connect = connect_mock
     with patch.dict(mysql.__salt__, {'config.option': MagicMock()}):
         function(*args, **kwargs)
         if isinstance(expected_sql, dict):
             calls = (call().cursor().execute('{0}'.format(expected_sql['sql']), expected_sql['sql_args']))
         else:
             calls = (call().cursor().execute('{0}'.format(expected_sql)))
         connect_mock.assert_has_calls(calls)
예제 #9
0
 def _test_call(self, function, expected_sql, *args, **kwargs):
     connect_mock = MagicMock()
     mysql._connect = connect_mock
     with patch.dict(mysql.__salt__, {"config.option": MagicMock()}):
         function(*args, **kwargs)
         if isinstance(expected_sql, dict):
             calls = call().cursor().execute("{0}".format(expected_sql["sql"]), expected_sql["sql_args"])
         else:
             calls = call().cursor().execute("{0}".format(expected_sql))
         connect_mock.assert_has_calls(calls)
예제 #10
0
파일: mysql_test.py 프로젝트: zer0n1/salt
 def test_get_slave_status_bad_server(self):
     '''
     Test get_slave_status in the mysql execution module, simulating a broken server
     '''
     connect_mock = MagicMock(return_value=None)
     mysql._connect = connect_mock
     with patch.dict(mysql.__salt__, {'config.option': MagicMock()}):
         rslt = mysql.get_slave_status()
         connect_mock.assert_has_calls([call()])
         self.assertEqual(rslt, [])
예제 #11
0
파일: mysql_test.py 프로젝트: bryson/salt
 def test_get_slave_status_bad_server(self):
     '''
     Test get_slave_status in the mysql execution module, simulating a broken server
     '''
     connect_mock = MagicMock(return_value=None)
     mysql._connect = connect_mock
     with patch.dict(mysql.__salt__, {'config.option': MagicMock()}):
         rslt = mysql.get_slave_status()
         connect_mock.assert_has_calls([call()])
         self.assertEqual(rslt, [])
예제 #12
0
    def test_set_proxy_macos(self):
        '''
            Test to make sure we can set the proxy settings on macOS
        '''
        proxy.__grains__['os'] = 'Darwin'
        expected = {'changes': {
            'new': [
                {'port': '3128',
                 'server': '192.168.0.1',
                 'service': 'http',
                 'user': '******'},
                {'port': '3128',
                 'server': '192.168.0.1',
                 'service': 'https',
                 'user': '******'},
                {'port': '3128',
                 'server': '192.168.0.1',
                 'service': 'ftp',
                 'user': '******'},
                {'bypass_domains': ['salt.com', 'test.com']}]
            },
            'comment': 'http proxy settings updated correctly\nhttps proxy settings updated correctly\nftp proxy '
                       'settings updated correctly\nProxy bypass domains updated correctly\n',
            'name': '192.168.0.1',
            'result': True}

        set_proxy_mock = MagicMock(return_value=True)
        patches = {
            'proxy.get_http_proxy': MagicMock(return_value={}),
            'proxy.get_https_proxy': MagicMock(return_value={}),
            'proxy.get_ftp_proxy': MagicMock(return_value={}),
            'proxy.get_proxy_bypass': MagicMock(return_value=[]),
            'proxy.set_http_proxy': set_proxy_mock,
            'proxy.set_https_proxy': set_proxy_mock,
            'proxy.set_ftp_proxy': set_proxy_mock,
            'proxy.set_proxy_bypass': set_proxy_mock,
        }

        with patch.dict(proxy.__salt__, patches):
            out = proxy.managed('192.168.0.1', '3128', user='******', password='******',
                                bypass_domains=['salt.com', 'test.com'])
            if six.PY3:
                # Sorting is different in Py3
                out['changes']['new'][-1]['bypass_domains'] = sorted(out['changes']['new'][-1]['bypass_domains'])

            calls = [
                call('192.168.0.1', '3128', 'frank', 'passw0rd', 'Ethernet'),
                call('192.168.0.1', '3128', 'frank', 'passw0rd', 'Ethernet'),
                call('192.168.0.1', '3128', 'frank', 'passw0rd', 'Ethernet'),
                call(['salt.com', 'test.com'], 'Ethernet')
            ]

            set_proxy_mock.assert_has_calls(calls)
            self.assertEqual(out, expected)
예제 #13
0
    def test_third_attempt_successful_connection(self):
        exc = vim.fault.HostConnectFault()
        exc.msg = '[SSL: CERTIFICATE_VERIFY_FAILED]'
        exc2 = Exception('certificate verify failed')
        mock_sc = MagicMock(side_effect=[exc, exc2, None])
        mock_ssl_unverif = MagicMock()
        mock_ssl_context = MagicMock()

        with patch('salt.utils.vmware.SmartConnect', mock_sc):
            with patch('ssl._create_unverified_context', mock_ssl_unverif):

                with patch('ssl.SSLContext', mock_ssl_context):

                    salt.utils.vmware._get_service_instance(
                        host='fake_host.fqdn',
                        username='******',
                        password='******',
                        protocol='fake_protocol',
                        port=1,
                        mechanism='sspi',
                        principal='fake_principal',
                        domain='fake_domain')

                    mock_ssl_context.assert_called_once_with(
                        ssl.PROTOCOL_TLSv1)
                    mock_ssl_unverif.assert_called_once_with()
                    calls = [
                        call(host='fake_host.fqdn',
                             user='******',
                             pwd='fake_password',
                             protocol='fake_protocol',
                             port=1,
                             b64token='fake_token',
                             mechanism='sspi'),
                        call(host='fake_host.fqdn',
                             user='******',
                             pwd='fake_password',
                             protocol='fake_protocol',
                             port=1,
                             sslContext=mock_ssl_unverif.return_value,
                             b64token='fake_token',
                             mechanism='sspi'),
                        call(host='fake_host.fqdn',
                             user='******',
                             pwd='fake_password',
                             protocol='fake_protocol',
                             port=1,
                             sslContext=mock_ssl_context.return_value,
                             b64token='fake_token',
                             mechanism='sspi'),
                    ]
                    mock_sc.assert_has_calls(calls)
예제 #14
0
    def test_install_pkgs(self):
        '''
        Test package install behavior for the following conditions:
        - only base package name is given ('png')
        - a flavor is specified ('vim--gtk2')
        - a branch is specified ('ruby%2.3')
        '''
        class ListPackages(object):
            def __init__(self):
                self._iteration = 0

            def __call__(self):
                pkg_lists = [
                     {'vim': '7.4.1467p1-gtk2'},
                     {'png': '1.6.23', 'vim': '7.4.1467p1-gtk2', 'ruby': '2.3.1p1'}
                ]
                pkgs = pkg_lists[self._iteration]
                self._iteration += 1
                return pkgs

        parsed_targets = (
            {'vim--gtk2': None, 'png': None, 'ruby%2.3': None},
            "repository"
        )
        cmd_out = {
            'retcode': 0,
            'stdout': 'quirks-2.241 signed on 2016-07-26T16:56:10Z',
            'stderr': ''
        }
        run_all_mock = MagicMock(return_value=cmd_out)
        patches = {
            'cmd.run_all': run_all_mock,
            'pkg_resource.parse_targets': MagicMock(return_value=parsed_targets),
            'pkg_resource.stringify': MagicMock(),
            'pkg_resource.sort_pkglist': MagicMock(),
        }

        with patch.dict(openbsdpkg.__salt__, patches):
            with patch('salt.modules.openbsdpkg.list_pkgs', ListPackages()):
                added = openbsdpkg.install()
                expected = {
                    'png': {'new': '1.6.23', 'old': ''},
                    'ruby': {'new': '2.3.1p1', 'old': ''}
                }
                self.assertDictEqual(added, expected)
        expected_calls = [
            call('pkg_add -x -I png--%', output_loglevel='trace', python_shell=False),
            call('pkg_add -x -I ruby--%2.3', output_loglevel='trace', python_shell=False),
            call('pkg_add -x -I vim--gtk2%', output_loglevel='trace', python_shell=False),
        ]
        run_all_mock.assert_has_calls(expected_calls, any_order=True)
        self.assertEqual(run_all_mock.call_count, 3)
예제 #15
0
    def test_set_proxy_osx(self):
        '''
            Test to make sure we can set the proxy settings on OSX
        '''
        proxy.__grains__['os'] = 'Darwin'
        expected = {'changes': {
            'new': [
                {'port': '3128',
                 'server': '192.168.0.1',
                 'service': 'http',
                 'user': '******'},
                {'port': '3128',
                 'server': '192.168.0.1',
                 'service': 'https',
                 'user': '******'},
                {'port': '3128',
                 'server': '192.168.0.1',
                 'service': 'ftp',
                 'user': '******'},
                {'bypass_domains': ['salt.com', 'test.com']}]
            },
            'comment': 'http proxy settings updated correctly\nhttps proxy settings updated correctly\nftp proxy '
                       'settings updated correctly\nProxy bypass domains updated correctly\n',
            'name': '192.168.0.1',
            'result': True}

        set_proxy_mock = MagicMock(return_value=True)
        patches = {
            'proxy.get_http_proxy': MagicMock(return_value={}),
            'proxy.get_https_proxy': MagicMock(return_value={}),
            'proxy.get_ftp_proxy': MagicMock(return_value={}),
            'proxy.get_proxy_bypass': MagicMock(return_value=[]),
            'proxy.set_http_proxy': set_proxy_mock,
            'proxy.set_https_proxy': set_proxy_mock,
            'proxy.set_ftp_proxy': set_proxy_mock,
            'proxy.set_proxy_bypass': set_proxy_mock,
        }

        with patch.dict(proxy.__salt__, patches):
            out = proxy.managed('192.168.0.1', '3128', user='******', password='******',
                                bypass_domains=['salt.com', 'test.com'])

            calls = [
                call('192.168.0.1', '3128', 'frank', 'passw0rd', 'Ethernet'),
                call('192.168.0.1', '3128', 'frank', 'passw0rd', 'Ethernet'),
                call('192.168.0.1', '3128', 'frank', 'passw0rd', 'Ethernet'),
                call(['salt.com', 'test.com'], 'Ethernet')
            ]

            set_proxy_mock.assert_has_calls(calls)
            self.assertEqual(out, expected)
예제 #16
0
    def test_set_hibernate_timeout_scheme(self):
        '''
            Test to make sure we can set the hibernate timeout value
        '''
        mock = MagicMock()
        mock.side_effect = [self.query_ouput]

        with patch.dict(powercfg.__salt__, {'cmd.run': mock}):
            powercfg.set_hibernate_timeout(0, "dc", scheme="SCHEME_MIN")
            calls = [
                call(
                    'powercfg /setdcvalueindex SCHEME_MIN SUB_SLEEP HIBERNATEIDLE 0',
                    python_shell=False)
            ]
            mock.assert_has_calls(calls)
예제 #17
0
    def test_list_attrs_hex(self):
        '''
            Test listing all of the extended attributes of a file with hex
        '''
        expected = {'com.test': 'first', 'com.other': 'second'}
        mock = MagicMock(side_effect=['com.test\ncom.other', 'first', 'second'])
        with patch.dict(xattr.__salt__, {'cmd.run': mock}):
            out = xattr.list('/path/to/file', True)

            calls = [
                call('xattr "/path/to/file"'),
                call('xattr -p -x "com.test" "/path/to/file"'),
                call('xattr -p -x "com.other" "/path/to/file"')
            ]
            mock.assert_has_calls(calls)
            self.assertEqual(out, expected)
예제 #18
0
    def test_get_rule(self):
        '''
        Test if it get firewall rule(s) info
        '''
        val = 'No rules match the specified criteria.'
        mock_cmd = MagicMock(side_effect=['salt', val])
        with patch.dict(win_firewall.__salt__, {'cmd.run': mock_cmd}):
            self.assertDictEqual(win_firewall.get_rule(), {'all': 'salt'})

            self.assertFalse(win_firewall.get_rule())

            calls = [
                call(['netsh', 'advfirewall', 'firewall', 'show', 'rule', 'name=all'], python_shell=False),
                call(['netsh', 'advfirewall', 'firewall', 'show', 'rule', 'name=all'], python_shell=False)
            ]
            mock_cmd.assert_has_calls(calls)
예제 #19
0
    def test_get_disk_timeout(self):
        '''
            Test to make sure we can get the disk timeout value
        '''
        mock = MagicMock()
        mock.side_effect = ["Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e  (Balanced)", self.query_ouput]

        with patch.dict(powercfg.__salt__, {'cmd.run': mock}):
            ret = powercfg.get_disk_timeout()
            calls = [
                call('powercfg /getactivescheme', python_shell=False),
                call('powercfg /q 381b4222-f694-41f0-9685-ff5bb260df2e SUB_DISK DISKIDLE', python_shell=False)
            ]
            mock.assert_has_calls(calls)

            self.assertEqual({'ac': 30, 'dc': 15}, ret)
예제 #20
0
    def test_get_hibernate_timeout_scheme(self):
        '''
            Test to make sure we can get the hibernate timeout value with a specified scheme
        '''
        mock = MagicMock()
        mock.side_effect = [self.query_ouput]

        with patch.dict(powercfg.__salt__, {'cmd.run': mock}):
            ret = powercfg.get_hibernate_timeout(scheme="SCHEME_MIN")
            calls = [
                call('powercfg /q SCHEME_MIN SUB_SLEEP HIBERNATEIDLE',
                     python_shell=False)
            ]
            mock.assert_has_calls(calls)

            self.assertEqual({'ac': 30, 'dc': 15}, ret)
예제 #21
0
 def _runner(self, expected_ret, pillar_name=None, nodegroup_matches=None):
     pillar_name = pillar_name or fake_pillar_name
     nodegroup_matches = nodegroup_matches or [
         True,
         False,
     ]
     mock_nodegroup_match = MagicMock(side_effect=nodegroup_matches)
     with patch.object(nodegroups.Matcher, 'nodegroup_match',
                       mock_nodegroup_match):
         actual_ret = nodegroups.ext_pillar(fake_minion_id,
                                            fake_pillar,
                                            pillar_name=pillar_name)
     self.assertDictEqual(actual_ret, expected_ret)
     fake_nodegroup_count = len(fake_nodegroups)
     self.assertEqual(mock_nodegroup_match.call_count, fake_nodegroup_count)
     mock_nodegroup_match.assert_has_calls(
         [call(x, fake_nodegroups) for x in fake_nodegroups.keys()])
예제 #22
0
파일: ipset_test.py 프로젝트: bryson/salt
 def _runner(self, expected_ret, test=False, check=False, delete=False,
             delete_assertion=False):
     mock_check = MagicMock(return_value=check)
     mock_delete = MagicMock(return_value=delete)
     with patch.dict(ipset.__opts__, {'test': test}):
         with patch.dict(ipset.__salt__, {'ipset.check': mock_check,
                                          'ipset.delete': mock_delete}):
             actual_ret = ipset.absent(self.fake_name, self.fake_entries, set_name=self.fake_name)
     mock_check.assert_has_calls([call(self.fake_name, e, 'ipv4') for e in self.fake_entries], any_order=True)
     if delete_assertion:
         expected_calls = [call(self.fake_name, e, 'ipv4', set_name=self.fake_name) for e in self.fake_entries]
         if delete is not True:
             expected_calls = expected_calls[:1]
         mock_delete.assert_has_calls(expected_calls, any_order=True)
     else:
         mock_delete.assert_not_called()
     self.assertDictEqual(actual_ret, expected_ret)
예제 #23
0
    def test_traversal_spec_init(self):
        mock_dc_name = MagicMock()
        mock_traversal_spec = MagicMock()
        mock_traversal_spec_ini = MagicMock(return_value=mock_traversal_spec)
        mock_get_service_instance_from_managed_object = MagicMock()
        patch_traversal_spec_str = \
                'salt.utils.vmware.vmodl.query.PropertyCollector.TraversalSpec'

        with patch(patch_traversal_spec_str, mock_traversal_spec_ini):
            vmware.get_cluster(self.mock_dc, 'fake_cluster')
        mock_traversal_spec_ini.assert_has_calls([
            call(path='childEntity', skip=False, type=vim.Folder),
            call(path='hostFolder',
                 skip=True,
                 type=vim.Datacenter,
                 selectSet=[mock_traversal_spec])
        ])
예제 #24
0
    def test_windows_7(self):
        '''
            Test to make sure we can get the hibernate timeout value on windows 7
        '''
        mock = MagicMock()
        mock.side_effect = ["Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e  (Balanced)", self.query_ouput]

        with patch.dict(powercfg.__salt__, {'cmd.run': mock}):
            with patch.dict(powercfg.__grains__, {'osrelease': '7'}):
                ret = powercfg.get_hibernate_timeout()
                calls = [
                    call('powercfg /getactivescheme', python_shell=False),
                    call('powercfg /q 381b4222-f694-41f0-9685-ff5bb260df2e SUB_SLEEP', python_shell=False)
                ]
                mock.assert_has_calls(calls)

                self.assertEqual({'ac': 30, 'dc': 15}, ret)
예제 #25
0
    def test_list_attrs_hex(self):
        '''
            Test listing all of the extended attributes of a file with hex
        '''
        expected = {'com.test': 'first', 'com.other': 'second'}
        mock = MagicMock(
            side_effect=['com.test\ncom.other', 'first', 'second'])
        with patch.dict(xattr.__salt__, {'cmd.run': mock}):
            out = xattr.list('/path/to/file', True)

            calls = [
                call('xattr "/path/to/file"'),
                call('xattr -p -x "com.test" "/path/to/file"'),
                call('xattr -p -x "com.other" "/path/to/file"')
            ]
            mock.assert_has_calls(calls)
            self.assertEqual(out, expected)
예제 #26
0
 def test_user_chpass(self):
     """
     Test changing a MySQL user password in mysql exec module
     """
     connect_mock = MagicMock()
     mysql._connect = connect_mock
     with patch.dict(mysql.__salt__, {"config.option": MagicMock()}):
         mysql.user_chpass("testuser", password="******")
         calls = (
             call()
             .cursor()
             .execute(
                 "UPDATE mysql.user SET password=PASSWORD(%(password)s) WHERE User=%(user)s AND Host = %(host)s;",
                 {"password": "******", "user": "******", "host": "localhost"},
             ),
             call().cursor().execute("FLUSH PRIVILEGES;"),
         )
         connect_mock.assert_has_calls(calls, any_order=True)
예제 #27
0
파일: cluster_test.py 프로젝트: bryson/salt
    def test_traversal_spec_init(self):
        mock_dc_name = MagicMock()
        mock_traversal_spec = MagicMock()
        mock_traversal_spec_ini = MagicMock(return_value=mock_traversal_spec)
        mock_get_service_instance_from_managed_object = MagicMock()
        patch_traversal_spec_str = \
                'salt.utils.vmware.vmodl.query.PropertyCollector.TraversalSpec'

        with patch(patch_traversal_spec_str, mock_traversal_spec_ini):
            vmware.get_cluster(self.mock_dc, 'fake_cluster')
        mock_traversal_spec_ini.assert_has_calls(
            [call(path='childEntity',
                  skip=False,
                  type=vim.Folder),
            call(path='hostFolder',
                  skip=True,
                  type=vim.Datacenter,
                  selectSet=[mock_traversal_spec])])
예제 #28
0
    def test_get_all_proxies_windows(self):
        '''
            Test to make sure that we correctly get the current proxy info
            on Windows
        '''
        proxy.__grains__['os'] = 'Windows'
        results = [
            {
                'vdata': 'http=192.168.0.1:3128;https=192.168.0.2:3128;ftp=192.168.0.3:3128'
            },
            {
                'vdata': 1
            }
        ]
        mock = MagicMock(side_effect=results)

        expected = {
            'enabled': True,
            'http': {
                'server': '192.168.0.1',
                'port': '3128'
            },
            'https': {
                'server': '192.168.0.2',
                'port': '3128'
            },
            'ftp': {
                'server': '192.168.0.3',
                'port': '3128'
            }
        }
        with patch.dict(proxy.__salt__, {'reg.read_value': mock}):
            out = proxy.get_proxy_win()
            calls = [
                call('HKEY_CURRENT_USER',
                     'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings',
                     'ProxyServer'),
                call('HKEY_CURRENT_USER',
                     'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings',
                     'ProxyEnable'),
            ]

            mock.assert_has_calls(calls)
            self.assertEqual(expected, out)
예제 #29
0
 def test_user_chpass(self):
     '''
     Test changing a MySQL user password in mysql exec module
     '''
     connect_mock = MagicMock()
     mysql._connect = connect_mock
     with patch.dict(mysql.__salt__, {'config.option': MagicMock()}):
         mysql.user_chpass('testuser', password='******')
         calls = (
             call().cursor().execute(
                 'UPDATE mysql.user SET password=PASSWORD(%(password)s) WHERE User=%(user)s AND Host = %(host)s;',
                 {
                     'password': '******',
                     'user': '******',
                     'host': 'localhost',
                 }),
             call().cursor().execute('FLUSH PRIVILEGES;'),
         )
         connect_mock.assert_has_calls(calls, any_order=True)
예제 #30
0
파일: common_test.py 프로젝트: bryson/salt
    def test_get_mors_with_properties_calls(self):
        mock_get_mors_with_properties = MagicMock(return_value=[MagicMock()])
        with patch(
            'salt.utils.vmware.get_service_instance_from_managed_object',
            MagicMock(return_value=self.mock_si)):

            with patch('salt.utils.vmware.get_mors_with_properties',
                       mock_get_mors_with_properties):
                salt.utils.vmware.get_properties_of_managed_object(
                    self.fake_mo_ref, self.mock_props)
        mock_get_mors_with_properties.assert_has_calls(
            [call(self.mock_si, vim.ManagedEntity,
                  container_ref=self.fake_mo_ref,
                  property_list=['name'],
                  local_properties=True),
             call(self.mock_si, vim.ManagedEntity,
                  container_ref=self.fake_mo_ref,
                  property_list=self.mock_props,
                  local_properties=True)])
예제 #31
0
파일: ipset_test.py 프로젝트: bryson/salt
    def _runner(self, expected_ret, test=False, check=False, add=False,
                add_assertion=False):
        mock_check = MagicMock(return_value=check)
        mock_add = MagicMock(return_value=add)
        with patch.dict(ipset.__opts__, {'test': test}):
            with patch.dict(ipset.__salt__, {'ipset.check': mock_check,
                                             'ipset.add': mock_add}):
                actual_ret = ipset.present(self.fake_name, self.fake_entries, set_name=self.fake_name)

        mock_check.assert_has_calls([call(self.fake_name, e, 'ipv4') for e in self.fake_entries], any_order=True)
        if add_assertion:
            expected_calls = [call(self.fake_name, e, 'ipv4', set_name=self.fake_name) for e in self.fake_entries]
            if add is not True:
                # if the add fails, then it will only get called once.
                expected_calls = expected_calls[:1]
            mock_add.assert_has_calls(expected_calls, any_order=True)
        else:
            mock_add.assert_not_called()
        self.assertDictEqual(actual_ret, expected_ret)
예제 #32
0
    def test_get_mors_with_properties_calls(self):
        mock_get_mors_with_properties = MagicMock(return_value=[MagicMock()])
        with patch(
            'salt.utils.vmware.get_service_instance_from_managed_object',
            MagicMock(return_value=self.mock_si)):

            with patch('salt.utils.vmware.get_mors_with_properties',
                       mock_get_mors_with_properties):
                salt.utils.vmware.get_properties_of_managed_object(
                    self.fake_mo_ref, self.mock_props)
        mock_get_mors_with_properties.assert_has_calls(
            [call(self.mock_si, vim.ManagedEntity,
                  container_ref=self.fake_mo_ref,
                  property_list=['name'],
                  local_properties=True),
             call(self.mock_si, vim.ManagedEntity,
                  container_ref=self.fake_mo_ref,
                  property_list=self.mock_props,
                  local_properties=True)])
예제 #33
0
 def test_user_chpass(self):
     '''
     Test changing a MySQL user password in mysql exec module
     '''
     connect_mock = MagicMock()
     mysql._connect = connect_mock
     with patch.dict(mysql.__salt__, {'config.option': MagicMock()}):
         mysql.user_chpass('testuser', password='******')
         calls = (
             call().cursor().execute(
                 'UPDATE mysql.user SET password=PASSWORD(%(password)s) WHERE User=%(user)s AND Host = %(host)s;',
                 {'password': '******',
                  'user': '******',
                  'host': 'localhost',
                 }
             ),
             call().cursor().execute('FLUSH PRIVILEGES;'),
         )
         connect_mock.assert_has_calls(calls, any_order=True)
예제 #34
0
    def test_set_hibernate_timeout(self):
        '''
            Test to make sure we can set the hibernate timeout value
        '''
        mock = MagicMock()
        mock.side_effect = [
            "Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e  (Balanced)",
            self.query_ouput
        ]

        with patch.dict(powercfg.__salt__, {'cmd.run': mock}):
            powercfg.set_hibernate_timeout(0, "dc")
            calls = [
                call('powercfg /getactivescheme', python_shell=False),
                call(
                    'powercfg /setdcvalueindex 381b4222-f694-41f0-9685-ff5bb260df2e SUB_SLEEP HIBERNATEIDLE 0',
                    python_shell=False)
            ]
            mock.assert_has_calls(calls)
예제 #35
0
    def test_get_hibernate_timeout(self):
        '''
            Test to make sure we can get the hibernate timeout value
        '''
        mock = MagicMock()
        mock.side_effect = [
            "Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e  (Balanced)",
            self.query_ouput
        ]

        with patch.dict(powercfg.__salt__, {'cmd.run': mock}):
            ret = powercfg.get_hibernate_timeout()
            calls = [
                call('powercfg /getactivescheme', python_shell=False),
                call(
                    'powercfg /q 381b4222-f694-41f0-9685-ff5bb260df2e SUB_SLEEP HIBERNATEIDLE',
                    python_shell=False)
            ]
            mock.assert_has_calls(calls)

            self.assertEqual({'ac': 30, 'dc': 15}, ret)
예제 #36
0
    def test_enable(self):
        """
        Test for Enable the named service to start at boot
        """
        rc_update_mock = MagicMock(return_value=0)
        with patch.dict(gentoo_service.__salt__, {'cmd.retcode': rc_update_mock}):
            self.assertTrue(gentoo_service.enable('name'))
        rc_update_mock.assert_called_once_with('rc-update add name', python_shell=False)
        rc_update_mock.reset_mock()

        # move service from 'l1' to 'l2' runlevel
        service_name = 'name'
        runlevels = ['l1']
        level_list_mock = MagicMock(return_value=self.__services({service_name: runlevels}))
        with patch.dict(gentoo_service.__salt__, {'cmd.run': level_list_mock}):
            with patch.dict(gentoo_service.__salt__, {'cmd.retcode': rc_update_mock}):
                self.assertTrue(gentoo_service.enable('name', runlevels='l2'))
        rc_update_mock.assert_has_calls([call('rc-update delete name l1', python_shell=False),
                                         call('rc-update add name l2', python_shell=False)])
        rc_update_mock.reset_mock()

        # requested levels are the same as the current ones
        with patch.dict(gentoo_service.__salt__, {'cmd.run': level_list_mock}):
            with patch.dict(gentoo_service.__salt__, {'cmd.retcode': rc_update_mock}):
                self.assertTrue(gentoo_service.enable('name', runlevels='l1'))
        rc_update_mock.assert_not_called()
        rc_update_mock.reset_mock()

        # same as above with the list instead of the string
        with patch.dict(gentoo_service.__salt__, {'cmd.run': level_list_mock}):
            with patch.dict(gentoo_service.__salt__, {'cmd.retcode': rc_update_mock}):
                self.assertTrue(gentoo_service.enable('name', runlevels=['l1']))
        rc_update_mock.assert_not_called()
        rc_update_mock.reset_mock()

        # add service to 'l2' runlevel
        with patch.dict(gentoo_service.__salt__, {'cmd.run': level_list_mock}):
            with patch.dict(gentoo_service.__salt__, {'cmd.retcode': rc_update_mock}):
                self.assertTrue(gentoo_service.enable('name', runlevels=['l2', 'l1']))
        rc_update_mock.assert_called_once_with('rc-update add name l2', python_shell=False)
        rc_update_mock.reset_mock()

        # remove service from 'l1' runlevel
        runlevels = ['l1', 'l2']
        level_list_mock = MagicMock(return_value=self.__services({service_name: runlevels}))
        with patch.dict(gentoo_service.__salt__, {'cmd.run': level_list_mock}):
            with patch.dict(gentoo_service.__salt__, {'cmd.retcode': rc_update_mock}):
                self.assertTrue(gentoo_service.enable('name', runlevels=['l2']))
        rc_update_mock.assert_called_once_with('rc-update delete name l1', python_shell=False)
        rc_update_mock.reset_mock()

        # move service from 'l2' add to 'l3', leaving at l1
        with patch.dict(gentoo_service.__salt__, {'cmd.run': level_list_mock}):
            with patch.dict(gentoo_service.__salt__, {'cmd.retcode': rc_update_mock}):
                self.assertTrue(gentoo_service.enable('name', runlevels=['l1', 'l3']))
        rc_update_mock.assert_has_calls([call('rc-update delete name l2', python_shell=False),
                                         call('rc-update add name l3', python_shell=False)])
        rc_update_mock.reset_mock()

        # remove from l1, l3, and add to l2, l4, and leave at l5
        runlevels = ['l1', 'l3', 'l5']
        level_list_mock = MagicMock(return_value=self.__services({service_name: runlevels}))
        with patch.dict(gentoo_service.__salt__, {'cmd.run': level_list_mock}):
            with patch.dict(gentoo_service.__salt__, {'cmd.retcode': rc_update_mock}):
                self.assertTrue(gentoo_service.enable('name', runlevels=['l2', 'l4', 'l5']))
        rc_update_mock.assert_has_calls([call('rc-update delete name l1 l3', python_shell=False),
                                         call('rc-update add name l2 l4', python_shell=False)])
        rc_update_mock.reset_mock()

        # rc-update failed
        rc_update_mock = MagicMock(return_value=1)
        with patch.dict(gentoo_service.__salt__, {'cmd.retcode': rc_update_mock}):
            self.assertFalse(gentoo_service.enable('name'))
        rc_update_mock.assert_called_once_with('rc-update add name', python_shell=False)
        rc_update_mock.reset_mock()

        # move service delete failed
        runlevels = ['l1']
        level_list_mock = MagicMock(return_value=self.__services({service_name: runlevels}))
        with patch.dict(gentoo_service.__salt__, {'cmd.run': level_list_mock}):
            with patch.dict(gentoo_service.__salt__, {'cmd.retcode': rc_update_mock}):
                self.assertFalse(gentoo_service.enable('name', runlevels='l2'))
        rc_update_mock.assert_called_once_with('rc-update delete name l1', python_shell=False)
        rc_update_mock.reset_mock()

        # move service delete succeeds. add fails
        rc_update_mock = MagicMock()
        rc_update_mock.side_effect = [0, 1]
        with patch.dict(gentoo_service.__salt__, {'cmd.run': level_list_mock}):
            with patch.dict(gentoo_service.__salt__, {'cmd.retcode': rc_update_mock}):
                self.assertFalse(gentoo_service.enable('name', runlevels='l2'))
        rc_update_mock.assert_has_calls([call('rc-update delete name l1', python_shell=False),
                                         call('rc-update add name l2', python_shell=False)])
        rc_update_mock.reset_mock()
예제 #37
0
    def test_enable(self):
        """
        Test for Enable the named service to start at boot
        """
        rc_update_mock = MagicMock(return_value=0)
        with patch.dict(gentoo_service.__salt__,
                        {'cmd.retcode': rc_update_mock}):
            self.assertTrue(gentoo_service.enable('name'))
        rc_update_mock.assert_called_once_with('rc-update add name',
                                               python_shell=False)
        rc_update_mock.reset_mock()

        # move service from 'l1' to 'l2' runlevel
        service_name = 'name'
        runlevels = ['l1']
        level_list_mock = MagicMock(
            return_value=self.__services({service_name: runlevels}))
        with patch.dict(gentoo_service.__salt__, {'cmd.run': level_list_mock}):
            with patch.dict(gentoo_service.__salt__,
                            {'cmd.retcode': rc_update_mock}):
                self.assertTrue(gentoo_service.enable('name', runlevels='l2'))
        rc_update_mock.assert_has_calls([
            call('rc-update delete name l1', python_shell=False),
            call('rc-update add name l2', python_shell=False)
        ])
        rc_update_mock.reset_mock()

        # requested levels are the same as the current ones
        with patch.dict(gentoo_service.__salt__, {'cmd.run': level_list_mock}):
            with patch.dict(gentoo_service.__salt__,
                            {'cmd.retcode': rc_update_mock}):
                self.assertTrue(gentoo_service.enable('name', runlevels='l1'))
        self.assertTrue(rc_update_mock.call_count == 0)
        rc_update_mock.reset_mock()

        # same as above with the list instead of the string
        with patch.dict(gentoo_service.__salt__, {'cmd.run': level_list_mock}):
            with patch.dict(gentoo_service.__salt__,
                            {'cmd.retcode': rc_update_mock}):
                self.assertTrue(gentoo_service.enable('name',
                                                      runlevels=['l1']))
        self.assertTrue(rc_update_mock.call_count == 0)
        rc_update_mock.reset_mock()

        # add service to 'l2' runlevel
        with patch.dict(gentoo_service.__salt__, {'cmd.run': level_list_mock}):
            with patch.dict(gentoo_service.__salt__,
                            {'cmd.retcode': rc_update_mock}):
                self.assertTrue(
                    gentoo_service.enable('name', runlevels=['l2', 'l1']))
        rc_update_mock.assert_called_once_with('rc-update add name l2',
                                               python_shell=False)
        rc_update_mock.reset_mock()

        # remove service from 'l1' runlevel
        runlevels = ['l1', 'l2']
        level_list_mock = MagicMock(
            return_value=self.__services({service_name: runlevels}))
        with patch.dict(gentoo_service.__salt__, {'cmd.run': level_list_mock}):
            with patch.dict(gentoo_service.__salt__,
                            {'cmd.retcode': rc_update_mock}):
                self.assertTrue(gentoo_service.enable('name',
                                                      runlevels=['l2']))
        rc_update_mock.assert_called_once_with('rc-update delete name l1',
                                               python_shell=False)
        rc_update_mock.reset_mock()

        # move service from 'l2' add to 'l3', leaving at l1
        with patch.dict(gentoo_service.__salt__, {'cmd.run': level_list_mock}):
            with patch.dict(gentoo_service.__salt__,
                            {'cmd.retcode': rc_update_mock}):
                self.assertTrue(
                    gentoo_service.enable('name', runlevels=['l1', 'l3']))
        rc_update_mock.assert_has_calls([
            call('rc-update delete name l2', python_shell=False),
            call('rc-update add name l3', python_shell=False)
        ])
        rc_update_mock.reset_mock()

        # remove from l1, l3, and add to l2, l4, and leave at l5
        runlevels = ['l1', 'l3', 'l5']
        level_list_mock = MagicMock(
            return_value=self.__services({service_name: runlevels}))
        with patch.dict(gentoo_service.__salt__, {'cmd.run': level_list_mock}):
            with patch.dict(gentoo_service.__salt__,
                            {'cmd.retcode': rc_update_mock}):
                self.assertTrue(
                    gentoo_service.enable('name', runlevels=['l2', 'l4',
                                                             'l5']))
        rc_update_mock.assert_has_calls([
            call('rc-update delete name l1 l3', python_shell=False),
            call('rc-update add name l2 l4', python_shell=False)
        ])
        rc_update_mock.reset_mock()

        # rc-update failed
        rc_update_mock = MagicMock(return_value=1)
        with patch.dict(gentoo_service.__salt__,
                        {'cmd.retcode': rc_update_mock}):
            self.assertFalse(gentoo_service.enable('name'))
        rc_update_mock.assert_called_once_with('rc-update add name',
                                               python_shell=False)
        rc_update_mock.reset_mock()

        # move service delete failed
        runlevels = ['l1']
        level_list_mock = MagicMock(
            return_value=self.__services({service_name: runlevels}))
        with patch.dict(gentoo_service.__salt__, {'cmd.run': level_list_mock}):
            with patch.dict(gentoo_service.__salt__,
                            {'cmd.retcode': rc_update_mock}):
                self.assertFalse(gentoo_service.enable('name', runlevels='l2'))
        rc_update_mock.assert_called_once_with('rc-update delete name l1',
                                               python_shell=False)
        rc_update_mock.reset_mock()

        # move service delete succeeds. add fails
        rc_update_mock = MagicMock()
        rc_update_mock.side_effect = [0, 1]
        with patch.dict(gentoo_service.__salt__, {'cmd.run': level_list_mock}):
            with patch.dict(gentoo_service.__salt__,
                            {'cmd.retcode': rc_update_mock}):
                self.assertFalse(gentoo_service.enable('name', runlevels='l2'))
        rc_update_mock.assert_has_calls([
            call('rc-update delete name l1', python_shell=False),
            call('rc-update add name l2', python_shell=False)
        ])
        rc_update_mock.reset_mock()