Beispiel #1
0
    def test_pkg(self):
        '''
            Test to execute a packaged state run
        '''
        mock = MagicMock(side_effect=[False, True, True, True, True, True])
        with patch.object(os.path, 'isfile', mock):
            self.assertEqual(state.pkg("/tmp/state_pkg.tgz", "", "md5"), {})

            mock = MagicMock(side_effect=[False, 0, 0, 0, 0])
            with patch.object(salt.utils, 'get_hash', mock):
                self.assertDictEqual(
                    state.pkg("/tmp/state_pkg.tgz", "", "md5"), {})

                self.assertDictEqual(state.pkg("/tmp/state_pkg.tgz", 0, "md5"),
                                     {})

                MockTarFile.path = ""
                MockJson.flag = True
                with patch('salt.utils.fopen', mock_open()):
                    self.assertListEqual(
                        state.pkg("/tmp/state_pkg.tgz", 0, "md5"), [True])

                MockTarFile.path = ""
                MockJson.flag = False
                with patch('salt.utils.fopen', mock_open()):
                    self.assertTrue(state.pkg("/tmp/state_pkg.tgz", 0, "md5"))
Beispiel #2
0
    def test_pkg(self):
        '''
            Test to execute a packaged state run
        '''
        mock = MagicMock(side_effect=[False, True, True, True, True, True])
        with patch.object(os.path, 'isfile', mock):
            self.assertEqual(state.pkg("/tmp/state_pkg.tgz", "", "md5"), {})

            mock = MagicMock(side_effect=[False, 0, 0, 0, 0])
            with patch.object(salt.utils, 'get_hash', mock):
                self.assertDictEqual(state.pkg("/tmp/state_pkg.tgz", "", "md5"),
                                     {})

                self.assertDictEqual(state.pkg("/tmp/state_pkg.tgz", 0, "md5"),
                                     {})

                MockTarFile.path = ""
                MockJson.flag = True
                with patch('salt.utils.fopen', mock_open()):
                    self.assertListEqual(state.pkg("/tmp/state_pkg.tgz",
                                                   0,
                                                   "md5"),
                                         [True])

                MockTarFile.path = ""
                MockJson.flag = False
                with patch('salt.utils.fopen', mock_open()):
                    self.assertTrue(state.pkg("/tmp/state_pkg.tgz",
                                              0, "md5"))
 def test_persist_no_conf_success(self):
     '''
     Tests successful add of config file when previously not one
     '''
     mock = mock_open()
     with patch('salt.utils.fopen', mock_open(read_data=mock)) as m_open:
         darwin_sysctl.persist('net.inet.icmp.icmplim', 50)
         helper_open = m_open()
         helper_open.write.assert_called_once_with(
             '#\n# Kernel sysctl configuration\n#\n')
Beispiel #4
0
 def test_persist_no_conf_success(self):
     '''
     Tests successful add of config file when previously not one
     '''
     mock = mock_open()
     with patch('salt.utils.fopen', mock_open(read_data=mock)) as m_open:
         darwin_sysctl.persist('net.inet.icmp.icmplim', 50)
         helper_open = m_open()
         helper_open.write.assert_called_once_with(
             '#\n# Kernel sysctl configuration\n#\n')
Beispiel #5
0
 def test_persist_no_conf_failure(self):
     '''
     Tests adding of config file failure
     '''
     mock = mock_open()
     with patch('salt.utils.fopen', mock_open(read_data=mock)) as m_open:
         helper_open = m_open()
         helper_open.write.assertRaises(CommandExecutionError,
                                        darwin_sysctl.persist,
                                        'net.inet.icmp.icmplim',
                                        50, config=None)
Beispiel #6
0
 def test_diff_binary_files(self):
     fopen_effect = [
         mock_open(read_data="dummy binary").return_value,
         mock_open(read_data="dummy binary").return_value,
     ]
     with patch('salt.utils.fopen') as fopen_mock:
         fopen_mock.side_effect = fopen_effect
         module_ret = {
             "/tmp/foo3": MODULE_RET['DIFF']["/tmp/foo3"],
         }
         self.assertEqual(snapper.diff(), module_ret)
Beispiel #7
0
 def test_gen_keys(self):
     with patch('salt.utils.fopen', mock_open()):
         open_priv_wb = call('/keydir/keyname.pem', 'wb+')
         open_pub_wb = call('/keydir/keyname.pub', 'wb+')
         with patch('os.path.isfile', return_value=True):
             self.assertEqual(crypt.gen_keys('/keydir', 'keyname', 2048), '/keydir/keyname.pem')
             self.assertNotIn(open_priv_wb, salt.utils.fopen.mock_calls)
             self.assertNotIn(open_pub_wb, salt.utils.fopen.mock_calls)
         with patch('os.path.isfile', return_value=False):
             with patch('salt.utils.fopen', mock_open()):
                 crypt.gen_keys('/keydir', 'keyname', 2048)
                 salt.utils.fopen.assert_has_calls([open_priv_wb, open_pub_wb], any_order=True)
Beispiel #8
0
 def test_gen_keys(self):
     with patch('salt.utils.fopen', mock_open()):
         open_priv_wb = call('/keydir/keyname.pem', 'wb+')
         open_pub_wb = call('/keydir/keyname.pub', 'wb+')
         with patch('os.path.isfile', return_value=True):
             self.assertEqual(crypt.gen_keys('/keydir', 'keyname', 2048), '/keydir/keyname.pem')
             self.assertNotIn(open_priv_wb, salt.utils.fopen.mock_calls)
             self.assertNotIn(open_pub_wb, salt.utils.fopen.mock_calls)
         with patch('os.path.isfile', return_value=False):
             with patch('salt.utils.fopen', mock_open()):
                 crypt.gen_keys('/keydir', 'keyname', 2048)
                 salt.utils.fopen.assert_has_calls([open_priv_wb, open_pub_wb], any_order=True)
