Exemplo n.º 1
0
    def test_no_modprobe_cmd(self):
        '''Test user_data_rhevm() with no modprobe command.'''

        self.m_modprobe_floppy.side_effect = util.ProcessExecutionError(
            "No such file or dir")
        dsrc = dsac.DataSourceAltCloud({}, None, self.paths)
        self.assertEqual(False, dsrc.user_data_rhevm())
Exemplo n.º 2
0
 def test_get_device_info_from_zpool_handles_no_zpool(self, m_sub, m_os):
     """Handle case where there is no zpool command"""
     # mock /dev/zfs exists
     m_os.path.exists.return_value = True
     m_sub.side_effect = util.ProcessExecutionError("No zpool cmd")
     ret = util.get_device_info_from_zpool('vmzroot')
     self.assertIsNone(ret)
Exemplo n.º 3
0
    def test_udevadm_fails(self):
        '''Test user_data_rhevm() where udevadm fails.'''

        self.m_udevadm_settle.side_effect = util.ProcessExecutionError(
            "Failed settle.")
        dsrc = dsac.DataSourceAltCloud({}, None, self.paths)
        self.assertEqual(False, dsrc.user_data_rhevm())
Exemplo n.º 4
0
    def test_modprobe_fails(self):
        '''Test user_data_rhevm() where modprobe fails.'''

        self.m_modprobe_floppy.side_effect = util.ProcessExecutionError(
            "Failed modprobe")
        dsrc = dsac.DataSourceAltCloud({}, None, self.paths)
        self.assertEqual(False, dsrc.user_data_rhevm())
Exemplo n.º 5
0
 def test_no_retries_on_none(self, m_subp, m_sleep):
     """retry should not be done if retries is None."""
     m_subp.side_effect = util.ProcessExecutionError(
         stdout='', stderr='', exit_code=2, cmd=['mycmd'])
     with self.assertRaises(ValueError):
         gpg.recv_key("ABCD", "keyserver.example.com", retries=None)
     m_sleep.assert_not_called()
Exemplo n.º 6
0
 def test_retries_on_subp_exc(self, m_subp, m_sleep):
     """retry should be done on gpg receive keys failure."""
     retries = (1, 2, 4)
     my_exc = util.ProcessExecutionError(
         stdout='', stderr='', exit_code=2, cmd=['mycmd'])
     m_subp.side_effect = (my_exc, my_exc, ('', ''))
     gpg.recv_key("ABCD", "keyserver.example.com", retries=retries)
     self.assertEqual([mock.call(1), mock.call(2)], m_sleep.call_args_list)
Exemplo n.º 7
0
 def test_pexec_error_indent_text(self):
     error = util.ProcessExecutionError()
     msg = 'abc\ndef'
     formatted = 'abc\n{0}def'.format(' ' * 4)
     self.assertEqual(error._indent_text(msg, indent_level=4), formatted)
     self.assertEqual(error._indent_text(msg.encode(), indent_level=4),
                      formatted.encode())
     self.assertIsInstance(
         error._indent_text(msg.encode()), type(msg.encode()))
Exemplo n.º 8
0
 def test_pexec_error_empty_msgs(self):
     error = util.ProcessExecutionError()
     self.assertTrue(all(attr == self.empty_attr for attr in
                         (error.stderr, error.stdout, error.reason)))
     self.assertEqual(error.description, self.empty_description)
     self.assertEqual(str(error), self.template.format(
         description=self.empty_description, exit_code=self.empty_attr,
         reason=self.empty_attr, stdout=self.empty_attr,
         stderr=self.empty_attr, cmd=self.empty_attr))
Exemplo n.º 9
0
 def test_notfound_and_warns_on_unexpected_exit_code(self, m_subp, m_which):
     """If vmware-rpctool exits non zero or 1, warnings should be logged."""
     m_which.return_value = self.rpctool_path
     m_subp.side_effect = util.ProcessExecutionError(
         stdout=None, stderr="No value found", exit_code=2, cmd=["unused"])
     self.assertEqual(NOT_FOUND, dsovf.transport_vmware_guestinfo())
     self.assertEqual(1, m_subp.call_count)
     self.assertIn("WARNING", self.logs.getvalue(),
                   "exit code of 2 by rpctool should log WARNING.")
Exemplo n.º 10
0
 def test_notfound_on_exit_code_1(self, m_subp, m_which):
     """If vmware-rpctool exits 1, then must return not found."""
     m_which.return_value = self.rpctool_path
     m_subp.side_effect = util.ProcessExecutionError(
         stdout="", stderr="No value found", exit_code=1, cmd=["unused"])
     self.assertEqual(NOT_FOUND, dsovf.transport_vmware_guestinfo())
     self.assertEqual(1, m_subp.call_count)
     self.assertNotIn("WARNING", self.logs.getvalue(),
                      "exit code of 1 by rpctool should not cause warning.")
