コード例 #1
0
def test_run_cwd_doesnt_exist_issue_7154():
    """
    cmd.run should fail and raise
    salt.exceptions.CommandExecutionError if the cwd dir does not
    exist
    """
    cmd = "echo OHAI"
    cwd = "/path/to/nowhere"
    with pytest.raises(CommandExecutionError):
        cmdmod.run_all(cmd, cwd=cwd)
コード例 #2
0
ファイル: test_cmdmod.py プロジェクト: aneisch/salt-1
 def test_run_cwd_doesnt_exist_issue_7154(self):
     '''
     cmd.run should fail and raise
     salt.exceptions.CommandExecutionError if the cwd dir does not
     exist
     '''
     cmd = 'echo OHAI'
     cwd = '/path/to/nowhere'
     try:
         cmdmod.run_all(cmd, cwd=cwd)
     except CommandExecutionError:
         pass
     else:
         raise RuntimeError
コード例 #3
0
ファイル: test_cmdmod.py プロジェクト: aneisch/salt-1
    def test_run_all_binary_replace(self):
        '''
        Test for failed decoding of binary data, for instance when doing
        something silly like using dd to read from /dev/urandom and write to
        /dev/stdout.
        '''
        # Since we're using unicode_literals, read the random bytes from a file
        rand_bytes_file = os.path.join(FILES, 'file', 'base', 'random_bytes')
        with salt.utils.files.fopen(rand_bytes_file, 'rb') as fp_:
            stdout_bytes = fp_.read()

        # stdout with the non-decodable bits replaced with the unicode
        # replacement character U+FFFD.
        stdout_unicode = '\ufffd\x1b\ufffd\ufffd\n'
        stderr_bytes = b'1+0 records in\n1+0 records out\n' \
                       b'4 bytes copied, 9.1522e-05 s, 43.7 kB/s\n'
        stderr_unicode = stderr_bytes.decode()

        proc = MagicMock(
            return_value=MockTimedProc(
                stdout=stdout_bytes,
                stderr=stderr_bytes
            )
        )
        with patch('salt.utils.timed_subprocess.TimedProc', proc):
            ret = cmdmod.run_all(
                'dd if=/dev/urandom of=/dev/stdout bs=4 count=1',
                rstrip=False)

        self.assertEqual(ret['stdout'], stdout_unicode)
        self.assertEqual(ret['stderr'], stderr_unicode)
コード例 #4
0
ファイル: zfs.py プロジェクト: herlo/salt
    def _cmd(*args):
        '''
        Generated function. Maybe at some point in the
        future, fill this in dynamically.
        '''
        # Define a return value.
        ret = {}

        # Run the command.
        res = salt_cmd.run_all(
                '%s %s %s'.format(
                    _check_zfs(),
                    cmd_name,
                    ' '.join(args)
                    )
                )

        # Make a note of the error in the return object if retcode
        # not 0.
        if res['retcode'] != 0:
            ret['Error'] = _exit_status(res['retcode'])

        # Set the output to be splitlines for now.
        ret = res['stdout'].splitlines()

        return ret
コード例 #5
0
ファイル: test_cmdmod.py プロジェクト: FerrySchuller/salt
    def test_run_all_binary_replace(self):
        '''
        Test for failed decoding of binary data, for instance when doing
        something silly like using dd to read from /dev/urandom and write to
        /dev/stdout.
        '''
        # Since we're using unicode_literals, read the random bytes from a file
        rand_bytes_file = os.path.join(FILES, 'file', 'base', 'random_bytes')
        with salt.utils.files.fopen(rand_bytes_file, 'rb') as fp_:
            stdout_bytes = fp_.read()

        # kitchen-salt uses unix2dos on all the files before copying them over
        # to the vm that will be running the tests. It skips binary files though
        # The file specified in `rand_bytes_file` is detected as binary so the
        # Unix-style line ending remains. This should account for that.
        stdout_bytes = stdout_bytes.rstrip() + os.linesep.encode()

        # stdout with the non-decodable bits replaced with the unicode
        # replacement character U+FFFD.
        stdout_unicode = '\ufffd\x1b\ufffd\ufffd' + os.linesep
        stderr_bytes = os.linesep.encode().join([
            b'1+0 records in', b'1+0 records out',
            b'4 bytes copied, 9.1522e-05 s, 43.7 kB/s'
        ]) + os.linesep.encode()
        stderr_unicode = stderr_bytes.decode()

        proc = MagicMock(return_value=MockTimedProc(stdout=stdout_bytes,
                                                    stderr=stderr_bytes))
        with patch('salt.utils.timed_subprocess.TimedProc', proc):
            ret = cmdmod.run_all(
                'dd if=/dev/urandom of=/dev/stdout bs=4 count=1', rstrip=False)

        self.assertEqual(ret['stdout'], stdout_unicode)
        self.assertEqual(ret['stderr'], stderr_unicode)
