[Piglit] [PATCH 05/20] framework: Update unicode handling of subprocess output to support Python 3.x as well as 2.x.

Jon Severinsson jon at severinsson.net
Fri Apr 12 16:39:47 PDT 2013


---
 framework/exectest.py |   38 ++++++++++++++++++++------------------
 1 fil ändrad, 20 tillägg(+), 18 borttagningar(-)

diff --git a/framework/exectest.py b/framework/exectest.py
index 1f97f12..531863b 100644
--- a/framework/exectest.py
+++ b/framework/exectest.py
@@ -20,6 +20,8 @@
 # OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 # DEALINGS IN THE SOFTWARE.
 
+from __future__ import unicode_literals
+
 import os
 import subprocess
 import shlex
@@ -97,23 +99,6 @@ class ExecTest(Test):
 				else:
 					break
 
-			# proc.communicate() returns 8-bit strings, but we need
-			# unicode strings.  In Python 2.x, this is because we
-			# will eventually be serializing the strings as JSON,
-			# and the JSON library expects unicode.  In Python 3.x,
-			# this is because all string operations require
-			# unicode.  So translate the strings into unicode,
-			# assuming they are using UTF-8 encoding.
-			#
-			# If the subprocess output wasn't properly UTF-8
-			# encoded, we don't want to raise an exception, so
-			# translate the strings using 'replace' mode, which
-			# replaces erroneous charcters with the Unicode
-			# "replacement character" (a white question mark inside
-			# a black diamond).
-			out = out.decode('utf-8', 'replace')
-			err = err.decode('utf-8', 'replace')
-
 			results = TestResult()
 
 			if self.skip_test:
@@ -159,7 +144,7 @@ class ExecTest(Test):
 			if env:
 				results['environment'] = env
 
-			results['info'] = unicode("Returncode: {0}\n\nErrors:\n{1}\n\nOutput:\n{2}").format(returncode, err, out)
+			results['info'] = "Returncode: {0}\n\nErrors:\n{1}\n\nOutput:\n{2}".format(returncode, err, out)
 			results['returncode'] = returncode
 			results['command'] = ' '.join(self.command)
 
@@ -192,6 +177,23 @@ class ExecTest(Test):
 				)
 			out, err = proc.communicate()
 			returncode = proc.returncode
+
+			# In Python 2.x proc.communicate() returns 8-bit strings,
+			# but we need unicode strings.  This is because we will
+			# eventually be serializing the strings as JSON, and the
+			# JSON library expects unicode.  So translate the strings
+			# into unicode, assuming they are using UTF-8 encoding.
+			#
+			# If the subprocess output wasn't properly UTF-8
+			# encoded, we don't want to raise an exception, so
+			# translate the strings using 'replace' mode, which
+			# replaces erroneous charcters with the Unicode
+			# "replacement character" (a white question mark inside
+			# a black diamond).
+			if sys.hexversion < 0x030000A0:
+				out = out.decode('utf-8', 'replace')
+				err = err.decode('utf-8', 'replace')
+
 		except OSError as e:
 			# Different sets of tests get built under
 			# different build configurations.  If
-- 
1.7.10.4



More information about the Piglit mailing list