Blame SOURCES/0001-tests-run-tests-with-python3.patch

4d12ff
From c257850912897a07e20f205faecf3c1b692fa9e9 Mon Sep 17 00:00:00 2001
4d12ff
From: Sumit Bose <sbose@redhat.com>
4d12ff
Date: Wed, 4 Jul 2018 16:41:16 +0200
4d12ff
Subject: [PATCH] tests: run tests with python3
4d12ff
4d12ff
To allow the test to run with python3 build/tap-driver and
4d12ff
build/tap-gtester are updated to the latest version provided by the
4d12ff
cockpit project https://github.com/cockpit-project/cockpit.
4d12ff
4d12ff
Related to https://bugzilla.redhat.com/show_bug.cgi?id=1595813
4d12ff
---
4d12ff
 build/tap-driver  | 104 +++++++++++++++++++++++++++++++++++++++++++-----------
4d12ff
 build/tap-gtester |  59 ++++++++++++++++++++++---------
4d12ff
 2 files changed, 125 insertions(+), 38 deletions(-)
4d12ff
4d12ff
diff --git a/build/tap-driver b/build/tap-driver
4d12ff
index 42f57c8..241fd50 100755
4d12ff
--- a/build/tap-driver
4d12ff
+++ b/build/tap-driver
4d12ff
@@ -1,4 +1,5 @@
4d12ff
-#!/usr/bin/python
4d12ff
+#!/usr/bin/python3
4d12ff
+# This can also be run with Python 2.
4d12ff
 
4d12ff
 # Copyright (C) 2013 Red Hat, Inc.
4d12ff
 #
4d12ff
@@ -29,20 +30,58 @@
4d12ff
 #
4d12ff
 
4d12ff
 import argparse
4d12ff
+import fcntl
4d12ff
 import os
4d12ff
 import select
4d12ff
+import struct
4d12ff
 import subprocess
4d12ff
 import sys
4d12ff
+import termios
4d12ff
+import errno
4d12ff
+
4d12ff
+_PY3 = sys.version[0] >= '3'
4d12ff
+_str = _PY3 and str or unicode
4d12ff
+
4d12ff
+def out(data, stream=None, flush=False):
4d12ff
+    if not isinstance(data, bytes):
4d12ff
+        data = data.encode("UTF-8")
4d12ff
+    if not stream:
4d12ff
+        stream = _PY3 and sys.stdout.buffer or sys.stdout
4d12ff
+    while True:
4d12ff
+        try:
4d12ff
+            if data:
4d12ff
+                stream.write(data)
4d12ff
+            data = None
4d12ff
+            if flush:
4d12ff
+                stream.flush()
4d12ff
+            flush = False
4d12ff
+            break
4d12ff
+        except IOError as e:
4d12ff
+            if e.errno == errno.EAGAIN:
4d12ff
+                continue
4d12ff
+            raise
4d12ff
+
4d12ff
+def terminal_width():
4d12ff
+    try:
4d12ff
+        h, w, hp, wp = struct.unpack('HHHH',
4d12ff
+            fcntl.ioctl(1, termios.TIOCGWINSZ,
4d12ff
+            struct.pack('HHHH', 0, 0, 0, 0)))
4d12ff
+        return w
4d12ff
+    except IOError as e:
4d12ff
+        if e.errno != errno.ENOTTY:
4d12ff
+            sys.stderr.write("%i %s %s\n" % (e.errno, e.strerror, sys.exc_info()))
4d12ff
+        return sys.maxsize
4d12ff
 
4d12ff
 class Driver:
4d12ff
     def __init__(self, args):
4d12ff
         self.argv = args.command
4d12ff
         self.test_name = args.test_name
4d12ff
-        self.log = open(args.log_file, "w")
4d12ff
-        self.log.write("# %s\n" % " ".join(sys.argv))
4d12ff
+        self.log = open(args.log_file, "wb")
4d12ff
+        self.log.write(("# %s\n" % " ".join(sys.argv)).encode("UTF-8"))
4d12ff
         self.trs = open(args.trs_file, "w")
4d12ff
         self.color_tests = args.color_tests
4d12ff
         self.expect_failure = args.expect_failure
4d12ff
+        self.width = terminal_width() - 9
4d12ff
 
4d12ff
     def report(self, code, *args):
