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

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