Beispiel #9
0
    def test_summary(self):
        '''
            Test to show a summary of the last puppet agent run
        '''
        mock_lst = MagicMock(return_value=[])
        with patch.dict(puppet.__salt__, {'cmd.run': mock_lst}):
            with patch('salt.utils.fopen',
                       mock_open(read_data="resources: 1")):
                self.assertDictEqual(puppet.summary(), {'resources': 1})

            with patch('salt.utils.fopen', mock_open()) as m_open:
                m_open.side_effect = IOError(13, 'Permission denied:', '/file')
                self.assertRaises(CommandExecutionError, puppet.summary)
Beispiel #10
0
 def test_diff_text_files(self):
     fopen_effect = [
         mock_open(read_data=FILE_CONTENT["/tmp/foo"]['pre']).return_value,
         mock_open(read_data=FILE_CONTENT["/tmp/foo"]['post']).return_value,
         mock_open(read_data=FILE_CONTENT["/tmp/foo2"]['post']).return_value,
     ]
     with patch('salt.utils.fopen') as fopen_mock:
         fopen_mock.side_effect = fopen_effect
         module_ret = {
             "/tmp/foo": MODULE_RET['DIFF']["/tmp/foo"],
             "/tmp/foo2": MODULE_RET['DIFF']["/tmp/foo2"],
         }
         self.assertEqual(snapper.diff(), module_ret)
Beispiel #11
0
    def test_summary(self):
        '''
            Test to show a summary of the last puppet agent run
        '''
        mock_lst = MagicMock(return_value=[])
        with patch.dict(puppet.__salt__, {'cmd.run': mock_lst}):
            with patch('salt.utils.fopen',
                        mock_open(read_data="resources: 1")):
                self.assertDictEqual(puppet.summary(), {'resources': 1})

            with patch('salt.utils.fopen', mock_open()) as m_open:
                m_open.side_effect = IOError(13, 'Permission denied:', '/file')
                self.assertRaises(CommandExecutionError, puppet.summary)
Beispiel #12
0
    def test_summary(self):
        '''
            Test to show a summary of the last puppet agent run
        '''
        mock_lst = MagicMock(return_value=[])
        with patch.dict(puppet.__salt__, {'cmd.run': mock_lst}):
            with patch('salt.utils.fopen',
                       mock_open(read_data="resources: 1")):
                self.assertDictEqual(puppet.summary(), {'resources': 1})

            with patch('salt.utils.fopen', mock_open()) as m_open:
                helper_open = m_open()
                helper_open.write.assertRaises(CommandExecutionError,
                                               puppet.summary)
Beispiel #13
0
    def test_summary(self):
        '''
            Test to show a summary of the last puppet agent run
        '''
        mock_lst = MagicMock(return_value=[])
        with patch.dict(puppet.__salt__, {'cmd.run': mock_lst}):
            with patch('salt.utils.fopen',
                        mock_open(read_data="resources: 1")):
                self.assertDictEqual(puppet.summary(), {'resources': 1})

            with patch('salt.utils.fopen', mock_open()) as m_open:
                helper_open = m_open()
                helper_open.write.assertRaises(CommandExecutionError,
                                                puppet.summary)
Beispiel #14
0
    def test_rm_fstab(self):
        '''
        Remove the mount point from the fstab
        '''
        mock_fstab = MagicMock(return_value={})
        with patch.object(mount, 'fstab', mock_fstab):
            with patch('salt.utils.fopen', mock_open()):
                self.assertTrue(mount.rm_fstab('name', 'device'))

        mock_fstab = MagicMock(return_value={'name': 'name'})
        with patch.object(mount, 'fstab', mock_fstab):
            with patch('salt.utils.fopen', mock_open()) as m_open:
                m_open.side_effect = IOError(13, 'Permission denied:', '/file')
                self.assertRaises(CommandExecutionError, mount.rm_fstab,
                                  'name', 'device')
Beispiel #15
0
    def test_check_request(self):
        '''
            Test to return the state request information
        '''
        mock = MagicMock(return_value=True)
        with patch.object(os.path, 'join', mock):
            mock = MagicMock(side_effect=[True, True, False])
            with patch.object(os.path, 'isfile', mock):
                with patch('salt.utils.fopen', mock_open()):
                    self.assertDictEqual(state.check_request(), {'A': 'B'})

                with patch('salt.utils.fopen', mock_open()):
                    self.assertEqual(state.check_request("A"), 'B')

                self.assertDictEqual(state.check_request(), {})
