提交 b9a719cb 编写于 作者: C Cleber Rosa

avocado/utils/process.py: add cmd_split() function

Signed-off-by: NCleber Rosa <crosa@redhat.com>
上级 df98b07d
......@@ -34,6 +34,7 @@ import time
from io import BytesIO, UnsupportedOperation
from six import PY2, string_types
from . import astring
from . import gdb
from . import runtime
from . import path
......@@ -281,6 +282,26 @@ def binary_from_shell_cmd(cmd, encoding=None):
raise ValueError("Unable to parse first binary from '%s'" % cmd)
def cmd_split(cmd):
"""
Splits a command line into individual components
This is a simple wrapper around :func:`shlex.split`, which has the
requirement of having text (not bytes) as its argument on Python 3,
but bytes on Python 2.
:param cmd: text (a multi byte string) encoded as 'utf-8'
"""
if sys.version_info[0] < 3:
data = cmd.encode('utf-8')
result = shlex.split(data)
result = [i.decode('utf-8') for i in result]
else:
data = astring.to_text(cmd, 'utf-8')
result = shlex.split(data)
return result
class CmdResult(object):
"""
......
import io
import logging
import os
import shlex
import unittest
try:
......@@ -9,6 +10,7 @@ except ImportError:
import mock
from avocado.utils import astring
from avocado.utils import gdb
from avocado.utils import process
from avocado.utils import path
......@@ -285,6 +287,32 @@ class MiscProcessTests(unittest.TestCase):
res = process.binary_from_shell_cmd("FOO=bar ./bin var=value")
self.assertEqual("./bin", res)
def test_cmd_split(self):
plain_str = ''
unicode_str = u''
empty_bytes = b''
# shlex.split() can work with "plain_str" and "unicode_str" on both
# Python 2 and Python 3. While we're not testing Python itself,
# this will help us catch possible differences in the Python
# standard library should they arise.
self.assertEqual(shlex.split(plain_str), [])
self.assertEqual(shlex.split(astring.to_text(plain_str)), [])
self.assertEqual(shlex.split(unicode_str), [])
self.assertEqual(shlex.split(astring.to_text(unicode_str)), [])
# on Python 3, shlex.split() won't work with bytes, raising:
# AttributeError: 'bytes' object has no attribute 'read'.
# To turn bytes into text (when necessary), that is, on
# Python 3 only, use astring.to_text()
self.assertEqual(shlex.split(astring.to_text(empty_bytes)), [])
# Now let's test our specific implementation to split commands
self.assertEqual(process.cmd_split(plain_str), [])
self.assertEqual(process.cmd_split(unicode_str), [])
self.assertEqual(process.cmd_split(empty_bytes), [])
unicode_command = u"avok\xe1do_test_runner arguments"
self.assertEqual(process.cmd_split(unicode_command),
[u"avok\xe1do_test_runner",
u"arguments"])
class CmdResultTests(unittest.TestCase):
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册