blob: bdf4776b57c0c56e7cfe1f56fb41fc7c8b28e6d4 [file] [log] [blame]
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00001"""Unit tests for contextlib.py, and other context managers."""
2
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00004import sys
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00005import os
6import decimal
7import tempfile
8import unittest
9import threading
10from contextlib import * # Tests __all__
Benjamin Petersonee8712c2008-05-20 21:35:26 +000011from test import support
Raymond Hettingerc5b01952009-05-28 22:46:29 +000012import warnings
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000013
14class ContextManagerTestCase(unittest.TestCase):
15
16 def test_contextmanager_plain(self):
17 state = []
18 @contextmanager
19 def woohoo():
20 state.append(1)
21 yield 42
22 state.append(999)
23 with woohoo() as x:
24 self.assertEqual(state, [1])
25 self.assertEqual(x, 42)
26 state.append(x)
27 self.assertEqual(state, [1, 42, 999])
28
29 def test_contextmanager_finally(self):
30 state = []
31 @contextmanager
32 def woohoo():
33 state.append(1)
34 try:
35 yield 42
36 finally:
37 state.append(999)
38 try:
39 with woohoo() as x:
40 self.assertEqual(state, [1])
41 self.assertEqual(x, 42)
42 state.append(x)
43 raise ZeroDivisionError()
44 except ZeroDivisionError:
45 pass
46 else:
47 self.fail("Expected ZeroDivisionError")
48 self.assertEqual(state, [1, 42, 999])
49
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000050 def test_contextmanager_no_reraise(self):
51 @contextmanager
52 def whee():
53 yield
Thomas Wouters477c8d52006-05-27 19:21:47 +000054 ctx = whee()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000055 ctx.__enter__()
56 # Calling __exit__ should not result in an exception
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000057 self.assertFalse(ctx.__exit__(TypeError, TypeError("foo"), None))
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000058
59 def test_contextmanager_trap_yield_after_throw(self):
60 @contextmanager
61 def whoo():
62 try:
63 yield
64 except:
65 yield
Thomas Wouters477c8d52006-05-27 19:21:47 +000066 ctx = whoo()
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000067 ctx.__enter__()
68 self.assertRaises(
69 RuntimeError, ctx.__exit__, TypeError, TypeError("foo"), None
70 )
71
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000072 def test_contextmanager_except(self):
73 state = []
74 @contextmanager
75 def woohoo():
76 state.append(1)
77 try:
78 yield 42
Guido van Rossumb940e112007-01-10 16:19:56 +000079 except ZeroDivisionError as e:
Guido van Rossum1a5e21e2006-02-28 21:57:43 +000080 state.append(e.args[0])
81 self.assertEqual(state, [1, 42, 999])
82 with woohoo() as x:
83 self.assertEqual(state, [1])
84 self.assertEqual(x, 42)
85 state.append(x)
86 raise ZeroDivisionError(999)
87 self.assertEqual(state, [1, 42, 999])
88
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000089 def test_contextmanager_attribs(self):
90 def attribs(**kw):
91 def decorate(func):
92 for k,v in kw.items():
93 setattr(func,k,v)
94 return func
95 return decorate
96 @contextmanager
97 @attribs(foo='bar')
98 def baz(spam):
99 """Whee!"""
100 self.assertEqual(baz.__name__,'baz')
101 self.assertEqual(baz.foo, 'bar')
102 self.assertEqual(baz.__doc__, "Whee!")
103
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000104class ClosingTestCase(unittest.TestCase):
105
106 # XXX This needs more work
107
108 def test_closing(self):
109 state = []
110 class C:
111 def close(self):
112 state.append(1)
113 x = C()
114 self.assertEqual(state, [])
115 with closing(x) as y:
116 self.assertEqual(x, y)
117 self.assertEqual(state, [1])
118
119 def test_closing_error(self):
120 state = []
121 class C:
122 def close(self):
123 state.append(1)
124 x = C()
125 self.assertEqual(state, [])
126 try:
127 with closing(x) as y:
128 self.assertEqual(x, y)
129 1/0
130 except ZeroDivisionError:
131 self.assertEqual(state, [1])
132 else:
133 self.fail("Didn't raise ZeroDivisionError")
134
135class FileContextTestCase(unittest.TestCase):
136
137 def testWithOpen(self):
138 tfn = tempfile.mktemp()
139 try:
140 f = None
141 with open(tfn, "w") as f:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000142 self.assertFalse(f.closed)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000143 f.write("Booh\n")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000144 self.assertTrue(f.closed)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000145 f = None
146 try:
147 with open(tfn, "r") as f:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000148 self.assertFalse(f.closed)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000149 self.assertEqual(f.read(), "Booh\n")
150 1/0
151 except ZeroDivisionError:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000152 self.assertTrue(f.closed)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000153 else:
154 self.fail("Didn't raise ZeroDivisionError")
155 finally:
156 try:
157 os.remove(tfn)
158 except os.error:
159 pass
160
161class LockContextTestCase(unittest.TestCase):
162
163 def boilerPlate(self, lock, locked):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000164 self.assertFalse(locked())
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000165 with lock:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000166 self.assertTrue(locked())
167 self.assertFalse(locked())
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000168 try:
169 with lock:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000170 self.assertTrue(locked())
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000171 1/0
172 except ZeroDivisionError:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000173 self.assertFalse(locked())
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000174 else:
175 self.fail("Didn't raise ZeroDivisionError")
176
177 def testWithLock(self):
178 lock = threading.Lock()
179 self.boilerPlate(lock, lock.locked)
180
181 def testWithRLock(self):
182 lock = threading.RLock()
183 self.boilerPlate(lock, lock._is_owned)
184
185 def testWithCondition(self):
186 lock = threading.Condition()
187 def locked():
188 return lock._is_owned()
189 self.boilerPlate(lock, locked)
190
191 def testWithSemaphore(self):
192 lock = threading.Semaphore()
193 def locked():
194 if lock.acquire(False):
195 lock.release()
196 return False
197 else:
198 return True
199 self.boilerPlate(lock, locked)
200
201 def testWithBoundedSemaphore(self):
202 lock = threading.BoundedSemaphore()
203 def locked():
204 if lock.acquire(False):
205 lock.release()
206 return False
207 else:
208 return True
209 self.boilerPlate(lock, locked)
210
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000211# This is needed to make the test actually run under regrtest.py!
212def test_main():
Raymond Hettingerc5b01952009-05-28 22:46:29 +0000213 with warnings.catch_warnings():
214 warnings.simplefilter('ignore')
215 support.run_unittest(__name__)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000216
Guido van Rossum1a5e21e2006-02-28 21:57:43 +0000217if __name__ == "__main__":
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000218 test_main()