Beispiel #16
0
    def test_get_zone(self):
        '''
        Test to get current timezone (i.e. America/Denver)
        '''
        mock = MagicMock(side_effect=['Time zone: A', 'A'])
        with patch.object(salt.utils, 'which', return_value=True):
            with patch.dict(timezone.__salt__, {'cmd.run': mock}):
                self.assertEqual(timezone.get_zone(), 'A')

                self.assertRaises(CommandExecutionError, timezone.get_zone)

        with patch.object(salt.utils, 'which', return_value=False):
            file_data = '\n'.join(['#', 'A'])
            with patch('salt.utils.fopen',
                       mock_open(read_data=file_data),
                       create=True) as mfile:
                mfile.return_value.__iter__.return_value = file_data.splitlines(
                )
                with patch.dict(timezone.__grains__, {
                        'os_family': 'Debian',
                        'os': 'Debian'
                }):
                    self.assertEqual(timezone.get_zone(), '#\nA')

                with patch.dict(timezone.__grains__, {
                        'os_family': 'Gentoo',
                        'os': 'Gentoo'
                }):
                    self.assertEqual(timezone.get_zone(), '')

            with patch.dict(timezone.__grains__, {
                    'os_family': 'FreeBSD',
                    'os': 'FreeBSD'
            }):
                zone = 'America/Denver'
                linkpath = '/usr/share/zoneinfo/' + zone
                with patch.object(os, 'readlink', return_value=linkpath):
                    self.assertEqual(timezone.get_zone(), zone)

            with patch.dict(timezone.__grains__, {
                    'os_family': 'Solaris',
                    'os': 'Solaris'
            }):
                fl_data = 'TZ=Foo\n'
                with patch('salt.utils.fopen',
                           mock_open(read_data=fl_data)) as mfile:
                    mfile.return_value.__iter__.return_value = [fl_data]
                    self.assertEqual(timezone.get_zone(), 'Foo')
Beispiel #17
0
    def test_get_zone(self):
        '''
        Test to get current timezone (i.e. America/Denver)
        '''
        zone = 'MST'

        with patch.object(salt.utils, 'which', return_value=True):
            mock_cmd = MagicMock(return_value={'stderr': 'error', 'retcode': 1})
            with patch.dict(timezone.__salt__, {'cmd.run_all': mock_cmd}):
                self.assertRaises(CommandExecutionError, timezone.get_zone)

            mock_cmd = MagicMock(return_value={'stdout': 'Timezone: {0}'.format(zone),
                                               'retcode': 0})
            with patch.dict(timezone.__salt__, {'cmd.run_all': mock_cmd}):
                self.assertEqual(timezone.get_zone(), zone)

            mock_cmd = MagicMock(return_value={'stdout': 'ZoneCTL: {0}'.format(zone),
                                               'retcode': 0})
            with patch.dict(timezone.__salt__, {'cmd.run_all': mock_cmd}):
                self.assertRaises(CommandExecutionError, timezone.get_zone)

        with patch.object(salt.utils, 'which', return_value=False):
            file_data = '\n'.join(['#', 'A'])
            with patch('salt.utils.fopen', mock_open(read_data=file_data),
                       create=True) as mfile:
                mfile.return_value.__iter__.return_value = file_data.splitlines()
                with patch.dict(timezone.__grains__, {'os_family': 'Debian',
                                                      'os': 'Debian'}):
                    self.assertEqual(timezone.get_zone(), '#\nA')

                with patch.dict(timezone.__grains__, {'os_family': 'Gentoo',
                                                      'os': 'Gentoo'}):
                    self.assertEqual(timezone.get_zone(), '')

            with patch.dict(timezone.__grains__, {'os_family': 'FreeBSD',
                                                  'os': 'FreeBSD'}):
                zone = 'America/Denver'
                linkpath = '/usr/share/zoneinfo/' + zone
                with patch.object(os, 'readlink', return_value=linkpath):
                    self.assertEqual(timezone.get_zone(), zone)

            with patch.dict(timezone.__grains__, {'os_family': 'Solaris',
                                                  'os': 'Solaris'}):
                fl_data = 'TZ=Foo\n'
                with patch('salt.utils.fopen',
                           mock_open(read_data=fl_data)) as mfile:
                    mfile.return_value.__iter__.return_value = [fl_data]
                    self.assertEqual(timezone.get_zone(), 'Foo')
Beispiel #18
0
    def test_swaps(self):
        """
        Return a dict containing information on active swap
        """

        file_data = "\n".join(["Filename Type Size Used Priority", "/dev/sda1 partition 31249404 4100 -1"])
        with patch.dict(mount.__grains__, {"os": "", "kernel": ""}):
            with patch("salt.utils.fopen", mock_open(read_data=file_data), create=True) as m:
                m.return_value.__iter__.return_value = file_data.splitlines()

                self.assertDictEqual(
                    mount.swaps(),
                    {"/dev/sda1": {"priority": "-1", "size": "31249404", "type": "partition", "used": "4100"}},
                )

        file_data = "\n".join(
            ["Device Size Used Unknown Unknown Priority", "/dev/sda1 31249404 4100 unknown unknown -1"]
        )
        mock = MagicMock(return_value=file_data)
        with patch.dict(mount.__grains__, {"os": "OpenBSD", "kernel": "OpenBSD"}):
            with patch.dict(mount.__salt__, {"cmd.run_stdout": mock}):
                self.assertDictEqual(
                    mount.swaps(),
                    {"/dev/sda1": {"priority": "-1", "size": "31249404", "type": "partition", "used": "4100"}},
                )
Beispiel #19
0
 def test_get_saved_rules(self):
     '''
     Test if it return a data structure of the rules in the conf file
     '''
     with patch.dict(nftables.__grains__, {'os_family': 'Debian'}):
         with patch.object(salt.utils, 'fopen', MagicMock(mock_open())):
             self.assertListEqual(nftables.get_saved_rules(), [])