Exemplo n.º 11
0
 def test_raises_error_after_retries(self, m_subp, m_sleep):
     """If the final run fails, error should be raised."""
     naplen = 1
     keyid, keyserver = ("ABCD", "keyserver.example.com")
     m_subp.side_effect = util.ProcessExecutionError(
         stdout='', stderr='', exit_code=2, cmd=['mycmd'])
     with self.assertRaises(ValueError) as rcm:
         gpg.recv_key(keyid, keyserver, retries=(naplen,))
     self.assertIn(keyid, str(rcm.exception))
     self.assertIn(keyserver, str(rcm.exception))
     m_sleep.assert_called_with(naplen)
Exemplo n.º 12
0
 def test_configure_ua_attach_error(self, m_subp):
     """Errors from ua attach command are raised."""
     m_subp.side_effect = util.ProcessExecutionError(
         'Invalid token SomeToken')
     with self.assertRaises(RuntimeError) as context_manager:
         configure_ua(token='SomeToken')
     self.assertEqual(
         'Failure attaching Ubuntu Advantage:\nUnexpected error while'
         ' running command.\nCommand: -\nExit code: -\nReason: -\n'
         'Stdout: Invalid token SomeToken\nStderr: -',
         str(context_manager.exception))
Exemplo n.º 13
0
 def test_pexec_error_single_line_msgs(self):
     stdout_msg = 'out out'
     stderr_msg = 'error error'
     cmd = 'test command'
     exit_code = 3
     error = util.ProcessExecutionError(
         stdout=stdout_msg, stderr=stderr_msg, exit_code=3, cmd=cmd)
     self.assertEqual(str(error), self.template.format(
         description=self.empty_description, stdout=stdout_msg,
         stderr=stderr_msg, exit_code=str(exit_code),
         reason=self.empty_attr, cmd=cmd))
Exemplo n.º 14
0
 def test_get_tools_config_internal_exception(self):
     """
     This test is designed to verify the behavior if internal exception
     is raised.
     """
     with mock.patch.object(util, 'which', return_value='/dummy/path'):
         with mock.patch.object(util, 'subp',
                                return_value=('key=value', b''),
                                side_effect=util.ProcessExecutionError(
                                    "subp failed", exit_code=99)):
             # verify return value is 'defaultVal', not 'value'.
             self.assertEqual(
                 get_tools_config('section', 'key', 'defaultVal'),
                 'defaultVal')
Exemplo n.º 15
0
 def test_pexec_error_multi_line_msgs(self):
     # make sure bytes is converted handled properly when formatting
     stdout_msg = 'multi\nline\noutput message'.encode()
     stderr_msg = 'multi\nline\nerror message\n\n\n'
     error = util.ProcessExecutionError(stdout=stdout_msg,
                                        stderr=stderr_msg)
     self.assertEqual(
         str(error), '\n'.join((
             '{description}',
             'Command: {empty_attr}',
             'Exit code: {empty_attr}',
             'Reason: {empty_attr}',
             'Stdout: multi',
             '        line',
             '        output message',
             'Stderr: multi',
             '        line',
             '        error message',
         )).format(description=self.empty_description,
                   empty_attr=self.empty_attr))
Exemplo n.º 16
0
 def test_not_is_registered(self, mock_util_subp):
     mock_util_subp.side_effect = util.ProcessExecutionError(exit_code=1)
     self.assertFalse(cc_spacewalk.is_registered())
Exemplo n.º 17
0
 def test_pexec_error_type(self):
     self.assertIsInstance(util.ProcessExecutionError(), IOError)
Exemplo n.º 18
0
 def test_snap_config_add_assertions_ack_fails(self, msubp, mwrite):
     msubp.side_effect = [util.ProcessExecutionError("Invalid assertion")]
     self.assertRaises(util.ProcessExecutionError, add_assertions,
                       self.test_assertions)
Exemplo n.º 19
0
 def _dmidecode_subp(cmd):
     if cmd[-1] != key:
         raise util.ProcessExecutionError()
     return (content, error)
Exemplo n.º 20
0
 def test_subp_exception_raises_to_caller(self, m_subp):
     m_subp.side_effect = util.ProcessExecutionError("BOOM")
     self.assertRaises(util.ProcessExecutionError, util.udevadm_settle)