コード例 #6
0
ファイル: cmdmod.py プロジェクト: jslatts/salt
 def test_run_cwd_doesnt_exist_issue_7154(self):
     '''
     cmd.run should fail and raise
     salt.exceptions.CommandExecutionError if the cwd dir does not
     exist
     '''
     from salt.exceptions import CommandExecutionError
     import salt.modules.cmdmod as cmdmod
     cmd = 'echo OHAI'
     cwd = '/path/to/nowhere'
     try:
         cmdmod.run_all(cmd, cwd=cwd)
     except CommandExecutionError:
         pass
     else:
         raise RuntimeError
コード例 #7
0
def test_run_all_binary_replace():
    """
    Test for failed decoding of binary data, for instance when doing
    something silly like using dd to read from /dev/urandom and write to
    /dev/stdout.
    """
    # Since we're using unicode_literals, read the random bytes from a file
    rand_bytes_file = os.path.join(RUNTIME_VARS.BASE_FILES, "random_bytes")
    with salt.utils.files.fopen(rand_bytes_file, "rb") as fp_:
        stdout_bytes = fp_.read()

    # kitchen-salt uses unix2dos on all the files before copying them over
    # to the vm that will be running the tests. It skips binary files though
    # The file specified in `rand_bytes_file` is detected as binary so the
    # Unix-style line ending remains. This should account for that.
    stdout_bytes = stdout_bytes.rstrip() + os.linesep.encode()

    # stdout with the non-decodable bits replaced with the unicode
    # replacement character U+FFFD.
    stdout_unicode = "\ufffd\x1b\ufffd\ufffd" + os.linesep
    stderr_bytes = (os.linesep.encode().join([
        b"1+0 records in",
        b"1+0 records out",
        b"4 bytes copied, 9.1522e-05 s, 43.7 kB/s",
    ]) + os.linesep.encode())
    stderr_unicode = stderr_bytes.decode()

    proc = MagicMock(
        return_value=MockTimedProc(stdout=stdout_bytes, stderr=stderr_bytes))
    with patch("salt.utils.timed_subprocess.TimedProc", proc):
        ret = cmdmod.run_all("dd if=/dev/urandom of=/dev/stdout bs=4 count=1",
                             rstrip=False)

    assert ret["stdout"] == stdout_unicode
    assert ret["stderr"] == stderr_unicode
コード例 #8
0
def test_cmd_run_all_encoded_cmd(shell):
    cmd = "Write-Output 'encoded command'"
    cmd = "$ProgressPreference='SilentlyContinue'; {}".format(cmd)
    cmd_utf16 = cmd.encode("utf-16-le")
    encoded_cmd = base64.standard_b64encode(cmd_utf16)
    encoded_cmd = salt.utils.stringutils.to_str(encoded_cmd)
    ret = cmdmod.run_all(cmd=encoded_cmd, shell=shell, encoded_cmd=True)
    assert ret["stdout"] == "encoded command"
コード例 #9
0
def test_cmd_run_all_powershell_string():
    """
    Ensure that cmd.run_all supports running shell='powershell' with cmd passed
     as a string
    """
    ret = cmdmod.run_all(cmd="Write-Output salt",
                         python_shell=False,
                         shell="powershell")
    assert ret["stdout"] == "salt"
コード例 #10
0
def test_run_all_none():
    """
    Tests cases when proc.stdout or proc.stderr are None. These should be
    caught and replaced with empty strings.
    """
    proc = MagicMock(return_value=MockTimedProc(stdout=None, stderr=None))
    with patch("salt.utils.timed_subprocess.TimedProc", proc):
        ret = cmdmod.run_all("some command", rstrip=False)

    assert ret["stdout"] == ""
    assert ret["stderr"] == ""