Beispiel #20
0
    def test_delete(self):
        '''
        Test to delete a DNS record.
        '''
        file_data = json.dumps({'A': 'B'})

        class MockAnswer(object):
            def __init__(self, *args, **kwargs):
                self.answer = [{'address': 'localhost'}]

            def rcode(self):
                return 0

        def mock_udp_query(*args, **kwargs):
            return MockAnswer

        with contextlib.nested(
                patch.object(dns.query, 'udp', mock_udp_query()),
                patch('salt.utils.fopen',
                      mock_open(read_data=file_data),
                      create=True),
                patch.object(dns.tsigkeyring, 'from_text', return_value=True),
                patch.object(ddns, '_get_keyring', return_value=None),
                patch.object(ddns, '_config', return_value=None)):
            self.assertTrue(ddns.delete(zone='A', name='B'))
Beispiel #21
0
    def test_push_success(self):
        '''
        Test if push succeeds.
        '''
        path = '/srv/salt/saltines'
        file_data = ''
        mock_buf_size = len(file_data)
        mock_id = 'You don\'t need to see his identification.'
        ret = True

        class MockChannel(object):
            @staticmethod
            def factory(__opts__):
                return MockChannel()

            def send(self, load):
                return 'channel info'

        class MockAuth(object):
            def gen_token(self, salt):
                return 'token info'

        def mock_auth_factory():
            return MockAuth()

        with patch('salt.transport.Channel', MockChannel):
            with patch('salt.modules.cp._auth', mock_auth_factory):
                with patch('salt.utils.fopen', mock_open(read_data=file_data)):
                    with patch.dict(cp.__opts__,
                                    {'file_buffer_size': mock_buf_size,
                                     'id': mock_id}):
                        self.assertEqual(cp.push(path), ret)
    def test_persist_no_conf_success(self):
        '''
        Tests successful add of config file when previously not one
        '''
        asn_cmd = {
            'pid': 1337,
            'retcode': 0,
            'stderr': '',
            'stdout': 'net.ipv4.ip_forward = 1'
        }
        mock_asn_cmd = MagicMock(return_value=asn_cmd)

        sys_cmd = 'systemd 208\n+PAM +LIBWRAP'
        mock_sys_cmd = MagicMock(return_value=sys_cmd)

        with patch('salt.utils.fopen', mock_open()) as m_open:
            with patch.dict(linux_sysctl.__salt__, {
                    'cmd.run_stdout': mock_sys_cmd,
                    'cmd.run_all': mock_asn_cmd
            }):
                with patch.dict(systemd.__context__,
                                {'salt.utils.systemd.booted': True}):
                    linux_sysctl.persist('net.ipv4.ip_forward', 1)
                    helper_open = m_open()
                    helper_open.write.assert_called_once_with(
                        '#\n# Kernel sysctl configuration\n#\n')
Beispiel #23
0
    def test_swaps(self):
        '''
        Return a dict containing information on active swap
        '''

        file_data = '\n'.join(['Filename Type Size Used Priority',
                               '/dev/sda1 partition 31249404 4100 -1'])
        with patch.dict(mount.__grains__, {'os': ''}):
            with patch('salt.utils.fopen',
                       mock_open(read_data=file_data),
                       create=True) as m:
                m.return_value.__iter__.return_value = file_data.splitlines()

                self.assertDictEqual(mount.swaps(), {'/dev/sda1':
                                                     {'priority': '-1',
                                                      'size': '31249404',
                                                      'type': 'partition',
                                                      'used': '4100'}})

        file_data = '\n'.join(['Device Size Used Unknown Unknown Priority',
                               '/dev/sda1 31249404 4100 unknown unknown -1'])
        mock = MagicMock(return_value=file_data)
        with patch.dict(mount.__grains__, {'os': 'OpenBSD'}):
            with patch.dict(mount.__salt__, {'cmd.run_stdout': mock}):
                self.assertDictEqual(mount.swaps(), {'/dev/sda1':
                                                     {'priority': '-1',
                                                      'size': '31249404',
                                                      'type': 'partition',
                                                      'used': '4100'}})
Beispiel #24
0
 def test_request(self):
     '''
         Test to request the local admin execute a state run
     '''
     mock = MagicMock(return_value=True)
     with patch.object(state, 'apply_', mock):
         with patch.dict(state.__opts__, {"cachedir": "D"}):
             mock = MagicMock(return_value=True)
             with patch.object(os.path, 'join', mock):
                 mock = MagicMock(return_value=
                                  {"test_run": "",
                                   "mods": "",
                                   "kwargs": ""})
                 with patch.object(state, 'check_request', mock):
                     mock = MagicMock(return_value=True)
                     with patch.object(os, 'umask', mock):
                         with patch.object(salt.utils, 'is_windows', mock):
                             with patch.dict(state.__salt__,
                                             {'cmd.run': mock}):
                                 with patch('salt.utils.fopen',
                                            mock_open()):
                                     mock = MagicMock(
                                                      return_value=True)
                                     with patch.object(os, 'umask',
                                                       mock):
                                         self.assertTrue(
                                                         state.request("A")
                                                         )
Beispiel #25
0
    def test_rm_fstab(self):
        '''
        Remove the mount point from the fstab
        '''
        mock_fstab = MagicMock(return_value={})
        with patch.object(mount, 'fstab', mock_fstab):
            with patch('salt.utils.fopen', mock_open()):
                self.assertTrue(mount.rm_fstab('name', 'device'))

        mock_fstab = MagicMock(return_value={'name': 'name'})
        with patch.object(mount, 'fstab', mock_fstab):
            with patch('salt.utils.fopen', mock_open()) as m_open:
                helper_open = m_open()
                helper_open.write.assertRaises(CommandExecutionError,
                                               mount.rm_fstab,
                                               config=None)
