PageRenderTime 105ms CodeModel.GetById 40ms app.highlight 22ms RepoModel.GetById 38ms app.codeStats 0ms

/Lib/test/test_pep352.py

http://unladen-swallow.googlecode.com/
Python | 249 lines | 219 code | 18 blank | 12 comment | 20 complexity | 6861ef6c4af5b8ae145410114ac5244e MD5 | raw file
  1import unittest
  2import __builtin__
  3import exceptions
  4import warnings
  5from test.test_support import run_unittest
  6import os
  7from platform import system as platform_system
  8
  9def ignore_message_warning():
 10    """Ignore the DeprecationWarning for BaseException.message."""
 11    warnings.resetwarnings()
 12    warnings.filterwarnings("ignore", "BaseException.message",
 13                            DeprecationWarning)
 14
 15
 16class ExceptionClassTests(unittest.TestCase):
 17
 18    """Tests for anything relating to exception objects themselves (e.g.,
 19    inheritance hierarchy)"""
 20
 21    def test_builtins_new_style(self):
 22        self.failUnless(issubclass(Exception, object))
 23
 24    def verify_instance_interface(self, ins):
 25        with warnings.catch_warnings():
 26            ignore_message_warning()
 27            for attr in ("args", "message", "__str__", "__repr__",
 28                            "__getitem__"):
 29                self.failUnless(hasattr(ins, attr),
 30                        "%s missing %s attribute" %
 31                            (ins.__class__.__name__, attr))
 32
 33    def test_inheritance(self):
 34        # Make sure the inheritance hierarchy matches the documentation
 35        exc_set = set(x for x in dir(exceptions) if not x.startswith('_'))
 36        inheritance_tree = open(os.path.join(os.path.split(__file__)[0],
 37                                                'exception_hierarchy.txt'))
 38        try:
 39            superclass_name = inheritance_tree.readline().rstrip()
 40            try:
 41                last_exc = getattr(__builtin__, superclass_name)
 42            except AttributeError:
 43                self.fail("base class %s not a built-in" % superclass_name)
 44            self.failUnless(superclass_name in exc_set)
 45            exc_set.discard(superclass_name)
 46            superclasses = []  # Loop will insert base exception
 47            last_depth = 0
 48            for exc_line in inheritance_tree:
 49                exc_line = exc_line.rstrip()
 50                depth = exc_line.rindex('-')
 51                exc_name = exc_line[depth+2:]  # Slice past space
 52                if '(' in exc_name:
 53                    paren_index = exc_name.index('(')
 54                    platform_name = exc_name[paren_index+1:-1]
 55                    exc_name = exc_name[:paren_index-1]  # Slice off space
 56                    if platform_system() != platform_name:
 57                        exc_set.discard(exc_name)
 58                        continue
 59                if '[' in exc_name:
 60                    left_bracket = exc_name.index('[')
 61                    exc_name = exc_name[:left_bracket-1]  # cover space
 62                try:
 63                    exc = getattr(__builtin__, exc_name)
 64                except AttributeError:
 65                    self.fail("%s not a built-in exception" % exc_name)
 66                if last_depth < depth:
 67                    superclasses.append((last_depth, last_exc))
 68                elif last_depth > depth:
 69                    while superclasses[-1][0] >= depth:
 70                        superclasses.pop()
 71                self.failUnless(issubclass(exc, superclasses[-1][1]),
 72                "%s is not a subclass of %s" % (exc.__name__,
 73                    superclasses[-1][1].__name__))
 74                try:  # Some exceptions require arguments; just skip them
 75                    self.verify_instance_interface(exc())
 76                except TypeError:
 77                    pass
 78                self.failUnless(exc_name in exc_set)
 79                exc_set.discard(exc_name)
 80                last_exc = exc
 81                last_depth = depth
 82        finally:
 83            inheritance_tree.close()
 84        self.failUnlessEqual(len(exc_set), 0, "%s not accounted for" % exc_set)
 85
 86    interface_tests = ("length", "args", "message", "str", "unicode", "repr",
 87            "indexing")
 88
 89    def interface_test_driver(self, results):
 90        for test_name, (given, expected) in zip(self.interface_tests, results):
 91            self.failUnlessEqual(given, expected, "%s: %s != %s" % (test_name,
 92                given, expected))
 93
 94    def test_interface_single_arg(self):
 95        # Make sure interface works properly when given a single argument
 96        arg = "spam"
 97        exc = Exception(arg)
 98        with warnings.catch_warnings():
 99            ignore_message_warning()
