python/samba/netcmd/schema.py: add schema show_oc for attribute
[kai/samba-autobuild/.git] / selftest / subunithelper.py
index c29bdbabf0e389746bcd56b2650fcf90452e71cd..f20f3fe8ba735216171190444527223feea8a359 100644 (file)
 # You should have received a copy of the GNU General Public License
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
+from __future__ import print_function
 __all__ = ['parse_results']
 
+import datetime
 import re
 import sys
-import subunit
-import subunit.iso8601
-import testtools
+import os
+from samba import subunit
+from samba.subunit.run import TestProtocolClient
+from samba.subunit import iso8601
+import unittest
 
-VALID_RESULTS = ['success', 'successful', 'failure', 'fail', 'skip', 'knownfail', 'error', 'xfail', 'skip-testsuite', 'testsuite-failure', 'testsuite-xfail', 'testsuite-success', 'testsuite-error']
+VALID_RESULTS = set(['success', 'successful', 'failure', 'fail', 'skip',
+                     'knownfail', 'error', 'xfail', 'skip-testsuite',
+                     'testsuite-failure', 'testsuite-xfail',
+                     'testsuite-success', 'testsuite-error',
+                     'uxsuccess', 'testsuite-uxsuccess'])
 
-class TestsuiteEnabledTestResult(testtools.testresult.TestResult):
+class TestsuiteEnabledTestResult(unittest.TestResult):
 
     def start_testsuite(self, name):
         raise NotImplementedError(self.start_testsuite)
@@ -33,7 +41,6 @@ class TestsuiteEnabledTestResult(testtools.testresult.TestResult):
 
 def parse_results(msg_ops, statistics, fh):
     exitcode = 0
-    expected_fail = 0
     open_tests = {}
 
     while fh:
@@ -57,9 +64,9 @@ def parse_results(msg_ops, statistics, fh):
         elif command == "time":
             msg_ops.control_msg(l)
             try:
-                dt = subunit.iso8601.parse_date(arg.rstrip("\n"))
-            except TypeError, e:
-                print "Unable to parse time line: %s" % arg.rstrip("\n")
+                dt = iso8601.parse_date(arg.rstrip("\n"))
+            except TypeError as e:
+                print("Unable to parse time line: %s" % arg.rstrip("\n"))
             else:
                 msg_ops.time(dt)
         elif command in VALID_RESULTS:
@@ -76,7 +83,8 @@ def parse_results(msg_ops, statistics, fh):
                     if l == "":
                         break
                     msg_ops.control_msg(l)
-                    if l == "]\n":
+                    if l[-2:] == "]\n":
+                        reason += l[:-2]
                         terminated = True
                         break
                     else:
@@ -111,7 +119,17 @@ def parse_results(msg_ops, statistics, fh):
                 else:
                     statistics['TESTS_EXPECTED_FAIL']+=1
                     msg_ops.addExpectedFailure(test, remote_error)
-                    expected_fail+=1
+            elif result in ("uxsuccess", ):
+                try:
+                    test = open_tests.pop(testname)
+                except KeyError:
+                    statistics['TESTS_ERROR']+=1
+                    exitcode = 1
+                    msg_ops.addError(subunit.RemotedTestCase(testname), subunit.RemoteError(u"Test was never started"))
+                else:
+                    statistics['TESTS_UNEXPECTED_OK']+=1
+                    msg_ops.addUnexpectedSuccess(test)
+                    exitcode = 1
             elif result in ("failure", "fail"):
                 try:
                     test = open_tests.pop(testname)
@@ -148,6 +166,9 @@ def parse_results(msg_ops, statistics, fh):
                 exitcode = 1
             elif result == "testsuite-xfail":
                 msg_ops.end_testsuite(testname, "xfail", reason)
+            elif result == "testsuite-uxsuccess":
+                msg_ops.end_testsuite(testname, "uxsuccess", reason)
+                exitcode = 1
             elif result == "testsuite-error":
                 msg_ops.end_testsuite(testname, "error", reason)
                 exitcode = 1
