Commits

Georg Brandl committed 4c3abad

Fixup regex tests to use unittest.TestCase and mostly standard unittest assertions.

  • Participants
  • Parent commits 68c8727

Comments (0)

Files changed (1)

File Lib/test/test_regex.py

 import sys
 import unicodedata
 from weakref import proxy
-
-class Test:
+import unittest
+from test.support import run_unittest
+
+class RegexTests(unittest.TestCase):
     MATCH_CLASS = "<class '_regex.Match'>"
     PATTERN_CLASS = "<class '_regex.Pattern'>"
     FLAGS_WITH_COMPILED_PAT = """ValueError("can't process flags argument with a compiled pattern",)"""
     DUPLICATE_GROUP = "error('duplicate group',)"
     CANT_TURN_OFF = """error("bad inline flags: can't turn flags off",)"""
 
-    def __init__(self):
-        pass
-
     def expect(self, code, expected_result):
-        self.index += 1
-        try:
-            actual_result = ascii(code())
-        except Exception as e:
-            actual_result = ascii(e)
-        if actual_result != expected_result:
-            self.record_failure("Expected {} but got {} instead".format(expected_result,
-              actual_result))
-
-    def record_failure(self, message="Failed"):
-        self.failed_tests.append((self.performing, self.index, message))
+        actual_result = ascii(code())
+        self.assertEqual(actual_result, expected_result)
 
     def test_weakref(self):
-        self.index += 1
         s = 'QabbbcR'
         x = regex.compile('ab+c')
         y = proxy(x)
         if x.findall('QabbbcR') != y.findall('QabbbcR'):
-            self.record_failure()
+            self.fail()
 
     def test_search_star_plus(self):
         # 1..10
         sigma = "\u03A3\u03C3\u03C2"
         for ch1 in sigma:
             for ch2 in sigma:
-                self.index += 1
                 if not regex.match(r"(?fi)" + ch1, ch2):
-                    self.record_failure()
+                    self.fail()
 
         # 28..39
         self.expect(lambda: bool(regex.search(r"(?iV1)ff", "\uFB00\uFB01")),
         self.expect(lambda: pat.match(p).span(), ascii((0, 256)))
 
     def test_constants(self):
-        self.index += 1
         if regex.I != regex.IGNORECASE:
-            self.record_failure()
-        self.index += 1
+            self.fail()
         if regex.L != regex.LOCALE:
-            self.record_failure()
-        self.index += 1
+            self.fail()
         if regex.M != regex.MULTILINE:
-            self.record_failure()
-        self.index += 1
+            self.fail()
         if regex.S != regex.DOTALL:
-            self.record_failure()
-        self.index += 1
+            self.fail()
         if regex.X != regex.VERBOSE:
-            self.record_failure()
+            self.fail()
 
     def test_flags(self):
         for flag in [regex.I, regex.M, regex.X, regex.S, regex.L]:
         self.expect(lambda: [item[0] for item in it], ascii([':', '::', ':::']))
 
     def test_bug_926075(self):
-        self.index += 1
         if regex.compile('bug_926075') is regex.compile(b'bug_926075'):
-            self.record_failure()
+            self.fail()
 
     def test_bug_931848(self):
         pattern = "[\u002E\u3002\uFF0E\uFF61]"
         self.expect(lambda: regex.compile('(?au)\w'), self.MIXED_FLAGS)
 
     def test_subscripting_match(self):
-        self.index += 1
         m = regex.match(r'(?<a>\w)', 'xy')
         if not m:
-            self.record_failure("Failed: expected match but returned None")
+            self.fail("Failed: expected match but returned None")
         elif not m or m[0] != m.group(0) or m[1] != m.group(1):
-            self.record_failure("Failed")
-        self.index += 1
+            self.fail("Failed")
         if not m:
-            self.record_failure("Failed: expected match but returned None")
+            self.fail("Failed: expected match but returned None")
         elif m[:] != ('x', 'x'):
-            self.record_failure("Failed: expected \"('x', 'x')\" but got {} instead".format(ascii(m[:])))
+            self.fail("Failed: expected \"('x', 'x')\" but got {} instead".format(ascii(m[:])))
 
     def test_new_named_groups(self):
-        self.index += 1
         m0 = regex.match(r'(?P<a>\w)', 'x')
         m1 = regex.match(r'(?<a>\w)', 'x')
         if not (m0 and m1 and m0[:] == m1[:]):
-            self.record_failure("Failed")
+            self.fail("Failed")
 
     def test_properties(self):
         # 1..4
             (br"(?a)[[:^xdigit:]]", chars_b, b"-Zz_"),
         ]
         for pattern, chars, expected in tests:
-            self.index += 1
             try:
                 if chars[ : 0].join(regex.findall(pattern, chars)) != expected:
-                    self.record_failure("Failed: {}".format(pattern))
+                    self.fail("Failed: {}".format(pattern))
             except Exception as e:
-                self.record_failure("Failed: {} raised {}".format(pattern,
+                self.fail("Failed: {} raised {}".format(pattern,
                   ascii(e)))
 
     def test_word_class(self):
         ]
 
         for t in tests:
-            self.index += 1
             try:
                 pattern, string, groups, expected = t
             except ValueError:
                 fields = ", ".join([ascii(f) for f in t[ : 3]] + ["..."])
-                self.record_failure("Incorrect number of test fields: ({})".format(fields))
+                self.fail("Incorrect number of test fields: ({})".format(fields))
             else:
                 group_list = []
                 if groups:
 
                 if actual != expected:
                     fields = ", ".join([ascii(f) for f in t[ : 3]] + ["..."])
-                    self.record_failure("Expected {} but got {} instead: ({})".format(expected,
+                    self.fail("Expected {} but got {} instead: ({})".format(expected,
                       actual, fields))
 
     def test_replacement(self):
 
         for ch1 in all_chars:
             for ch2 in all_chars:
-                self.index += 1
                 m = regex.match(r"(?i)\A" + ch1 + r"\Z", ch2)
                 if m:
                     if (ch1, ch2) not in matching:
-                        self.record_failure("{} matching {}".format(ascii(ch1),
+                        self.fail("{} matching {}".format(ascii(ch1),
                           ascii(ch2)))
                 else:
                     if (ch1, ch2) in matching:
-                        self.record_failure("{} not matching {}".format(ascii(ch1),
+                        self.fail("{} not matching {}".format(ascii(ch1),
                           ascii(ch2)))
 
     def test_named_lists(self):
         self.expect(lambda: regex.search("(a|)+", "a").group(0, 1),
           ascii(("a", "")))
 
-    def run(self):
-        print("Performing tests")
-        print("================")
-
-        def make_key(name):
-            pos = len(name)
-            while name[pos - 1].isdigit():
-                pos -= 1
-            return (name[ : pos], int(name[pos : ] or "0"))
-
-        funcs = [name for name in dir(self) if name.startswith("test_")]
-        funcs.sort(key=make_key)
-
-        self.failed_tests = []
-        performed_count = 0
-
-        for name in funcs:
-            obj = getattr(self, name)
-            if hasattr(obj, "__call__"):
-                self.performing = name
-                performed_count += 1
-                self.index = 0
-                print(self.performing)
-                sys.stdout.flush()
-                obj()
-
-        print()
-        print("Performed {}".format(performed_count))
-        print()
-
-        if self.failed_tests:
-            print("Failures")
-            print("========")
-            current = ""
-            failed_count = 0
-            for name, index, message in self.failed_tests:
-                if name != current:
-                    if current:
-                        print()
-                    current = name
-                    failed_count += 1
-                    print(current)
-                print("\t{}) {}".format(index, message))
-            print()
-            print("Failed {}".format(failed_count))
-        else:
-            print("Passed")
+
+def test_main():
+    run_unittest(RegexTests)
 
 if __name__ == "__main__":
-    Test().run()
+    test_main()