100            results = ([len(exc.args), 1], [exc.args[0], arg],
101                    [exc.message, arg],
102                    [str(exc), str(arg)], [unicode(exc), unicode(arg)],
103                [repr(exc), exc.__class__.__name__ + repr(exc.args)], [exc[0],
104                arg])
105            self.interface_test_driver(results)
106
107    def test_interface_multi_arg(self):
108        # Make sure interface correct when multiple arguments given
109        arg_count = 3
110        args = tuple(range(arg_count))
111        exc = Exception(*args)
112        with warnings.catch_warnings():
113            ignore_message_warning()
114            results = ([len(exc.args), arg_count], [exc.args, args],
115                    [exc.message, ''], [str(exc), str(args)],
116                    [unicode(exc), unicode(args)],
117                    [repr(exc), exc.__class__.__name__ + repr(exc.args)],
118                    [exc[-1], args[-1]])
119            self.interface_test_driver(results)
120
121    def test_interface_no_arg(self):
122        # Make sure that with no args that interface is correct
123        exc = Exception()
124        with warnings.catch_warnings():
125            ignore_message_warning()
126            results = ([len(exc.args), 0], [exc.args, tuple()],
127                    [exc.message, ''],
128                    [str(exc), ''], [unicode(exc), u''],
129                    [repr(exc), exc.__class__.__name__ + '()'], [True, True])
130            self.interface_test_driver(results)
131
132
133    def test_message_deprecation(self):
134        # As of Python 2.6, BaseException.message is deprecated.
135        with warnings.catch_warnings():
136            warnings.resetwarnings()
137            warnings.filterwarnings('error')
138
139            try:
140                BaseException().message
141            except DeprecationWarning:
142                pass
143            else:
144                self.fail("BaseException.message not deprecated")
145
146
147class UsageTests(unittest.TestCase):
148
149    """Test usage of exceptions"""
150
151    def raise_fails(self, object_):
152        """Make sure that raising 'object_' triggers a TypeError."""
153        try:
154            raise object_
155        except TypeError:
156            return  # What is expected.
157        self.fail("TypeError expected for raising %s" % type(object_))
158
159    def catch_fails(self, object_):
160        """Catching 'object_' should raise a TypeError."""
161        try:
162            try:
163                raise StandardError
164            except object_:
165                pass
166        except TypeError:
167            pass
168        except StandardError:
169            self.fail("TypeError expected when catching %s" % type(object_))
170
171        try:
172            try:
173                raise StandardError
174            except (object_,):
175                pass
176        except TypeError:
177            return
178        except StandardError:
179            self.fail("TypeError expected when catching %s as specified in a "
180                        "tuple" % type(object_))
181
182    def test_raise_classic(self):
183        # Raising a classic class is okay (for now).
184        class ClassicClass:
185            pass
186        try:
187            raise ClassicClass
188        except ClassicClass:
189            pass
190        except:
191            self.fail("unable to raise classic class")
192        try:
193            raise ClassicClass()
194        except ClassicClass:
195            pass
196        except:
197            self.fail("unable to raise class class instance")
198
199    def test_raise_new_style_non_exception(self):
200        # You cannot raise a new-style class that does not inherit from
201        # BaseException; the ability was not possible until BaseException's
202        # introduction so no need to support new-style objects that do not
203        # inherit from it.
204        class NewStyleClass(object):
205            pass
206        self.raise_fails(NewStyleClass)
207        self.raise_fails(NewStyleClass())
208
209    def test_raise_string(self):
210        # Raising a string raises TypeError.
211        self.raise_fails("spam")
212
213    def test_catch_string(self):
214        # Catching a string should trigger a DeprecationWarning.
215        with warnings.catch_warnings():
216            warnings.resetwarnings()
217            warnings.filterwarnings("error")
218            str_exc = "spam"
219            try:
220                try:
221                    raise StandardError
222                except str_exc:
223                    pass
224            except DeprecationWarning:
225                pass
226            except StandardError:
227                self.fail("catching a string exception did not raise "
228                            "DeprecationWarning")
229            # Make sure that even if the string exception is listed in a tuple
230            # that a warning is raised.
231            try:
232                try:
233                    raise StandardError
234                except (AssertionError, str_exc):
235                    pass
236            except DeprecationWarning:
237                pass
238            except StandardError:
239                self.fail("catching a string exception specified in a tuple did "
240                            "not raise DeprecationWarning")
241
242
243def test_main():
244    run_unittest(ExceptionClassTests, UsageTests)
245
246
247
248if __name__ == '__main__':
249    test_main()