コード例 #11
0
ファイル: test_cmdmod.py プロジェクト: aneisch/salt-1
    def test_run_all_none(self):
        '''
        Tests cases when proc.stdout or proc.stderr are None. These should be
        caught and replaced with empty strings.
        '''
        proc = MagicMock(return_value=MockTimedProc(stdout=None, stderr=None))
        with patch('salt.utils.timed_subprocess.TimedProc', proc):
            ret = cmdmod.run_all('some command', rstrip=False)

        self.assertEqual(ret['stdout'], '')
        self.assertEqual(ret['stderr'], '')
コード例 #12
0
ファイル: test_cmdmod.py プロジェクト: aneisch/salt-1
    def test_run_all_output_encoding(self):
        '''
        Test that specifying the output encoding works as expected
        '''
        stdout = 'Æ'
        stdout_latin1_enc = stdout.encode('latin1')

        proc = MagicMock(return_value=MockTimedProc(stdout=stdout_latin1_enc))

        with patch('salt.utils.timed_subprocess.TimedProc', proc), \
                patch.object(builtins, '__salt_system_encoding__', 'utf-8'):
            ret = cmdmod.run_all('some command', output_encoding='latin1')

        self.assertEqual(ret['stdout'], stdout)
コード例 #13
0
ファイル: test_cmdmod.py プロジェクト: zfouts/salt
    def test_run_all_output_loglevel_debug(self):
        """
        Test that specifying debug for loglevel
        does log the command.
        """
        stdout = b"test"
        proc = MagicMock(return_value=MockTimedProc(stdout=stdout))

        msg = "INFO:Executing command 'some command' in directory"
        with patch("salt.utils.timed_subprocess.TimedProc", proc):
            with TstSuiteLoggingHandler() as log_handler:
                ret = cmdmod.run_all("some command", output_loglevel="debug")
                assert [x for x in log_handler.messages if msg in x]

        self.assertEqual(ret["stdout"], salt.utils.stringutils.to_unicode(stdout))
コード例 #14
0
def test_run_all_output_loglevel_debug(caplog):
    """
    Test that specifying debug for loglevel
    does log the command.
    """
    stdout = b"test"
    proc = MagicMock(return_value=MockTimedProc(stdout=stdout))

    msg = "Executing command 'some' in directory"
    with patch("salt.utils.timed_subprocess.TimedProc", proc):
        with caplog.at_level(logging.DEBUG, logger="salt.modules.cmdmod"):
            ret = cmdmod.run_all("some command", output_loglevel="debug")
        assert msg in caplog.text

    assert ret["stdout"] == salt.utils.stringutils.to_unicode(stdout)
コード例 #15
0
def test_run_all_output_encoding():
    """
    Test that specifying the output encoding works as expected
    """
    stdout = "Æ"
    stdout_latin1_enc = stdout.encode("latin1")

    proc = MagicMock(return_value=MockTimedProc(stdout=stdout_latin1_enc))

    with patch("salt.utils.timed_subprocess.TimedProc",
               proc), patch.object(builtins, "__salt_system_encoding__",
                                   "utf-8"):
        ret = cmdmod.run_all("some command", output_encoding="latin1")

    assert ret["stdout"] == stdout
コード例 #16
0
ファイル: test_cmdmod.py プロジェクト: wicked-wei/salt
    def test_run_all_output_loglevel_quiet(self):
        '''
        Test that specifying quiet for loglevel
        does not log the command.
        '''
        stdout = b'test'
        proc = MagicMock(return_value=MockTimedProc(stdout=stdout))

        msg = "INFO:Executing command 'some command' in directory"
        with patch('salt.utils.timed_subprocess.TimedProc', proc):
            with TstSuiteLoggingHandler() as log_handler:
                ret = cmdmod.run_all('some command', output_loglevel='quiet')
                assert not [x for x in log_handler.messages if msg in x]

        self.assertEqual(ret['stdout'],
                         salt.utils.stringutils.to_unicode(stdout))
