s4:rpc_server: only pass dcesrv_auth to auth_state.session_key_fn()
[samba.git] / selftest / subunithelper.py
index c065e9edbad3704fd6d355f9d5a21a733af54491..651d9b00289dc597295b63944a6616e0ed4cb315 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
+from samba.compat import binary_type
+
+
+VALID_RESULTS = set(['success', 'successful', 'failure', 'fail', 'skip',
+                     'knownfail', 'error', 'xfail', 'skip-testsuite',
+                     'testsuite-failure', 'testsuite-xfail',
+                     'testsuite-success', 'testsuite-error',
+                     'uxsuccess', 'testsuite-uxsuccess'])
 
-VALID_RESULTS = ['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 +68,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,16 +86,20 @@ 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:
                         reason += l
 
-                remote_error = subunit.RemoteError(reason.decode("utf-8"))
+                if isinstance(reason, binary_type):
+                    remote_error = subunit.RemoteError(reason.decode("utf-8"))
+                else:
+                    remote_error = subunit.RemoteError(reason)
 
                 if not terminated:
-                    statistics['TESTS_ERROR']+=1
+                    statistics['TESTS_ERROR'] += 1
                     msg_ops.addError(subunit.RemotedTestCase(testname), subunit.RemoteError(u"reason (%s) interrupted" % result))
                     return 1
             else:
@@ -95,46 +109,46 @@ def parse_results(msg_ops, statistics, fh):
                 try:
                     test = open_tests.pop(testname)
                 except KeyError:
-                    statistics['TESTS_ERROR']+=1
+                    statistics['TESTS_ERROR'] += 1
                     exitcode = 1
                     msg_ops.addError(subunit.RemotedTestCase(testname), subunit.RemoteError(u"Test was never started"))
                 else:
-                    statistics['TESTS_EXPECTED_OK']+=1
+                    statistics['TESTS_EXPECTED_OK'] += 1
                     msg_ops.addSuccess(test)
             elif result in ("xfail", "knownfail"):
                 try:
                     test = open_tests.pop(testname)
                 except KeyError:
-                    statistics['TESTS_ERROR']+=1
+                    statistics['TESTS_ERROR'] += 1
                     exitcode = 1
                     msg_ops.addError(subunit.RemotedTestCase(testname), subunit.RemoteError(u"Test was never started"))
                 else:
-                    statistics['TESTS_EXPECTED_FAIL']+=1
+                    statistics['TESTS_EXPECTED_FAIL'] += 1
                     msg_ops.addExpectedFailure(test, remote_error)
             elif result in ("uxsuccess", ):
                 try:
                     test = open_tests.pop(testname)
                 except KeyError:
-                    statistics['TESTS_ERROR']+=1
+                    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
+                    statistics['TESTS_UNEXPECTED_OK'] += 1
                     msg_ops.addUnexpectedSuccess(test)
                     exitcode = 1
             elif result in ("failure", "fail"):
                 try:
                     test = open_tests.pop(testname)
                 except KeyError:
-                    statistics['TESTS_ERROR']+=1
+                    statistics['TESTS_ERROR'] += 1
                     exitcode = 1
                     msg_ops.addError(subunit.RemotedTestCase(testname), subunit.RemoteError(u"Test was never started"))
                 else:
-                    statistics['TESTS_UNEXPECTED_FAIL']+=1
+                    statistics['TESTS_UNEXPECTED_FAIL'] += 1
                     exitcode = 1
                     msg_ops.addFailure(test, remote_error)
             elif result == "skip":
-                statistics['TESTS_SKIP']+=1
+                statistics['TESTS_SKIP'] += 1
                 # Allow tests to be skipped without prior announcement of test
                 try:
                     test = open_tests.pop(testname)
@@ -142,7 +156,7 @@ def parse_results(msg_ops, statistics, fh):
                     test = subunit.RemotedTestCase(testname)
                 msg_ops.addSkip(test, reason)
             elif result == "error":
-                statistics['TESTS_ERROR']+=1
+                statistics['TESTS_ERROR'] += 1
                 exitcode = 1
                 try:
                     test = open_tests.pop(testname)
@@ -166,7 +180,7 @@ def parse_results(msg_ops, statistics, fh):
                 exitcode = 1
             else:
                 raise AssertionError("Recognized but unhandled result %r" %
-                    result)
+                                     result)
         elif command == "testsuite":
             msg_ops.start_testsuite(arg.strip())
         elif command == "progress":
