utils: fix UTF-8 handling with stdin
Make sure we convert input strings to bytes before passing down.
Bug: 140809632
Test: unittests pass for py2 & py3
Change-Id: I3e49eb319c3f0c063f2a1cb2b2800709172907bd
diff --git a/rh/utils.py b/rh/utils.py
index 30babd7..af63286 100644
--- a/rh/utils.py
+++ b/rh/utils.py
@@ -251,7 +251,8 @@
raise
-# pylint: disable=redefined-builtin
+# We use the keyword arg |input| which trips up pylint checks.
+# pylint: disable=redefined-builtin,input-builtin
def run_command(cmd, error_message=None, redirect_stdout=False,
redirect_stderr=False, cwd=None, input=None,
shell=False, env=None, extra_env=None, ignore_sigint=False,
@@ -365,6 +366,7 @@
# Otherwise we assume it's a file object that can be read from directly.
if isinstance(input, string_types):
stdin = subprocess.PIPE
+ input = input.encode('utf-8')
elif input is not None:
stdin = input
input = None
@@ -460,4 +462,4 @@
cmd_result.error = cmd_result.error.decode('utf-8', 'replace')
return cmd_result
-# pylint: enable=redefined-builtin
+# pylint: enable=redefined-builtin,input-builtin
diff --git a/rh/utils_unittest.py b/rh/utils_unittest.py
index 5497c28..3cb7259 100755
--- a/rh/utils_unittest.py
+++ b/rh/utils_unittest.py
@@ -183,6 +183,26 @@
self.assertEqual('hi\n', ret.output)
self.assertIsNone(ret.error)
+ def test_stderr_capture(self):
+ """Verify stderr capturing works."""
+ ret = rh.utils.run_command(['sh', '-c', 'echo hi >&2'],
+ redirect_stderr=True)
+ self.assertIsNone(ret.output)
+ self.assertEqual('hi\n', ret.error)
+
+ def test_stdout_utf8(self):
+ """Verify reading UTF-8 data works."""
+ ret = rh.utils.run_command(['printf', r'\xc3\x9f'],
+ redirect_stdout=True)
+ self.assertEqual(u'ß', ret.output)
+ self.assertIsNone(ret.error)
+
+ def test_stdin_utf8(self):
+ """Verify writing UTF-8 data works."""
+ ret = rh.utils.run_command(['cat'], redirect_stdout=True, input=u'ß')
+ self.assertEqual(u'ß', ret.output)
+ self.assertIsNone(ret.error)
+
if __name__ == '__main__':
unittest.main()