Beispiel #26
0
    def test_vfstab(self):
        '''
        List the content of the vfstab
        '''
        mock = MagicMock(return_value=False)
        with patch.object(os.path, 'isfile', mock):
            self.assertEqual(mount.vfstab(), {})

        mock = MagicMock(return_value=True)
        with patch.dict(mount.__grains__, {'kernel': 'SunOS'}):
            with patch.object(os.path, 'isfile', mock):
                file_data = '\n'.join([
                    '#',
                    'swap        -   /tmp                tmpfs    -   yes    size=2048m'
                ])
                with patch('salt.utils.fopen',
                           mock_open(read_data=file_data),
                           create=True) as m:
                    m.return_value.__iter__.return_value = file_data.splitlines(
                    )
                    self.assertEqual(
                        mount.fstab(), {
                            '/tmp': {
                                'device': 'swap',
                                'device_fsck': '-',
                                'fstype': 'tmpfs',
                                'mount_at_boot': 'yes',
                                'opts': ['size=2048m'],
                                'pass_fsck': '-'
                            }
                        })
Beispiel #27
0
def _present(name='testname',
             tick_script='/tmp/script.tick',
             task_type='stream',
             database='testdb',
             retention_policy='default',
             enable=True,
             task=None,
             define_result=True,
             enable_result=True,
             disable_result=True,
             script='test'):
    get_mock = Mock(return_value=task)
    define_mock = Mock(return_value=define_result)
    enable_mock = Mock(return_value=enable_result)
    disable_mock = Mock(return_value=disable_result)
    with patch.dict(kapacitor.__salt__, {
        'kapacitor.get_task': get_mock,
        'kapacitor.define_task': define_mock,
        'kapacitor.enable_task': enable_mock,
        'kapacitor.disable_task': disable_mock,
    }):
        with patch('salt.utils.fopen', mock_open(read_data=script)) as open_mock:
            retval = kapacitor.task_present(name, tick_script, task_type=task_type,
                database=database, retention_policy=retention_policy, enable=enable)
    return retval, get_mock, define_mock, enable_mock, disable_mock
Beispiel #28
0
    def test_swaps(self):
        '''
        Return a dict containing information on active swap
        '''

        file_data = '\n'.join(['Filename Type Size Used Priority',
                               '/dev/sda1 partition 31249404 4100 -1'])
        with patch.dict(mount.__grains__, {'os': '', 'kernel': ''}):
            with patch('salt.utils.fopen',
                       mock_open(read_data=file_data),
                       create=True) as m:
                m.return_value.__iter__.return_value = file_data.splitlines()

                self.assertDictEqual(mount.swaps(), {'/dev/sda1':
                                                     {'priority': '-1',
                                                      'size': '31249404',
                                                      'type': 'partition',
                                                      'used': '4100'}})

        file_data = '\n'.join(['Device Size Used Unknown Unknown Priority',
                               '/dev/sda1 31249404 4100 unknown unknown -1'])
        mock = MagicMock(return_value=file_data)
        with patch.dict(mount.__grains__, {'os': 'OpenBSD', 'kernel': 'OpenBSD'}):
            with patch.dict(mount.__salt__, {'cmd.run_stdout': mock}):
                self.assertDictEqual(mount.swaps(), {'/dev/sda1':
                                                     {'priority': '-1',
                                                      'size': '31249404',
                                                      'type': 'partition',
                                                      'used': '4100'}})
Beispiel #29
0
    def test_push_success(self):
        '''
        Test if push succeeds.
        '''
        path = '/srv/salt/saltines'
        file_data = ''
        mock_buf_size = len(file_data)
        mock_id = 'You don\'t need to see his identification.'
        ret = True

        class MockChannel(object):
            @staticmethod
            def factory(__opts__):
                return MockChannel()

            def send(self, load):
                return 'channel info'

        class MockAuth(object):
            def gen_token(self, salt):
                return 'token info'

        def mock_auth_factory():
            return MockAuth()

        with patch('salt.transport.Channel', MockChannel):
            with patch('salt.modules.cp._auth', mock_auth_factory):
                with patch('salt.utils.fopen', mock_open(read_data=file_data)):
                    with patch.dict(cp.__opts__,
                                    {'file_buffer_size': mock_buf_size,
                                     'id': mock_id}):
                        self.assertEqual(cp.push(path), ret)
Beispiel #30
0
    def test_fstab(self):
        '''
        List the content of the fstab
        '''
        mock = MagicMock(return_value=False)
        with patch.object(os.path, 'isfile', mock):
            self.assertEqual(mount.fstab(), {})

        mock = MagicMock(return_value=True)
        with patch.object(os.path, 'isfile', mock):
            file_data = '\n'.join(['#', 'A B C D,E,F G H'])
            with patch('salt.utils.fopen',
                       mock_open(read_data=file_data),
                       create=True) as m:
                m.return_value.__iter__.return_value = file_data.splitlines()
                self.assertEqual(
                    mount.fstab(), {
                        'B': {
                            'device': 'A',
                            'dump': 'G',
                            'fstype': 'C',
                            'opts': ['D', 'E', 'F'],
                            'pass': '******'
                        }
                    })