Exemplo n.º 21
0
class TestRbxDataSource(CiTestCase):
    parsed_user = None
    allowed_subp = ['bash']

    def _fetch_distro(self, kind):
        cls = distros.fetch(kind)
        paths = helpers.Paths({})
        return cls(kind, {}, paths)

    def setUp(self):
        super(TestRbxDataSource, self).setUp()
        self.tmp = self.tmp_dir()
        self.paths = helpers.Paths({
            'cloud_dir': self.tmp,
            'run_dir': self.tmp
        })

        # defaults for few tests
        self.ds = ds.DataSourceRbxCloud
        self.seed_dir = self.paths.seed_dir
        self.sys_cfg = {'datasource': {'RbxCloud': {'dsmode': 'local'}}}

    def test_seed_read_user_data_callback_empty_file(self):
        populate_user_metadata(self.seed_dir, '')
        populate_cloud_metadata(self.seed_dir, {})
        results = ds.read_user_data_callback(self.seed_dir)

        self.assertIsNone(results)

    def test_seed_read_user_data_callback_valid_disk(self):
        populate_user_metadata(self.seed_dir, '')
        populate_cloud_metadata(self.seed_dir, CLOUD_METADATA)
        results = ds.read_user_data_callback(self.seed_dir)

        self.assertNotEqual(results, None)
        self.assertTrue('userdata' in results)
        self.assertTrue('metadata' in results)
        self.assertTrue('cfg' in results)

    def test_seed_read_user_data_callback_userdata(self):
        userdata = "#!/bin/sh\nexit 1"
        populate_user_metadata(self.seed_dir, userdata)
        populate_cloud_metadata(self.seed_dir, CLOUD_METADATA)

        results = ds.read_user_data_callback(self.seed_dir)

        self.assertNotEqual(results, None)
        self.assertTrue('userdata' in results)
        self.assertEqual(results['userdata'], userdata)

    def test_generate_network_config(self):
        expected = {
            'version':
            1,
            'config': [{
                'subnets': [{
                    'control': 'auto',
                    'dns_nameservers': ['8.8.8.8', '8.8.4.4'],
                    'netmask': '255.255.248.0',
                    'address': '62.181.8.174',
                    'type': 'static',
                    'gateway': '62.181.8.1'
                }],
                'type':
                'physical',
                'name':
                'eth0',
                'mac_address':
                '00:15:5d:ff:0f:03'
            }, {
                'subnets': [{
                    'control': 'auto',
                    'dns_nameservers': ['9.9.9.9', '8.8.8.8'],
                    'netmask': '255.255.255.0',
                    'address': '10.209.78.11',
                    'type': 'static',
                    'gateway': '10.209.78.1'
                }],
                'type':
                'physical',
                'name':
                'eth1',
                'mac_address':
                '00:15:5d:ff:0f:24'
            }]
        }
        self.assertTrue(ds.generate_network_config(CLOUD_METADATA['netadp']),
                        expected)

    @mock.patch(DS_PATH + '.util.subp')
    def test_gratuitous_arp_run_standard_arping(self, m_subp):
        """Test handle run arping & parameters."""
        items = [
            {
                'destination': '172.17.0.2',
                'source': '172.16.6.104'
            },
            {
                'destination': '172.17.0.2',
                'source': '172.16.6.104',
            },
        ]
        ds.gratuitous_arp(items, self._fetch_distro('ubuntu'))
        self.assertEqual([
            mock.call(
                ['arping', '-c', '2', '-S', '172.16.6.104', '172.17.0.2']),
            mock.call(
                ['arping', '-c', '2', '-S', '172.16.6.104', '172.17.0.2'])
        ], m_subp.call_args_list)

    @mock.patch(DS_PATH + '.util.subp')
    def test_handle_rhel_like_arping(self, m_subp):
        """Test handle on RHEL-like distros."""
        items = [{
            'source': '172.16.6.104',
            'destination': '172.17.0.2',
        }]
        ds.gratuitous_arp(items, self._fetch_distro('fedora'))
        self.assertEqual([
            mock.call(
                ['arping', '-c', '2', '-s', '172.16.6.104', '172.17.0.2'])
        ], m_subp.call_args_list)

    @mock.patch(DS_PATH + '.util.subp',
                side_effect=util.ProcessExecutionError())
    def test_continue_on_arping_error(self, m_subp):
        """Continue when command error"""
        items = [
            {
                'destination': '172.17.0.2',
                'source': '172.16.6.104'
            },
            {
                'destination': '172.17.0.2',
                'source': '172.16.6.104',
            },
        ]
        ds.gratuitous_arp(items, self._fetch_distro('ubuntu'))
        self.assertEqual([
            mock.call(
                ['arping', '-c', '2', '-S', '172.16.6.104', '172.17.0.2']),
            mock.call(
                ['arping', '-c', '2', '-S', '172.16.6.104', '172.17.0.2'])
        ], m_subp.call_args_list)
Exemplo n.º 22
0
 def fake_subp(cmd, capture=None):
     fail_cmds = [['ua', 'enable', svc] for svc in ['esm', 'cc']]
     if cmd in fail_cmds and capture:
         svc = cmd[-1]
         raise util.ProcessExecutionError(
             'Invalid {} credentials'.format(svc.upper()))