test_baseexception.py 6.86 KB
Newer Older
1
import unittest
2
import builtins
3 4 5
import os
from platform import system as platform_system

6

7 8 9 10 11 12
class ExceptionClassTests(unittest.TestCase):

    """Tests for anything relating to exception objects themselves (e.g.,
    inheritance hierarchy)"""

    def test_builtins_new_style(self):
13
        self.assertTrue(issubclass(Exception, object))
14 15

    def verify_instance_interface(self, ins):
16
        for attr in ("args", "__str__", "__repr__"):
17
            self.assertTrue(hasattr(ins, attr),
18 19
                    "%s missing %s attribute" %
                        (ins.__class__.__name__, attr))
20 21 22

    def test_inheritance(self):
        # Make sure the inheritance hierarchy matches the documentation
23
        exc_set = set()
24
        for object_ in builtins.__dict__.values():
25 26 27 28 29 30
            try:
                if issubclass(object_, BaseException):
                    exc_set.add(object_.__name__)
            except TypeError:
                pass

31 32 33 34 35
        inheritance_tree = open(os.path.join(os.path.split(__file__)[0],
                                                'exception_hierarchy.txt'))
        try:
            superclass_name = inheritance_tree.readline().rstrip()
            try:
36
                last_exc = getattr(builtins, superclass_name)
37 38
            except AttributeError:
                self.fail("base class %s not a built-in" % superclass_name)
39 40
            self.assertIn(superclass_name, exc_set,
                          '%s not found' % superclass_name)
41 42 43 44 45 46 47 48 49 50
            exc_set.discard(superclass_name)
            superclasses = []  # Loop will insert base exception
            last_depth = 0
            for exc_line in inheritance_tree:
                exc_line = exc_line.rstrip()
                depth = exc_line.rindex('-')
                exc_name = exc_line[depth+2:]  # Slice past space
                if '(' in exc_name:
                    paren_index = exc_name.index('(')
                    platform_name = exc_name[paren_index+1:-1]
51
                    exc_name = exc_name[:paren_index-1]  # Slice off space
52 53 54 55 56 57 58
                    if platform_system() != platform_name:
                        exc_set.discard(exc_name)
                        continue
                if '[' in exc_name:
                    left_bracket = exc_name.index('[')
                    exc_name = exc_name[:left_bracket-1]  # cover space
                try:
59
                    exc = getattr(builtins, exc_name)
60 61 62 63 64 65 66
                except AttributeError:
                    self.fail("%s not a built-in exception" % exc_name)
                if last_depth < depth:
                    superclasses.append((last_depth, last_exc))
                elif last_depth > depth:
                    while superclasses[-1][0] >= depth:
                        superclasses.pop()
67
                self.assertTrue(issubclass(exc, superclasses[-1][1]),
68 69 70 71 72 73
                "%s is not a subclass of %s" % (exc.__name__,
                    superclasses[-1][1].__name__))
                try:  # Some exceptions require arguments; just skip them
                    self.verify_instance_interface(exc())
                except TypeError:
                    pass
74
                self.assertIn(exc_name, exc_set)
75 76 77 78 79
                exc_set.discard(exc_name)
                last_exc = exc
                last_depth = depth
        finally:
            inheritance_tree.close()
80
        self.assertEqual(len(exc_set), 0, "%s not accounted for" % exc_set)
81

82
    interface_tests = ("length", "args", "str", "repr")
83 84 85

    def interface_test_driver(self, results):
        for test_name, (given, expected) in zip(self.interface_tests, results):
86
            self.assertEqual(given, expected, "%s: %s != %s" % (test_name,
87 88 89 90 91 92
                given, expected))

    def test_interface_single_arg(self):
        # Make sure interface works properly when given a single argument
        arg = "spam"
        exc = Exception(arg)
93 94 95 96
        results = ([len(exc.args), 1], [exc.args[0], arg],
                   [str(exc), str(arg)],
            [repr(exc), exc.__class__.__name__ + repr(exc.args)])
        self.interface_test_driver(results)
97 98 99 100 101 102

    def test_interface_multi_arg(self):
        # Make sure interface correct when multiple arguments given
        arg_count = 3
        args = tuple(range(arg_count))
        exc = Exception(*args)
103 104 105 106
        results = ([len(exc.args), arg_count], [exc.args, args],
                [str(exc), str(args)],
                [repr(exc), exc.__class__.__name__ + repr(exc.args)])
        self.interface_test_driver(results)
107 108 109 110

    def test_interface_no_arg(self):
        # Make sure that with no args that interface is correct
        exc = Exception()
111 112 113 114
        results = ([len(exc.args), 0], [exc.args, tuple()],
                [str(exc), ''],
                [repr(exc), exc.__class__.__name__ + '()'])
        self.interface_test_driver(results)
115 116 117 118 119

class UsageTests(unittest.TestCase):

    """Test usage of exceptions"""

120 121 122 123 124 125 126 127 128 129 130 131
    def raise_fails(self, object_):
        """Make sure that raising 'object_' triggers a TypeError."""
        try:
            raise object_
        except TypeError:
            return  # What is expected.
        self.fail("TypeError expected for raising %s" % type(object_))

    def catch_fails(self, object_):
        """Catching 'object_' should raise a TypeError."""
        try:
            try:
132
                raise Exception
133 134 135 136
            except object_:
                pass
        except TypeError:
            pass
137
        except Exception:
138 139 140 141
            self.fail("TypeError expected when catching %s" % type(object_))

        try:
            try:
142
                raise Exception
143 144 145 146
            except (object_,):
                pass
        except TypeError:
            return
147
        except Exception:
148 149 150
            self.fail("TypeError expected when catching %s as specified in a "
                        "tuple" % type(object_))

151
    def test_raise_new_style_non_exception(self):
152 153 154 155
        # You cannot raise a new-style class that does not inherit from
        # BaseException; the ability was not possible until BaseException's
        # introduction so no need to support new-style objects that do not
        # inherit from it.
156 157
        class NewStyleClass(object):
            pass
158 159
        self.raise_fails(NewStyleClass)
        self.raise_fails(NewStyleClass())
160 161 162

    def test_raise_string(self):
        # Raising a string raises TypeError.
163
        self.raise_fails("spam")
164

165 166 167 168 169 170 171 172
    def test_catch_non_BaseException(self):
        # Tryinng to catch an object that does not inherit from BaseException
        # is not allowed.
        class NonBaseException(object):
            pass
        self.catch_fails(NonBaseException)
        self.catch_fails(NonBaseException())

173 174 175 176
    def test_catch_BaseException_instance(self):
        # Catching an instance of a BaseException subclass won't work.
        self.catch_fails(BaseException())

177
    def test_catch_string(self):
178 179
        # Catching a string is bad.
        self.catch_fails("spam")
180 181 182


if __name__ == '__main__':
183
    unittest.main()