Beispiel #31
0
    def test_keys(self):
        '''
        Test to manage libvirt keys.
        '''
        name = 'sunrise'

        ret = {'name': name,
               'result': True,
               'comment': '',
               'changes': {}}

        mock = MagicMock(side_effect=[[], ['libvirt.servercert.pem'],
                                      {'libvirt.servercert.pem': 'A'}])
        with patch.dict(libvirt.__salt__, {'pillar.ext': mock}):
            comt = ('All keys are correct')
            ret.update({'comment': comt})
            self.assertDictEqual(libvirt.keys(name), ret)

            with patch.dict(libvirt.__opts__, {'test': True}):
                comt = ('Libvirt keys are set to be updated')
                ret.update({'comment': comt, 'result': None})
                self.assertDictEqual(libvirt.keys(name), ret)

            with patch.dict(libvirt.__opts__, {'test': False}):
                with patch.object(salt.utils, 'fopen', MagicMock(mock_open())):
                    comt = ('Updated libvirt certs and keys')
                    ret.update({'comment': comt, 'result': True,
                                'changes': {'servercert': 'new'}})
                    self.assertDictEqual(libvirt.keys(name), ret)
    def test_persist_read_conf_success(self):
        '''
        Tests sysctl.conf read success
        '''
        asn_cmd = {
            'pid': 1337,
            'retcode': 0,
            'stderr': '',
            'stdout': 'net.ipv4.ip_forward = 1'
        }
        mock_asn_cmd = MagicMock(return_value=asn_cmd)

        sys_cmd = 'systemd 208\n+PAM +LIBWRAP'
        mock_sys_cmd = MagicMock(return_value=sys_cmd)

        with patch('salt.utils.fopen', mock_open()):
            with patch.dict(linux_sysctl.__salt__, {
                    'cmd.run_stdout': mock_sys_cmd,
                    'cmd.run_all': mock_asn_cmd
            }):
                with patch.dict(systemd.__context__,
                                {'salt.utils.systemd.booted': True}):
                    self.assertEqual(
                        linux_sysctl.persist('net.ipv4.ip_forward', 1),
                        'Updated')
Beispiel #33
0
 def test_config(self):
     '''
     Test if it create VirtualHost configuration files
     '''
     with patch('salt.utils.fopen', mock_open()):
         self.assertEqual(apache.config('/ports.conf',
                                        [{'Listen': '22'}]), 'Listen 22')
Beispiel #34
0
    def test_keys(self):
        '''
        Test to manage libvirt keys.
        '''
        name = 'sunrise'

        ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}

        mock = MagicMock(side_effect=[[], ['libvirt.servercert.pem'], {
            'libvirt.servercert.pem': 'A'
        }])
        with patch.dict(libvirt.__salt__, {'pillar.ext': mock}):
            comt = ('All keys are correct')
            ret.update({'comment': comt})
            self.assertDictEqual(libvirt.keys(name), ret)

            with patch.dict(libvirt.__opts__, {'test': True}):
                comt = ('Libvirt keys are set to be updated')
                ret.update({'comment': comt, 'result': None})
                self.assertDictEqual(libvirt.keys(name), ret)

            with patch.dict(libvirt.__opts__, {'test': False}):
                with patch.object(salt.utils, 'fopen', MagicMock(mock_open())):
                    comt = ('Updated libvirt certs and keys')
                    ret.update({
                        'comment': comt,
                        'result': True,
                        'changes': {
                            'servercert': 'new'
                        }
                    })
                    self.assertDictEqual(libvirt.keys(name), ret)
Beispiel #35
0
    def test_check_request(self):
        '''
            Test to return the state request information
        '''
        with patch.dict(state.__opts__, {"cachedir": "D"}):
            mock = MagicMock(return_value=True)
            with patch.object(os.path, 'join', mock):
                mock = MagicMock(side_effect=[True, True, False])
                with patch.object(os.path, 'isfile', mock):
                    with patch('salt.utils.fopen', mock_open()):
                        self.assertDictEqual(state.check_request(), {'A': 'B'})

                    with patch('salt.utils.fopen', mock_open()):
                        self.assertEqual(state.check_request("A"), 'B')

                    self.assertDictEqual(state.check_request(), {})
Beispiel #36
0
    def test_vfstab(self):
        """
        List the content of the vfstab
        """
        mock = MagicMock(return_value=False)
        with patch.object(os.path, "isfile", mock):
            self.assertEqual(mount.vfstab(), {})

        mock = MagicMock(return_value=True)
        with patch.dict(mount.__grains__, {"kernel": "SunOS"}):
            with patch.object(os.path, "isfile", mock):
                file_data = "\n".join(["#", "swap        -   /tmp                tmpfs    -   yes    size=2048m"])
                with patch("salt.utils.fopen", mock_open(read_data=file_data), create=True) as m:
                    m.return_value.__iter__.return_value = file_data.splitlines()
                    self.assertEqual(
                        mount.fstab(),
                        {
                            "/tmp": {
                                "device": "swap",
                                "device_fsck": "-",
                                "fstype": "tmpfs",
                                "mount_at_boot": "yes",
                                "opts": ["size=2048m"],
                                "pass_fsck": "-",
                            }
                        },
                    )
Beispiel #37
0
 def test_get_saved_rules(self):
     '''
     Test if it return a data structure of the rules in the conf file
     '''
     with patch.dict(nftables.__grains__, {'os_family': 'Debian'}):
         with patch.object(salt.utils, 'fopen', MagicMock(mock_open())):
             self.assertListEqual(nftables.get_saved_rules(), [])