@@ -185,13 +199,13 @@ def parse_results(msg_ops, statistics, fh):
     while open_tests:
         test = subunit.RemotedTestCase(open_tests.popitem()[1])
         msg_ops.addError(test, subunit.RemoteError(u"was started but never finished!"))
-        statistics['TESTS_ERROR']+=1
+        statistics['TESTS_ERROR'] += 1
         exitcode = 1
 
     return exitcode
 
 
-class SubunitOps(TestProtocolClient,TestsuiteEnabledTestResult):
+class SubunitOps(TestProtocolClient, TestsuiteEnabledTestResult):
 
     def progress(self, count, whence):
         if whence == subunit.PROGRESS_POP:
@@ -223,26 +237,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 ""
@@ -260,7 +286,7 @@ class ImmediateFail(Exception):
 class FilterOps(unittest.TestResult):
 
     def control_msg(self, msg):
-        pass # We regenerate control messages, so ignore this
+        pass  # We regenerate control messages, so ignore this
 
     def time(self, time):
         self._ops.time(time)
@@ -272,30 +298,23 @@ class FilterOps(unittest.TestResult):
         if self.output is None:
             sys.stdout.write(msg)
         else:
-            self.output+=msg
+            self.output += msg
 
     def startTest(self, test):
         self.seen_output = True
         test = self._add_prefix(test)
         if self.strip_ok_output:
-           self.output = ""
+            self.output = ""
 
         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)
-        self.error_added+=1
-        self.total_error+=1
+        self.error_added += 1
+        self.total_error += 1
         self._ops.addError(test, err)
         self.output = None
         if self.fail_immediately:
@@ -314,8 +333,8 @@ class FilterOps(unittest.TestResult):
 
     def addUnexpectedSuccess(self, test):
         test = self._add_prefix(test)
-        self.uxsuccess_added+=1
-        self.total_uxsuccess+=1
+        self.uxsuccess_added += 1
+        self.total_uxsuccess += 1
         self._ops.addUnexpectedSuccess(test)
         if self.output:
             self._ops.output_msg(self.output)
@@ -329,12 +348,12 @@ class FilterOps(unittest.TestResult):
         if xfail_reason is None:
             xfail_reason = find_in_list(self.flapping, test.id())
         if xfail_reason is not None:
-            self.xfail_added+=1
-            self.total_xfail+=1
+            self.xfail_added += 1
+            self.total_xfail += 1
             self._ops.addExpectedFailure(test, err)
         else:
-            self.fail_added+=1
-            self.total_fail+=1
+            self.fail_added += 1
+            self.total_fail += 1
             self._ops.addFailure(test, err)
             if self.output:
                 self._ops.output_msg(self.output)
@@ -348,7 +367,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,10 +451,77 @@ 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,
-            totaltests=None):
+                 totaltests=None):
         super(PlainFormatter, self).__init__()
         self.verbose = verbose
         self.immediate = immediate
@@ -520,11 +606,11 @@ class PlainFormatter(TestsuiteEnabledTestResult):
         out = ""
         unexpected = False
 
-        if not name in self.test_output:
-            print "no output for name[%s]" % name
+        if name not in self.test_output:
+            print("no output for name[%s]" % name)
 
         if result in ("success", "xfail"):
-            self.suites_ok+=1
+            self.suites_ok += 1
         else:
             self.output_msg("ERROR: Testsuite[%s]\n" % name)
             if reason is not None:
@@ -574,7 +660,7 @@ class PlainFormatter(TestsuiteEnabledTestResult):
                     'success': '.'}.get(result, "?(%s)" % result))
             return
 
-        if not self.name in self.test_output:
+        if self.name not in self.test_output:
             self.test_output[self.name] = ""
 
         self.test_output[self.name] += "UNEXPECTED(%s): %s\n" % (result, testname)
@@ -587,7 +673,7 @@ class PlainFormatter(TestsuiteEnabledTestResult):
 
         if not self.immediate:
             sys.stdout.write({
-               'error': 'E',
+                'error': 'E',
                'failure': 'F',
                'uxsuccess': 'U',
                'success': 'S'}.get(result, "?"))
@@ -601,17 +687,17 @@ class PlainFormatter(TestsuiteEnabledTestResult):
             for suite in self.suitesfailed:
                 f.write("== %s ==\n" % suite)
                 if suite in self.test_output:
-                    f.write(self.test_output[suite]+"\n\n")
+                    f.write(self.test_output[suite] + "\n\n")
 
             f.write("\n")
 
         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,15 +713,15 @@ 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)
         if self.totalsuites:
-            self.totalsuites-=1
+            self.totalsuites -= 1