import pickle import unittest import sys from test import test_support class TestBaseException(unittest.TestCase): # Note: a lot of these tests will need to be changed # when pep 352 is completely implemented def test_constructor(self): e = BaseException() self.assertEqual(e.message, '') self.assertEqual(e.args, ()) e = BaseException('spam') self.assertEqual(e.message, 'spam') self.assertEqual(e.args, ('spam',)) e = BaseException('spam', 'eggs') # There is a difference between the docstring # in PEP 352 and the code in its __init__ method. self.assertEqual(e.message, '') self.assertEqual(e.args, ('spam', 'eggs')) # Exceptions now accept keywordargs self.assertRaises(TypeError, BaseException, a=1) def test_attributes(self): e = BaseException() e.message = 1 self.assertEqual(e.message, 1) # exceptions don't preserve the type of args assigned anymore e.args = ['spam', 'eggs'] self.assertEqual(e.args, ['spam', 'eggs']) self.assertEqual(e.message, 1) # and only allow iterables as args e.args = 1 self.assertEqual(e.args, 1) def test_str(self): e = BaseException() self.assertEqual(str(e), '') e.message = 'spam' self.assertEqual(str(e), '') e.args = ('eggs',) self.assertEqual(str(e), 'eggs') e.args = ('eggs', 'ham') self.assertEqual(str(e), "('eggs', 'ham')") e.args = 1 self.assertEqual(str(e), '1') e.args = 'eggs' self.assertEqual(str(e), 'eggs') e.args = ['eggs'] self.assertEqual(str(e), 'eggs') def test_pickling(self): # this crashes python when e->dict == NULL e1 = BaseException() e2 = pickle.loads(pickle.dumps(e1)) self.assertEqual(e1.message, e2.message) self.assertEqual(e1.args, e2.args) def test_main(verbose=None): test_classes = ( TestBaseException, ) test_support.run_unittest(*test_classes) # verify reference counting if verbose and hasattr(sys, "gettotalrefcount"): import gc counts = [None] * 5 for i in xrange(len(counts)): test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() print counts if __name__ == "__main__": test_main(verbose=True)