Beispiel #38
0
 def test_request(self):
     '''
         Test to request the local admin execute a state run
     '''
     mock = MagicMock(return_value=True)
     with patch.object(state, 'apply_', mock):
         with patch.dict(state.__opts__, {"cachedir": "D"}):
             mock = MagicMock(return_value=True)
             with patch.object(os.path, 'join', mock):
                 mock = MagicMock(return_value={
                     "test_run": "",
                     "mods": "",
                     "kwargs": ""
                 })
                 with patch.object(state, 'check_request', mock):
                     mock = MagicMock(return_value=True)
                     with patch.object(os, 'umask', mock):
                         with patch.object(salt.utils, 'is_windows', mock):
                             with patch.dict(state.__salt__,
                                             {'cmd.run': mock}):
                                 with patch('salt.utils.fopen',
                                            mock_open()):
                                     mock = MagicMock(return_value=True)
                                     with patch.object(os, 'umask', mock):
                                         self.assertTrue(state.request("A"))
Beispiel #39
0
    def test_cert_info(self):
        '''
        Test cert info
        '''
        ca_path = '/tmp/test_tls'
        ca_name = 'test_ca'
        certp = '{0}/{1}/{2}_ca_cert.crt'.format(ca_path, ca_name, ca_name)
        ret = {
            'not_after':
            1462379961,
            'signature_algorithm':
            'sha256WithRSAEncryption',
            'extensions':
            None,
            'fingerprint': ('96:72:B3:0A:1D:34:37:05:75:57:44:7E:08:81:A7:09:'
                            '0C:E1:8F:5F:4D:0C:49:CE:5B:D2:6B:45:D3:4D:FF:31'),
            'serial_number':
            284092004844685647925744086791559203700,
            'subject': {
                'C': 'US',
                'CN': 'localhost',
                'L': 'Salt Lake City',
                'O': 'SaltStack',
                'ST': 'Utah',
                'emailAddress': '*****@*****.**'
            },
            'not_before':
            1430843961,
            'issuer': {
                'C': 'US',
                'CN': 'localhost',
                'L': 'Salt Lake City',
                'O': 'SaltStack',
                'ST': 'Utah',
                'emailAddress': '*****@*****.**'
            }
        }

        def ignore_extensions(data):
            '''
            Ignore extensions pending a resolution of issue 24338
            '''
            if 'extensions' in data.keys():
                data['extensions'] = None
            return data

        # older pyopenssl versions don't have extensions or
        # signature_algorithms
        def remove_not_in_result(source, reference):
            if 'signature_algorithm' not in reference:
                del source['signature_algorithm']
            if 'extensions' not in reference:
                del source['extensions']

        with patch('salt.utils.fopen',
                   mock_open(read_data=_TLS_TEST_DATA['ca_cert'])):
            result = ignore_extensions(tls.cert_info(certp))
        remove_not_in_result(ret, result)
        self.assertEqual(result, ret)
Beispiel #40
0
 def test_set_host_true(self):
     """
     Tests true if the alias is set
     """
     with patch("salt.utils.fopen", mock_open()):
         mock_opt = MagicMock(return_value=None)
         with patch.dict(hosts.__salt__, {"config.option": mock_opt}):
             self.assertTrue(hosts.set_host("10.10.10.10", "Salt1"))
Beispiel #41
0
 def test_add_host_create_entry(self):
     """
     Tests if specified host entry gets added from the hosts file
     """
     with patch("salt.utils.fopen", mock_open()):
         mock_opt = MagicMock(return_value=None)
         with patch.dict(hosts.__salt__, {"config.option": mock_opt}):
             self.assertTrue(hosts.add_host("10.10.10.10", "Salt1"))
Beispiel #42
0
 def test_dump(self):
     '''
     Test if it replace the entire datastore with a passed data structure
     '''
     mock = MagicMock(return_value='/')
     with patch.dict(data.__opts__, {'cachedir': mock}):
         with patch('salt.utils.fopen', mock_open()):
             self.assertTrue(data.dump('{"eggs": "spam"}'))
Beispiel #43
0
    def test_disable(self):
        '''
            Test to disable the puppet agent
        '''
        mock_lst = MagicMock(return_value=[])
        with patch.dict(puppet.__salt__, {'cmd.run': mock_lst}):
            mock = MagicMock(side_effect=[True, False])
            with patch.object(os.path, 'isfile', mock):
                self.assertFalse(puppet.disable())

                with patch('salt.utils.fopen', mock_open()):
                    self.assertTrue(puppet.disable())

                with patch('salt.utils.fopen', mock_open()) as m_open:
                    helper_open = m_open()
                    helper_open.write.assertRaises(CommandExecutionError,
                                                    puppet.disable)
Beispiel #44
0
 def test_hosts_append(self):
     with patch('salt.utils.fopen',
                mock_open(read_data=mock_hosts_file)) as m_open:
         dnsutil.hosts_append('/etc/hosts', '127.0.0.1',
                              'ad1.yuk.co,ad2.yuk.co')
         helper_open = m_open()
         helper_open.write.assert_called_once_with(
             '\n127.0.0.1 ad1.yuk.co ad2.yuk.co')
Beispiel #45
0
 def test_read_file(self):
     '''
     Test if the parsing function works
     '''
     with patch('salt.utils.fopen', mock_open(read_data=MOCK_FILE)):
         self.assertListEqual(pam.read_file('/etc/pam.d/login'),
                              [{'arguments': [], 'control_flag': 'ok',
                                'interface': 'ok', 'module': 'ignore'}])
Beispiel #46
0
 def test_hosts_remove(self):
     to_remove = 'ad1.yuk.co'
     new_mock_file = mock_hosts_file + '\n127.0.0.1 ' + to_remove + '\n'
     with patch('salt.utils.fopen', mock_open(read_data=new_mock_file)) as m_open:
         dnsutil.hosts_remove('/etc/hosts', to_remove)
         helper_open = m_open()
         calls_list = helper_open.method_calls
         self.assertEqual(calls_list, mock_calls_list)
