• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import sys
2import unittest
3import StringIO
4import atexit
5from imp import reload
6from test import test_support
7
8
9def exit():
10    raise SystemExit
11
12
13class TestCase(unittest.TestCase):
14    def setUp(self):
15        self.save_stdout = sys.stdout
16        self.save_stderr = sys.stderr
17        self.stream = StringIO.StringIO()
18        sys.stdout = sys.stderr = self.subst_io = self.stream
19        self.save_handlers = atexit._exithandlers
20        atexit._exithandlers = []
21
22    def tearDown(self):
23        sys.stdout = self.save_stdout
24        sys.stderr = self.save_stderr
25        atexit._exithandlers = self.save_handlers
26
27    def test_args(self):
28        atexit.register(self.h1)
29        atexit.register(self.h4)
30        atexit.register(self.h4, 4, kw="abc")
31        atexit._run_exitfuncs()
32        self.assertEqual(self.subst_io.getvalue(),
33                         "h4 (4,) {'kw': 'abc'}\nh4 () {}\nh1\n")
34
35    def test_badargs(self):
36        atexit.register(lambda: 1, 0, 0, (x for x in (1,2)), 0, 0)
37        self.assertRaises(TypeError, atexit._run_exitfuncs)
38
39    def test_order(self):
40        atexit.register(self.h1)
41        atexit.register(self.h2)
42        atexit.register(self.h3)
43        atexit._run_exitfuncs()
44        self.assertEqual(self.subst_io.getvalue(), "h3\nh2\nh1\n")
45
46    def test_sys_override(self):
47        # be sure a preset sys.exitfunc is handled properly
48        exfunc = sys.exitfunc
49        sys.exitfunc = self.h1
50        reload(atexit)
51        try:
52            atexit.register(self.h2)
53            atexit._run_exitfuncs()
54        finally:
55            sys.exitfunc = exfunc
56        self.assertEqual(self.subst_io.getvalue(), "h2\nh1\n")
57
58    def test_raise(self):
59        atexit.register(self.raise1)
60        atexit.register(self.raise2)
61        self.assertRaises(TypeError, atexit._run_exitfuncs)
62
63    def test_exit(self):
64        # be sure a SystemExit is handled properly
65        atexit.register(exit)
66
67        self.assertRaises(SystemExit, atexit._run_exitfuncs)
68        self.assertEqual(self.stream.getvalue(), '')
69
70    ### helpers
71    def h1(self):
72        print "h1"
73
74    def h2(self):
75        print "h2"
76
77    def h3(self):
78        print "h3"
79
80    def h4(self, *args, **kwargs):
81        print "h4", args, kwargs
82
83    def raise1(self):
84        raise TypeError
85
86    def raise2(self):
87        raise SystemError
88
89def test_main():
90    test_support.run_unittest(TestCase)
91
92
93if __name__ == "__main__":
94    test_main()
95