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

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