4d12ff
         CODES = {
4d12ff
@@ -57,17 +96,18 @@ class Driver:
4d12ff
         # Print out to console
4d12ff
         if self.color_tests:
4d12ff
             if code in CODES:
4d12ff
-                sys.stdout.write(CODES[code])
4d12ff
-        sys.stdout.write(code)
4d12ff
+                out(CODES[code])
4d12ff
+        out(code)
4d12ff
         if self.color_tests:
4d12ff
-            sys.stdout.write('\x1b[m')
4d12ff
-        sys.stdout.write(": ")
4d12ff
-        sys.stdout.write(self.test_name)
4d12ff
-        sys.stdout.write(" ")
4d12ff
-        for arg in args:
4d12ff
-            sys.stdout.write(str(arg))
4d12ff
-        sys.stdout.write("\n")
4d12ff
-        sys.stdout.flush()
4d12ff
+            out('\x1b[m')
4d12ff
+        out(": ")
4d12ff
+        msg = "".join([ self.test_name + " " ] + list(map(_str, args)))
4d12ff
+        if code == "PASS" and len(msg) > self.width:
4d12ff
+            out(msg[:self.width])
4d12ff
+            out("...")
4d12ff
+        else:
4d12ff
+            out(msg)
4d12ff
+        out("\n", flush=True)
4d12ff
 
4d12ff
         # Book keeping
4d12ff
         if code in CODES:
4d12ff
@@ -100,12 +140,14 @@ class Driver:
4d12ff
     def execute(self):
4d12ff
         try:
4d12ff
             proc = subprocess.Popen(self.argv, close_fds=True,
4d12ff
+                                    stdin=subprocess.PIPE,
4d12ff
                                     stdout=subprocess.PIPE,
4d12ff
                                     stderr=subprocess.PIPE)
4d12ff
-        except OSError, ex:
4d12ff
+        except OSError as ex:
4d12ff
             self.report_error("Couldn't run %s: %s" % (self.argv[0], str(ex)))
4d12ff
             return
4d12ff
 
4d12ff
+        proc.stdin.close()
4d12ff
         outf = proc.stdout.fileno()
4d12ff
         errf = proc.stderr.fileno()
4d12ff
         rset = [outf, errf]
4d12ff
@@ -113,18 +155,25 @@ class Driver:
4d12ff
             ret = select.select(rset, [], [], 10)
4d12ff
             if outf in ret[0]:
4d12ff
                 data = os.read(outf, 1024)
4d12ff
-                if data == "":
4d12ff
+                if data == b"":
4d12ff
                     rset.remove(outf)
4d12ff
                 self.log.write(data)
4d12ff
                 self.process(data)
4d12ff
             if errf in ret[0]:
4d12ff
                 data = os.read(errf, 1024)
4d12ff
-                if data == "":
4d12ff
+                if data == b"":
4d12ff
                     rset.remove(errf)
4d12ff
                 self.log.write(data)
4d12ff
-                sys.stderr.write(data)
4d12ff
+                stream = _PY3 and sys.stderr.buffer or sys.stderr
4d12ff
+                out(data, stream=stream, flush=True)
4d12ff
 
4d12ff
         proc.wait()
4d12ff
+
4d12ff
+        # Make sure the test didn't change blocking output
4d12ff
+        assert fcntl.fcntl(0, fcntl.F_GETFL) & os.O_NONBLOCK == 0
4d12ff
+        assert fcntl.fcntl(1, fcntl.F_GETFL) & os.O_NONBLOCK == 0
4d12ff
+        assert fcntl.fcntl(2, fcntl.F_GETFL) & os.O_NONBLOCK == 0
4d12ff
+
4d12ff
         return proc.returncode
4d12ff
 
4d12ff
 
4d12ff
@@ -137,6 +186,7 @@ class TapDriver(Driver):
4d12ff
         self.late_plan = False
4d12ff
         self.errored = False
4d12ff
         self.bail_out = False
4d12ff
+        self.skip_all_reason = None
4d12ff
 
4d12ff
     def report(self, code, num, *args):
4d12ff
         if num:
4d12ff
@@ -170,13 +220,19 @@ class TapDriver(Driver):
4d12ff
         else:
4d12ff
             self.result_fail(num, description)
4d12ff
 
4d12ff
-    def consume_test_plan(self, first, last):
4d12ff
+    def consume_test_plan(self, line):
4d12ff
         # Only one test plan is supported
4d12ff
         if self.test_plan:
4d12ff
             self.report_error("Get a second TAP test plan")
4d12ff
             return
4d12ff
 
4d12ff
+        if line.lower().startswith('1..0 # skip'):
4d12ff
+            self.skip_all_reason = line[5:].strip()
4d12ff
+            self.bail_out = True
4d12ff
+            return
4d12ff
+
4d12ff
         try:
4d12ff
+            (first, unused, last) = line.partition("..")
4d12ff
             first = int(first)
4d12ff
             last = int(last)
4d12ff
         except ValueError:
4d12ff
@@ -192,7 +248,7 @@ class TapDriver(Driver):
4d12ff
 
4d12ff
     def process(self, output):
4d12ff
         if output:
4d12ff
-            self.output += output
4d12ff
+            self.output += output.decode("UTF-8")
4d12ff
         elif self.output:
4d12ff
             self.output += "\n"
4d12ff
         (ready, unused, self.output) = self.output.rpartition("\n")
4d12ff
@@ -202,8 +258,7 @@ class TapDriver(Driver):
4d12ff
             elif line.startswith("not ok "):
4d12ff
                 self.consume_test_line(False, line[7:])
4d12ff
             elif line and line[0].isdigit() and ".." in line:
4d12ff
-                (first, unused, last) = line.partition("..")
4d12ff
-                self.consume_test_plan(first, last)
4d12ff
+                self.consume_test_plan(line)
4d12ff
             elif line.lower().startswith("bail out!"):
4d12ff
                 self.consume_bail_out(line)
4d12ff
 
4d12ff
@@ -213,6 +268,13 @@ class TapDriver(Driver):
4d12ff
         failed = False
4d12ff
         skipped = True
4d12ff
 
4d12ff
+        if self.skip_all_reason is not None:
4d12ff
+            self.result_skip("skipping:", self.skip_all_reason)
4d12ff
+            self.trs.write(":global-test-result: SKIP\n")
4d12ff
+            self.trs.write(":test-global-result: SKIP\n")
4d12ff
+            self.trs.write(":recheck: no\n")
4d12ff
+            return 0
4d12ff
+
4d12ff
         # Basic collation of results
4d12ff
         for (num, code) in self.reported.items():
4d12ff
             if code == "ERROR":
4d12ff
diff --git a/build/tap-gtester b/build/tap-gtester
4d12ff
index 7e667d4..bbda266 100755
4d12ff
--- a/build/tap-gtester
4d12ff
+++ b/build/tap-gtester
4d12ff
@@ -1,4 +1,5 @@
4d12ff
-#!/usr/bin/python
4d12ff
+#!/usr/bin/python3
4d12ff
+# This can also be run with Python 2.
4d12ff
 
4d12ff
 # Copyright (C) 2014 Red Hat, Inc.
4d12ff
 #
4d12ff
@@ -30,9 +31,19 @@
4d12ff
 import argparse
4d12ff
 import os
4d12ff
 import select
4d12ff
+import signal
4d12ff
 import subprocess
4d12ff
 import sys
4d12ff
 
4d12ff
+# Yes, it's dumb, but strsignal is not exposed in python
4d12ff
+# In addition signal numbers varify heavily from arch to arch
4d12ff
+def strsignal(sig):
4d12ff
+    for name in dir(signal):
4d12ff
+        if name.startswith("SIG") and sig == getattr(signal, name):
4d12ff
+            return name
4d12ff
+    return str(sig)
4d12ff
+
4d12ff
+
4d12ff
 class NullCompiler:
4d12ff
     def __init__(self, command):
4d12ff
         self.command = command
4d12ff
@@ -76,22 +87,22 @@ class GTestCompiler(NullCompiler):
4d12ff
            elif cmd == "result":
4d12ff
                if self.test_name:
4d12ff
                    if data == "OK":
4d12ff
-                       print "ok %d %s" % (self.test_num, self.test_name)
4d12ff
+                       print("ok %d %s" % (self.test_num, self.test_name))
4d12ff
                    if data == "FAIL":
4d12ff
-                       print "not ok %d %s", (self.test_num, self.test_name)
4d12ff
+                       print("not ok %d %s" % (self.test_num, self.test_name))
4d12ff
                self.test_name = None
4d12ff
            elif cmd == "skipping":
4d12ff
                if "/subprocess" not in data:
4d12ff
-                   print "ok %d # skip -- %s" % (self.test_num, data)
4d12ff
+                   print("ok %d # skip -- %s" % (self.test_num, data))
4d12ff
                self.test_name = None
4d12ff
            elif data:
4d12ff
-               print "# %s: %s" % (cmd, data)
4d12ff
+               print("# %s: %s" % (cmd, data))
4d12ff
            else:
4d12ff
-               print "# %s" % cmd
4d12ff
+               print("# %s" % cmd)
4d12ff
         elif line.startswith("(MSG: "):
4d12ff
-            print "# %s" % line[6:-1]
4d12ff
+            print("# %s" % line[6:-1])
4d12ff
         elif line:
4d12ff
-            print "# %s" % line
4d12ff
+            print("# %s" % line)
4d12ff
         sys.stdout.flush()
4d12ff
 
4d12ff
     def run(self, proc, output=""):
4d12ff
@@ -106,22 +117,26 @@ class GTestCompiler(NullCompiler):
4d12ff
             if line.startswith("/"):
4d12ff
                 self.test_remaining.append(line.strip())
4d12ff
         if not self.test_remaining:
4d12ff
-            print "Bail out! No tests found in GTest: %s" % self.command[0]
4d12ff
+            print("Bail out! No tests found in GTest: %s" % self.command[0])
4d12ff
             return 0
4d12ff
 
4d12ff
-        print "1..%d" % len(self.test_remaining)
4d12ff
+        print("1..%d" % len(self.test_remaining))
4d12ff
 
4d12ff
         # First try to run all the tests in a batch
4d12ff
-        proc = subprocess.Popen(self.command + ["--verbose" ], close_fds=True, stdout=subprocess.PIPE)
4d12ff
+        proc = subprocess.Popen(self.command + ["--verbose" ], close_fds=True,
4d12ff
+                                stdout=subprocess.PIPE, universal_newlines=True)
4d12ff
         result = self.process(proc)
4d12ff
         if result == 0:
4d12ff
             return 0
4d12ff
 
4d12ff
+        if result < 0:
4d12ff
+            sys.stderr.write("%s terminated with %s\n" % (self.command[0], strsignal(-result)))
4d12ff
+
4d12ff
         # Now pick up any stragglers due to failures
4d12ff
         while True:
4d12ff
             # Assume that the last test failed
4d12ff
             if self.test_name:
4d12ff
-                print "not ok %d %s" % (self.test_num, self.test_name)
4d12ff
+                print("not ok %d %s" % (self.test_num, self.test_name))
4d12ff
                 self.test_name = None
4d12ff
 
4d12ff
             # Run any tests which didn't get run
4d12ff
@@ -129,7 +144,8 @@ class GTestCompiler(NullCompiler):
4d12ff
                 break
4d12ff
 
4d12ff
             proc = subprocess.Popen(self.command + ["--verbose", "-p", self.test_remaining[0]],
4d12ff
-                                    close_fds=True, stdout=subprocess.PIPE)
4d12ff
+                                    close_fds=True, stdout=subprocess.PIPE,
4d12ff
+                                    universal_newlines=True)
4d12ff
             result = self.process(proc)