@@ -178,7 +199,17 @@ def parse_results(msg_ops, statistics, fh):
     return exitcode
 
 
-class SubunitOps(subunit.TestProtocolClient,TestsuiteEnabledTestResult):
+class SubunitOps(TestProtocolClient,TestsuiteEnabledTestResult):
+
+    def progress(self, count, whence):
+        if whence == subunit.PROGRESS_POP:
+            self._stream.write("progress: pop\n")
+        elif whence == subunit.PROGRESS_PUSH:
+            self._stream.write("progress: push\n")
+        elif whence == subunit.PROGRESS_SET:
+            self._stream.write("progress: %d\n" % count)
+        elif whence == subunit.PROGRESS_CUR:
+            raise NotImplementedError
 
     # The following are Samba extensions:
     def start_testsuite(self, name):
@@ -200,26 +231,38 @@ class SubunitOps(subunit.TestProtocolClient,TestsuiteEnabledTestResult):
         self._stream.write(msg)
 
 
-def read_test_regexes(name):
+def read_test_regexes(*names):
     ret = {}
-    f = open(name, 'r')
-    try:
-        for l in f:
-            l = l.strip()
-            if l == "" or l[0] == "#":
-                continue
-            if "#" in l:
-                (regex, reason) = l.split("#", 1)
-                ret[regex.strip()] = reason.strip()
-            else:
-                ret[l] = None
-    finally:
-        f.close()
+    files = []
+    for name in names:
+        # if we are given a directory, we read all the files it contains
+        # (except the ones that end with "~").
+        if os.path.isdir(name):
+            files.extend([os.path.join(name, x)
+                          for x in os.listdir(name)
+                          if x[-1] != '~'])
+        else:
+            files.append(name)
+
+    for filename in files:
+        f = open(filename, 'r')
+        try:
+            for l in f:
+                l = l.strip()
+                if l == "" or l[0] == "#":
+                    continue
+                if "#" in l:
+                    (regex, reason) = l.split("#", 1)
+                    ret[regex.strip()] = reason.strip()
+                else:
+                    ret[l] = None
+        finally:
+            f.close()
     return ret
 
 
 def find_in_list(regexes, fullname):
-    for regex, reason in regexes.iteritems():
+    for regex, reason in regexes.items():
         if re.match(regex, fullname):
             if reason is None:
                 return ""
@@ -234,7 +277,7 @@ class ImmediateFail(Exception):
         super(ImmediateFail, self).__init__("test failed and fail_immediately set")
 
 
-class FilterOps(testtools.testresult.TestResult):
+class FilterOps(unittest.TestResult):
 
     def control_msg(self, msg):
         pass # We regenerate control messages, so ignore this
@@ -260,32 +303,40 @@ class FilterOps(testtools.testresult.TestResult):
         self._ops.startTest(test)
 
     def _add_prefix(self, test):
-        if self.prefix is not None:
-            return subunit.RemotedTestCase(self.prefix + test.id())
-        else:
-            return test
+        return subunit.RemotedTestCase(self.prefix + test.id() + self.suffix)
 
-    def addError(self, test, details=None):
+    def addError(self, test, err=None):
         test = self._add_prefix(test)
         self.error_added+=1
         self.total_error+=1
-        self._ops.addError(test, details)
+        self._ops.addError(test, err)
         self.output = None
         if self.fail_immediately:
             raise ImmediateFail()
 
-    def addSkip(self, test, details=None):
+    def addSkip(self, test, reason=None):
         self.seen_output = True
         test = self._add_prefix(test)
-        self._ops.addSkip(test, details)
+        self._ops.addSkip(test, reason)
         self.output = None
 
-    def addExpectedFailure(self, test, details=None):
+    def addExpectedFailure(self, test, err=None):
         test = self._add_prefix(test)
