PageRenderTime 11ms CodeModel.GetById 2ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 0ms

/Lib/test/test_atexit.py

http://unladen-swallow.googlecode.com/
Python | 81 lines | 63 code | 16 blank | 2 comment | 3 complexity | 0659715f7a8000c2a168796a3a4fbfd3 MD5 | raw file
 1import sys
 2import unittest
 3import StringIO
 4import atexit
 5from test import test_support
 6
 7class TestCase(unittest.TestCase):
 8    def setUp(self):
 9        s = StringIO.StringIO()
10        self.save_stdout = sys.stdout
11        self.save_stderr = sys.stderr
12        sys.stdout = sys.stderr = self.subst_io = s
13        self.save_handlers = atexit._exithandlers
14        atexit._exithandlers = []
15
16    def tearDown(self):
17        sys.stdout = self.save_stdout
18        sys.stderr = self.save_stderr
19        atexit._exithandlers = self.save_handlers
20
21    def test_args(self):
22        atexit.register(self.h1)
23        atexit.register(self.h4)
24        atexit.register(self.h4, 4, kw="abc")
25        atexit._run_exitfuncs()
26        self.assertEqual(self.subst_io.getvalue(),
27                         "h4 (4,) {'kw': 'abc'}\nh4 () {}\nh1\n")
28
29    def test_badargs(self):
30        atexit.register(lambda: 1, 0, 0, (x for x in (1,2)), 0, 0)
31        self.assertRaises(TypeError, atexit._run_exitfuncs)
32
33    def test_order(self):
34        atexit.register(self.h1)
35        atexit.register(self.h2)
36        atexit.register(self.h3)
37        atexit._run_exitfuncs()
38        self.assertEqual(self.subst_io.getvalue(), "h3\nh2\nh1\n")
39
40    def test_sys_override(self):
41        # be sure a preset sys.exitfunc is handled properly
42        exfunc = sys.exitfunc
43        sys.exitfunc = self.h1
44        reload(atexit)
45        try:
46            atexit.register(self.h2)
47            atexit._run_exitfuncs()
48        finally:
49            sys.exitfunc = exfunc
50        self.assertEqual(self.subst_io.getvalue(), "h2\nh1\n")
51
52    def test_raise(self):
53        atexit.register(self.raise1)
54        atexit.register(self.raise2)
55        self.assertRaises(TypeError, atexit._run_exitfuncs)
56
57    ### helpers
58    def h1(self):
59        print "h1"
60
61    def h2(self):
62        print "h2"
63
64    def h3(self):
65        print "h3"
66
67    def h4(self, *args, **kwargs):
68        print "h4", args, kwargs
69
70    def raise1(self):
71        raise TypeError
72
73    def raise2(self):
74        raise SystemError
75
76def test_main():
77    test_support.run_unittest(TestCase)
78
79
80if __name__ == "__main__":
81    test_main()