コード例 #17
0
ファイル: zfs.py プロジェクト: s7726/salt
    def _cmd(*args):
        # Define a return value.
        ret = {}

        # Run the command.
        res = salt_cmd.run_all('{0} {1} {2}'.format(_check_zfs(), cmd_name,
                                                    ' '.join(args)))

        # Make a note of the error in the return object if retcode
        # not 0.
        if res['retcode'] != 0:
            ret['Error'] = _exit_status(res['retcode'])

        # Set the output to be splitlines for now.
        ret = res['stdout'].splitlines()

        return ret
コード例 #18
0
ファイル: test_cmdmod.py プロジェクト: wicked-wei/salt
    def test_run_all_unicode(self):
        '''
        Ensure that unicode stdout and stderr are decoded properly
        '''
        stdout_unicode = 'Here is some unicode: спам'
        stderr_unicode = 'Here is some unicode: яйца'
        stdout_bytes = stdout_unicode.encode('utf-8')
        stderr_bytes = stderr_unicode.encode('utf-8')

        proc = MagicMock(return_value=MockTimedProc(stdout=stdout_bytes,
                                                    stderr=stderr_bytes))

        with patch('salt.utils.timed_subprocess.TimedProc', proc), \
                patch.object(builtins, '__salt_system_encoding__', 'utf-8'):
            ret = cmdmod.run_all('some command', rstrip=False)

        self.assertEqual(ret['stdout'], stdout_unicode)
        self.assertEqual(ret['stderr'], stderr_unicode)
コード例 #19
0
def test_run_all_unicode():
    """
    Ensure that unicode stdout and stderr are decoded properly
    """
    stdout_unicode = "Here is some unicode: спам"
    stderr_unicode = "Here is some unicode: яйца"
    stdout_bytes = stdout_unicode.encode("utf-8")
    stderr_bytes = stderr_unicode.encode("utf-8")

    proc = MagicMock(
        return_value=MockTimedProc(stdout=stdout_bytes, stderr=stderr_bytes))

    with patch("salt.utils.timed_subprocess.TimedProc",
               proc), patch.object(builtins, "__salt_system_encoding__",
                                   "utf-8"):
        ret = cmdmod.run_all("some command", rstrip=False)

    assert ret["stdout"] == stdout_unicode
    assert ret["stderr"] == stderr_unicode
コード例 #20
0
ファイル: zfs.py プロジェクト: herlo/salt
def _available_commands():
    '''
    List available commands based on 'zfs help'. Either
    returns a list, or False.
    '''
    zfs_path = _check_zfs()
    if not zfs_path:
        return False

    _return = []
    # Note that we append '|| :' as a unix hack to force return code to be 0.
    res = salt_cmd.run_all('{0} help || :'.format(zfs_path))

    # This bit is dependant on specific output from `zfs help` - any major changes
    # in how this works upstream will require a change.
    for line in res['stderr'].splitlines():
        if re.match('	[a-zA-Z]', line):
            for cmd in [cmd.strip() for cmd in line.split(' ')[0].split( '|' )]:
                if cmd not in _return:
                    _return.append(cmd)
    return _return
コード例 #21
0
ファイル: zfs.py プロジェクト: 1mentat/salt
    def _cmd(*args):
        # Define a return value.
        ret = {}

        # Run the command.
        res = salt_cmd.run_all(
                '{0} {1} {2}'.format(
                    _check_zfs(),
                    cmd_name,
                    ' '.join(args)
                    )
                )

        # Make a note of the error in the return object if retcode
        # not 0.
        if res['retcode'] != 0:
            ret['Error'] = _exit_status(res['retcode'])

        # Set the output to be splitlines for now.
        ret = res['stdout'].splitlines()

        return ret
コード例 #22
0
def _available_commands():
    '''
    List available commands based on 'zfs help'. Returns a dict.
    '''
    zfs_path = _check_zfs()
    if not zfs_path:
        return False

    _return = {}
    # Note that we append '|| :' as a unix hack to force return code to be 0.
    res = salt_cmd.run_all('{0} help || :'.format(zfs_path))

    # This bit is dependent on specific output from `zfs help` - any major changes
    # in how this works upstream will require a change.
    for line in res['stderr'].splitlines():
        if re.match('	[a-zA-Z]', line):
            cmds = line.split(' ')[0].split('|')
            doc = ' '.join(line.split(' ')[1:])
            for cmd in [cmd.strip() for cmd in cmds]:
                if cmd not in _return:
                    _return[cmd] = doc
    return _return