Beispiel #47
0
 def test_config(self):
     '''
     Test if it create VirtualHost configuration files
     '''
     with patch('salt.utils.fopen', mock_open()):
         self.assertEqual(apache.config('/ports.conf', [{
             'Listen': '22'
         }]), 'Listen 22')
Beispiel #48
0
 def _render_yaml(data):
     '''
     Takes a YAML string, puts it into a mock file, passes that to the YAML
     SaltYamlSafeLoader and then returns the rendered/parsed YAML data
     '''
     with patch('salt.utils.fopen', mock_open(read_data=data)) as mocked_file:
         with salt.utils.fopen(mocked_file) as mocked_stream:
             return SaltYamlSafeLoader(mocked_stream).get_data()
Beispiel #49
0
 def test_add_host_create_entry(self):
     '''
     Tests if specified host entry gets added from the hosts file
     '''
     with patch('salt.utils.fopen', mock_open()):
         mock_opt = MagicMock(return_value=None)
         with patch.dict(hosts.__salt__, {'config.option': mock_opt}):
             self.assertTrue(hosts.add_host('10.10.10.10', 'Salt1'))
Beispiel #50
0
 def test_dump(self):
     '''
     Test if it replace the entire datastore with a passed data structure
     '''
     mock = MagicMock(return_value='/')
     with patch.dict(data.__opts__, {'cachedir': mock}):
         with patch('salt.utils.fopen', mock_open()):
             self.assertTrue(data.dump('{"eggs": "spam"}'))
Beispiel #51
0
 def test_set_host_true(self):
     '''
     Tests true if the alias is set
     '''
     with patch('salt.utils.fopen', mock_open()):
         mock_opt = MagicMock(return_value=None)
         with patch.dict(hosts.__salt__, {'config.option': mock_opt}):
             self.assertTrue(hosts.set_host('10.10.10.10', 'Salt1'))
Beispiel #52
0
 def test_add_host_create_entry(self):
     '''
     Tests if specified host entry gets added from the hosts file
     '''
     with patch('salt.utils.fopen', mock_open()):
         mock_opt = MagicMock(return_value=None)
         with patch.dict(hosts.__salt__, {'config.option': mock_opt}):
             self.assertTrue(hosts.add_host('10.10.10.10', 'Salt1'))
Beispiel #53
0
 def test_set_host_true(self):
     '''
     Tests true if the alias is set
     '''
     with patch('salt.utils.fopen', mock_open()):
         mock_opt = MagicMock(return_value=None)
         with patch.dict(hosts.__salt__, {'config.option': mock_opt}):
             self.assertTrue(hosts.set_host('10.10.10.10', 'Salt1'))
Beispiel #54
0
    def test_status(self):
        '''
            Test to display puppet agent status
        '''
        mock_lst = MagicMock(return_value=[])
        with patch.dict(puppet.__salt__, {'cmd.run': mock_lst}):
            mock = MagicMock(return_value=True)
            with patch.object(puppet, '_check_puppet', mock):
                mock = MagicMock(side_effect=[True])
                with patch.object(os.path, 'isfile', mock):
                    self.assertEqual(puppet.status(),
                                     "Administratively disabled")

                mock = MagicMock(side_effect=[False, True])
                with patch.object(os.path, 'isfile', mock):
                    with patch('salt.utils.fopen', mock_open(read_data="1")):
                        mock = MagicMock(return_value=True)
                        with patch.object(os, 'kill', mock):
                            self.assertEqual(puppet.status(),
                                             "Applying a catalog")

                mock = MagicMock(side_effect=[False, True])
                with patch.object(os.path, 'isfile', mock):
                    with patch('salt.utils.fopen', mock_open()):
                        mock = MagicMock(return_value=True)
                        with patch.object(os, 'kill', mock):
                            self.assertEqual(puppet.status(), "Stale lockfile")

                mock = MagicMock(side_effect=[False, False, True])
                with patch.object(os.path, 'isfile', mock):
                    with patch('salt.utils.fopen', mock_open(read_data="1")):
                        mock = MagicMock(return_value=True)
                        with patch.object(os, 'kill', mock):
                            self.assertEqual(puppet.status(), "Idle daemon")

                mock = MagicMock(side_effect=[False, False, True])
                with patch.object(os.path, 'isfile', mock):
                    with patch('salt.utils.fopen', mock_open()):
                        mock = MagicMock(return_value=True)
                        with patch.object(os, 'kill', mock):
                            self.assertEqual(puppet.status(), "Stale pidfile")

                mock = MagicMock(side_effect=[False, False, False])
                with patch.object(os.path, 'isfile', mock):
                    self.assertEqual(puppet.status(), "Stopped")
Beispiel #55
0
 def test_rm_fstab(self):
     """
     Remove the mount point from the fstab
     """
     mock_fstab = MagicMock(return_value={})
     with patch.dict(mount.__grains__, {"kernel": ""}):
         with patch.object(mount, "fstab", mock_fstab):
             with patch("salt.utils.fopen", mock_open()):
                 self.assertTrue(mount.rm_fstab("name", "device"))
Beispiel #56
0
 def test_persist_no_conf_failure(self):
     '''
     Tests adding of config file failure
     '''
     with patch('salt.utils.fopen', mock_open()) as m_open:
         helper_open = m_open()
         helper_open.write.assertRaises(CommandExecutionError,
                                        linux_sysctl.persist,
                                        'net.ipv4.ip_forward',
                                        1, config=None)