-        self._ops.addExpectedFailure(test, details)
+        self._ops.addExpectedFailure(test, err)
         self.output = None
 
-    def addFailure(self, test, details=None):
+    def addUnexpectedSuccess(self, test):
+        test = self._add_prefix(test)
+        self.uxsuccess_added+=1
+        self.total_uxsuccess+=1
+        self._ops.addUnexpectedSuccess(test)
+        if self.output:
+            self._ops.output_msg(self.output)
+        self.output = None
+        if self.fail_immediately:
+            raise ImmediateFail()
+
+    def addFailure(self, test, err=None):
         test = self._add_prefix(test)
         xfail_reason = find_in_list(self.expected_failures, test.id())
         if xfail_reason is None:
@@ -293,38 +344,30 @@ class FilterOps(testtools.testresult.TestResult):
         if xfail_reason is not None:
             self.xfail_added+=1
             self.total_xfail+=1
-            if details is not None:
-                details = subunit.RemoteError(unicode(details[1]) + xfail_reason.decode("utf-8"))
-            else:
-                details = subunit.RemoteError(xfail_reason.decode("utf-8"))
-            self._ops.addExpectedFailure(test, details)
+            self._ops.addExpectedFailure(test, err)
         else:
             self.fail_added+=1
             self.total_fail+=1
-            self._ops.addFailure(test, details)
+            self._ops.addFailure(test, err)
             if self.output:
                 self._ops.output_msg(self.output)
             if self.fail_immediately:
                 raise ImmediateFail()
         self.output = None
 
-    def addSuccess(self, test, details=None):
+    def addSuccess(self, test):
         test = self._add_prefix(test)
         xfail_reason = find_in_list(self.expected_failures, test.id())
         if xfail_reason is not None:
             self.uxsuccess_added += 1
             self.total_uxsuccess += 1
-            if details is not None:
-                details = subunit.RemoteError(unicode(details[1]) + xfail_reason.decode("utf-8"))
-            else:
-                details = subunit.RemoteError(xfail_reason.decode("utf-8"))
-            self._ops.addUnexpectedSuccess(test, details)
+            self._ops.addUnexpectedSuccess(test)
             if self.output:
                 self._ops.output_msg(self.output)
             if self.fail_immediately:
                 raise ImmediateFail()
         else:
-            self._ops.addSuccess(test, details)
+            self._ops.addSuccess(test)
         self.output = None
 
     def skip_testsuite(self, name, reason=None):
@@ -342,12 +385,18 @@ class FilterOps(testtools.testresult.TestResult):
 
         if self.xfail_added > 0:
             xfail = True
-        if self.fail_added > 0 or self.error_added > 0:
+        if self.fail_added > 0 or self.error_added > 0 or self.uxsuccess_added > 0:
             xfail = False
 
         if xfail and result in ("fail", "failure"):
             result = "xfail"
 
+        if self.uxsuccess_added > 0 and result != "uxsuccess":
+            result = "uxsuccess"
+            if reason is None:
+                reason = "Subunit/Filter Reason"
+            reason += "\n uxsuccess[%d]" % self.uxsuccess_added
+
         if self.fail_added > 0 and result != "failure":
             result = "failure"
             if reason is None:
@@ -361,14 +410,21 @@ class FilterOps(testtools.testresult.TestResult):
             reason += "\n errors[%d]" % self.error_added
 
         self._ops.end_testsuite(name, result, reason)
+        if result not in ("success", "xfail"):
+            if self.output:
+                self._ops.output_msg(self.output)
+            if self.fail_immediately:
+                raise ImmediateFail()
+        self.output = None
 