4d12ff
 
4d12ff
             # The various exit codes and signals we continue for
4d12ff
@@ -139,24 +155,32 @@ class GTestCompiler(NullCompiler):
4d12ff
         return result
4d12ff
 
4d12ff
 def main(argv):
4d12ff
-    parser = argparse.ArgumentParser(description='Automake TAP compiler')
4d12ff
+    parser = argparse.ArgumentParser(description='Automake TAP compiler',
4d12ff
+                                     usage="tap-gtester [--format FORMAT] command ...")
4d12ff
     parser.add_argument('--format', metavar='FORMAT', choices=[ "auto", "gtest", "tap" ],
4d12ff
                         default="auto", help='The input format to compile')
4d12ff
     parser.add_argument('--verbose', action='store_true',
4d12ff
                         default=True, help='Verbose mode (ignored)')
4d12ff
-    parser.add_argument('command', nargs='+', help="A test command to run")
4d12ff
+    parser.add_argument('command', nargs=argparse.REMAINDER, help="A test command to run")
4d12ff
     args = parser.parse_args(argv[1:])
4d12ff
 
4d12ff
     output = None
4d12ff
     format = args.format
4d12ff
     cmd = args.command
4d12ff
+    if not cmd:
4d12ff
+        sys.stderr.write("tap-gtester: specify a command to run\n")
4d12ff
+        return 2
4d12ff
+    if cmd[0] == '--':
4d12ff
+        cmd.pop(0)
4d12ff
+
4d12ff
     proc = None
