python/samba/netcmd/schema.py: add schema show_oc for attribute
[kai/samba-autobuild/.git] / selftest / subunithelper.py
index 5308e99a243266b2fac8f224a21bd15adaf8c331..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 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', 'uxsuccess', 'testsuite-uxsuccess']
+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(unittest.TestResult):
 
@@ -58,8 +65,8 @@ def parse_results(msg_ops, statistics, fh):
             msg_ops.control_msg(l)
             try:
                 dt = iso8601.parse_date(arg.rstrip("\n"))
-            except TypeError, e:
-                print "Unable to parse time line: %s" % 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:
@@ -120,7 +128,7 @@ def parse_results(msg_ops, statistics, fh):
                     msg_ops.addError(subunit.RemotedTestCase(testname), subunit.RemoteError(u"Test was never started"))
                 else:
                     statistics['TESTS_UNEXPECTED_OK']+=1
-                    msg_ops.addUnexpectedSuccess(test, remote_error)
+                    msg_ops.addUnexpectedSuccess(test)
                     exitcode = 1
             elif result in ("failure", "fail"):
                 try:
@@ -223,26 +231,38 @@ class SubunitOps(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 ""
@@ -283,14 +303,7 @@ class FilterOps(unittest.TestResult):
         self._ops.startTest(test)
 
     def _add_prefix(self, test):
-        prefix = ""
-        suffix = ""
-        if self.prefix is not None:
-            prefix = self.prefix
-        if self.suffix is not None:
-            suffix = self.suffix
-
-        return subunit.RemotedTestCase(prefix + test.id() + suffix)
+        return subunit.RemotedTestCase(self.prefix + test.id() + self.suffix)
 
     def addError(self, test, err=None):
         test = self._add_prefix(test)
@@ -312,11 +325,11 @@ class FilterOps(unittest.TestResult):
         self._ops.addExpectedFailure(test, err)
         self.output = None
 
-    def addUnexpectedSuccess(self, test, err=None):
+    def addUnexpectedSuccess(self, test):
         test = self._add_prefix(test)
         self.uxsuccess_added+=1
         self.total_uxsuccess+=1
-        self._ops.addUnexpectedSuccess(test, err)
+        self._ops.addUnexpectedSuccess(test)
         if self.output:
             self._ops.output_msg(self.output)
         self.output = None
@@ -348,7 +361,7 @@ class FilterOps(unittest.TestResult):
         if xfail_reason is not None:
             self.uxsuccess_added += 1
             self.total_uxsuccess += 1
-            self._ops.addUnexpectedSuccess(test, subunit.RemoteError(xfail_reason))
+            self._ops.addUnexpectedSuccess(test)
             if self.output:
                 self._ops.output_msg(self.output)
             if self.fail_immediately:
@@ -432,6 +445,73 @@ class FilterOps(unittest.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,
@@ -521,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
@@ -607,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():
@@ -627,13 +707,13 @@ class PlainFormatter(TestsuiteEnabledTestResult):
             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, %d errors and %d unexpected successes 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'],
                 self.statistics['TESTS_UNEXPECTED_OK'],
-                len(self.suitesfailed))
+                len(self.suitesfailed)))
 
     def skip_testsuite(self, name, reason="UNKNOWN"):
         self.skips.setdefault(reason, []).append(name)