-    def __init__(self, out, prefix=None, expected_failures=None,
+    def __init__(self, out, prefix=None, suffix=None, expected_failures=None,
                  strip_ok_output=False, fail_immediately=False,
                  flapping=None):
         self._ops = out
         self.seen_output = False
         self.output = None
         self.prefix = prefix
+        self.suffix = suffix
         if expected_failures is not None:
             self.expected_failures = expected_failures
         else:
@@ -389,6 +445,73 @@ class FilterOps(testtools.testresult.TestResult):
         self.fail_immediately = fail_immediately
 
 
+class PerfFilterOps(unittest.TestResult):
+
+    def progress(self, delta, whence):
+        pass
+
+    def output_msg(self, msg):
+        pass
+
+    def control_msg(self, msg):
+        pass
+
+    def skip_testsuite(self, name, reason=None):
+        self._ops.skip_testsuite(name, reason)
+
+    def start_testsuite(self, name):
+        self.suite_has_time = False
+
+    def end_testsuite(self, name, result, reason=None):
+        pass
+
+    def _add_prefix(self, test):
+        return subunit.RemotedTestCase(self.prefix + test.id() + self.suffix)
+
+    def time(self, time):
+        self.latest_time = time
+        #self._ops.output_msg("found time %s\n" % time)
+        self.suite_has_time = True
+
+    def get_time(self):
+        if self.suite_has_time:
+            return self.latest_time
+        return datetime.datetime.utcnow()
+
+    def startTest(self, test):
+        self.seen_output = True
+        test = self._add_prefix(test)
+        self.starts[test.id()] = self.get_time()
+
+    def addSuccess(self, test):
+        test = self._add_prefix(test)
+        tid = test.id()
+        if tid not in self.starts:
+            self._ops.addError(test, "%s succeeded without ever starting!" % tid)
+        delta = self.get_time() - self.starts[tid]
+        self._ops.output_msg("elapsed-time: %s: %f\n" % (tid, delta.total_seconds()))
+
+    def addFailure(self, test, err=''):
+        tid = test.id()
+        delta = self.get_time() - self.starts[tid]
+        self._ops.output_msg("failure: %s failed after %f seconds (%s)\n" %
+                             (tid, delta.total_seconds(), err))
+
+    def addError(self, test, err=''):
+        tid = test.id()
+        delta = self.get_time() - self.starts[tid]
+        self._ops.output_msg("error: %s failed after %f seconds (%s)\n" %
+                             (tid, delta.total_seconds(), err))
+
+    def __init__(self, out, prefix='', suffix=''):
+        self._ops = out
+        self.prefix = prefix or ''
+        self.suffix = suffix or ''
+        self.starts = {}
+        self.seen_output = False
+        self.suite_has_time = False
+
+
 class PlainFormatter(TestsuiteEnabledTestResult):
 
     def __init__(self, verbose, immediate, statistics,
@@ -443,11 +566,17 @@ class PlainFormatter(TestsuiteEnabledTestResult):
         if not self.verbose:
             self.test_output[name] = ""
 
-        out = "[%d" % self.index
+        total_tests = (self.statistics['TESTS_EXPECTED_OK'] +
+                       self.statistics['TESTS_EXPECTED_FAIL'] +
+                       self.statistics['TESTS_ERROR'] +
+                       self.statistics['TESTS_UNEXPECTED_FAIL'] +
+                       self.statistics['TESTS_UNEXPECTED_OK'])
+
+        out = "[%d(%d)" % (self.index, total_tests)
         if self.totalsuites is not None:
             out += "/%d" % self.totalsuites
         if self.start_time is not None:
-            out += " in " + self._format_time(self.last_time - self.start_time)
+            out += " at " + self._format_time(self.last_time - self.start_time)
         if self.suitesfailed:
             out += ", %d errors" % (len(self.suitesfailed),)
         out += "] %s" % name
@@ -472,7 +601,7 @@ class PlainFormatter(TestsuiteEnabledTestResult):
         unexpected = False
 
         if not name in self.test_output:
-            print "no output for name[%s]" % name
+            print("no output for name[%s]" % name)
 
         if result in ("success", "xfail"):
             self.suites_ok+=1
@@ -499,19 +628,22 @@ class PlainFormatter(TestsuiteEnabledTestResult):
     def addSuccess(self, test):
         self.end_test(test.id(), "success", False)
 
-    def addError(self, test, details=None):
-        self.end_test(test.id(), "error", True, details)
+    def addError(self, test, err=None):
+        self.end_test(test.id(), "error", True, err)
+
+    def addFailure(self, test, err=None):
+        self.end_test(test.id(), "failure", True, err)
 
-    def addFailure(self, test, details=None):
-        self.end_test(test.id(), "failure", True, details)
+    def addSkip(self, test, reason=None):
+        self.end_test(test.id(), "skip", False, reason)
 
-    def addSkip(self, test, details=None):
-        self.end_test(test.id(), "skip", False, details)
+    def addExpectedFailure(self, test, err=None):
+        self.end_test(test.id(), "xfail", False, err)
 
-    def addExpectedFail(self, test, details=None):
-        self.end_test(test.id(), "xfail", False, details)
+    def addUnexpectedSuccess(self, test):
+        self.end_test(test.id(), "uxsuccess", True)
 
-    def end_test(self, testname, result, unexpected, reason=None):
+    def end_test(self, testname, result, unexpected, err=None):
         if not unexpected:
             self.test_output[self.name] = ""
             if not self.immediate:
@@ -526,17 +658,18 @@ class PlainFormatter(TestsuiteEnabledTestResult):
             self.test_output[self.name] = ""
 
         self.test_output[self.name] += "UNEXPECTED(%s): %s\n" % (result, testname)
-        if reason is not None:
-            self.test_output[self.name] += "REASON: %s\n" % (unicode(reason[1]).encode("utf-8").strip(),)
+        if err is not None:
+            self.test_output[self.name] += "REASON: %s\n" % str(err[1]).strip()
 
         if self.immediate and not self.verbose:
-            print self.test_output[self.name]
+            sys.stdout.write(self.test_output[self.name])
             self.test_output[self.name] = ""
 
         if not self.immediate:
             sys.stdout.write({
                'error': 'E',
                'failure': 'F',
+               'uxsuccess': 'U',
                'success': 'S'}.get(result, "?"))
 
     def write_summary(self, path):
@@ -554,11 +687,11 @@ class PlainFormatter(TestsuiteEnabledTestResult):
 
         if not self.immediate and not self.verbose:
             for suite in self.suitesfailed:
-                print "=" * 78
-                print "FAIL: %s" % suite
+                print("=" * 78)
+                print("FAIL: %s" % suite)
                 if suite in self.test_output:
-                    print self.test_output[suite]
-                print ""
+                    print(self.test_output[suite])
+                print("")
 
         f.write("= Skipped tests =\n")
         for reason in self.skips.keys():
@@ -570,15 +703,17 @@ class PlainFormatter(TestsuiteEnabledTestResult):
 
         if (not self.suitesfailed and
             not self.statistics['TESTS_UNEXPECTED_FAIL'] and
+            not self.statistics['TESTS_UNEXPECTED_OK'] and
             not self.statistics['TESTS_ERROR']):
             ok = (self.statistics['TESTS_EXPECTED_OK'] +
                   self.statistics['TESTS_EXPECTED_FAIL'])
-            print "\nALL OK (%d tests in %d testsuites)" % (ok, self.suites_ok)
+            print("\nALL OK (%d tests in %d testsuites)" % (ok, self.suites_ok))
         else:
-            print "\nFAILED (%d failures and %d errors in %d testsuites)" % (
+            print("\nFAILED (%d failures, %d errors and %d unexpected successes in %d testsuites)" % (
                 self.statistics['TESTS_UNEXPECTED_FAIL'],
                 self.statistics['TESTS_ERROR'],
-                len(self.suitesfailed))
+                self.statistics['TESTS_UNEXPECTED_OK'],
+                len(self.suitesfailed)))
 
     def skip_testsuite(self, name, reason="UNKNOWN"):
         self.skips.setdefault(reason, []).append(name)