4d12ff
 
4d12ff
     os.environ['HARNESS_ACTIVE'] = '1'
4d12ff
 
4d12ff
     if format in ["auto", "gtest"]:
4d12ff
         list_cmd = cmd + ["-l", "--verbose"]
4d12ff
-        proc = subprocess.Popen(list_cmd, close_fds=True, stdout=subprocess.PIPE)
4d12ff
+        proc = subprocess.Popen(list_cmd, close_fds=True, stdout=subprocess.PIPE,
4d12ff
+                                universal_newlines=True)
4d12ff
         output = proc.stdout.readline()
4d12ff
         # Smell whether we're dealing with GTest list output from first line
4d12ff
         if "random seed" in output or "GTest" in output or output.startswith("/"):
4d12ff
@@ -164,7 +188,8 @@ def main(argv):
4d12ff
         else:
4d12ff
             format = "tap"
4d12ff
     else:
4d12ff
-        proc = subprocess.Popen(cmd, close_fds=True, stdout=subprocess.PIPE)
4d12ff
+        proc = subprocess.Popen(cmd, close_fds=True, stdout=subprocess.PIPE,
4d12ff
+                                universal_newlines=True)
4d12ff
 
4d12ff
     if format == "gtest":
4d12ff
         compiler = GTestCompiler(cmd)
4d12ff
-- 
4d12ff
2.14.4
4d12ff