blob: 49f3d3a7b776c1f15c8b158c9c9f566ba268ae6b [file] [log] [blame]
Christian Heimes33fe8092008-04-13 13:53:33 +00001from contextlib import contextmanager
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00002import linecache
Raymond Hettingerdc9dcf12003-07-13 06:15:11 +00003import os
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00004from io import StringIO
Guido van Rossum61e21b52007-08-20 19:06:03 +00005import sys
Raymond Hettingerd6f6e502003-07-13 08:37:40 +00006import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00007from test import support
Jeremy Hylton85014662003-07-11 15:37:59 +00008
Guido van Rossum805365e2007-05-07 22:24:25 +00009from test import warning_tests
Jeremy Hylton85014662003-07-11 15:37:59 +000010
Christian Heimes33fe8092008-04-13 13:53:33 +000011import warnings as original_warnings
Jeremy Hylton85014662003-07-11 15:37:59 +000012
Christian Heimes33fe8092008-04-13 13:53:33 +000013sys.modules['_warnings'] = 0
14del sys.modules['warnings']
15
16import warnings as py_warnings
17
18del sys.modules['_warnings']
19del sys.modules['warnings']
20
21import warnings as c_warnings
22
23sys.modules['warnings'] = original_warnings
24
25
26@contextmanager
27def warnings_state(module):
28 """Use a specific warnings implementation in warning_tests."""
29 global __warningregistry__
30 for to_clear in (sys, warning_tests):
31 try:
32 to_clear.__warningregistry__.clear()
33 except AttributeError:
34 pass
35 try:
36 __warningregistry__.clear()
37 except NameError:
38 pass
39 original_warnings = warning_tests.warnings
40 try:
41 warning_tests.warnings = module
42 yield
43 finally:
44 warning_tests.warnings = original_warnings
45
46
47class BaseTest(unittest.TestCase):
48
49 """Basic bookkeeping required for testing."""
50
51 def setUp(self):
52 # The __warningregistry__ needs to be in a pristine state for tests
53 # to work properly.
54 if '__warningregistry__' in globals():
55 del globals()['__warningregistry__']
56 if hasattr(warning_tests, '__warningregistry__'):
57 del warning_tests.__warningregistry__
58 if hasattr(sys, '__warningregistry__'):
59 del sys.__warningregistry__
60 # The 'warnings' module must be explicitly set so that the proper
61 # interaction between _warnings and 'warnings' can be controlled.
62 sys.modules['warnings'] = self.module
63 super(BaseTest, self).setUp()
64
65 def tearDown(self):
66 sys.modules['warnings'] = original_warnings
67 super(BaseTest, self).tearDown()
68
69
70class FilterTests(object):
71
72 """Testing the filtering functionality."""
73
74 def test_error(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000075 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000076 self.module.resetwarnings()
77 self.module.filterwarnings("error", category=UserWarning)
78 self.assertRaises(UserWarning, self.module.warn,
79 "FilterTests.test_error")
80
81 def test_ignore(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000082 with original_warnings.catch_warnings(record=True,
83 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000084 self.module.resetwarnings()
85 self.module.filterwarnings("ignore", category=UserWarning)
86 self.module.warn("FilterTests.test_ignore", UserWarning)
Brett Cannonec92e182008-09-02 02:46:59 +000087 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +000088
89 def test_always(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000090 with original_warnings.catch_warnings(record=True,
91 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000092 self.module.resetwarnings()
93 self.module.filterwarnings("always", category=UserWarning)
94 message = "FilterTests.test_always"
95 self.module.warn(message, UserWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +000096 self.assert_(message, w[-1].message)
Christian Heimes33fe8092008-04-13 13:53:33 +000097 self.module.warn(message, UserWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +000098 self.assert_(w[-1].message, message)
Christian Heimes33fe8092008-04-13 13:53:33 +000099
100 def test_default(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000101 with original_warnings.catch_warnings(record=True,
102 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000103 self.module.resetwarnings()
104 self.module.filterwarnings("default", category=UserWarning)
105 message = UserWarning("FilterTests.test_default")
106 for x in range(2):
107 self.module.warn(message, UserWarning)
108 if x == 0:
Brett Cannon1cd02472008-09-09 01:52:27 +0000109 self.assertEquals(w[-1].message, message)
110 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000111 elif x == 1:
Brett Cannon1cd02472008-09-09 01:52:27 +0000112 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000113 else:
114 raise ValueError("loop variant unhandled")
115
116 def test_module(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000117 with original_warnings.catch_warnings(record=True,
118 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000119 self.module.resetwarnings()
120 self.module.filterwarnings("module", category=UserWarning)
121 message = UserWarning("FilterTests.test_module")
122 self.module.warn(message, UserWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +0000123 self.assertEquals(w[-1].message, message)
124 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000125 self.module.warn(message, UserWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +0000126 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000127
128 def test_once(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000129 with original_warnings.catch_warnings(record=True,
130 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000131 self.module.resetwarnings()
132 self.module.filterwarnings("once", category=UserWarning)
133 message = UserWarning("FilterTests.test_once")
134 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
135 42)
Brett Cannon1cd02472008-09-09 01:52:27 +0000136 self.assertEquals(w[-1].message, message)
137 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000138 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
139 13)
Brett Cannonec92e182008-09-02 02:46:59 +0000140 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000141 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
142 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000143 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000144
145 def test_inheritance(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000146 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000147 self.module.resetwarnings()
148 self.module.filterwarnings("error", category=Warning)
149 self.assertRaises(UserWarning, self.module.warn,
150 "FilterTests.test_inheritance", UserWarning)
151
152 def test_ordering(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000153 with original_warnings.catch_warnings(record=True,
154 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000155 self.module.resetwarnings()
156 self.module.filterwarnings("ignore", category=UserWarning)
157 self.module.filterwarnings("error", category=UserWarning,
158 append=True)
Brett Cannon1cd02472008-09-09 01:52:27 +0000159 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000160 try:
161 self.module.warn("FilterTests.test_ordering", UserWarning)
162 except UserWarning:
163 self.fail("order handling for actions failed")
Brett Cannonec92e182008-09-02 02:46:59 +0000164 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000165
166 def test_filterwarnings(self):
167 # Test filterwarnings().
168 # Implicitly also tests resetwarnings().
Brett Cannon1cd02472008-09-09 01:52:27 +0000169 with original_warnings.catch_warnings(record=True,
170 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000171 self.module.filterwarnings("error", "", Warning, "", 0)
172 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
173
174 self.module.resetwarnings()
175 text = 'handle normally'
176 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000177 self.assertEqual(str(w[-1].message), text)
178 self.assert_(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000179
180 self.module.filterwarnings("ignore", "", Warning, "", 0)
181 text = 'filtered out'
182 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000183 self.assertNotEqual(str(w[-1].message), text)
Christian Heimes33fe8092008-04-13 13:53:33 +0000184
185 self.module.resetwarnings()
186 self.module.filterwarnings("error", "hex*", Warning, "", 0)
187 self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
188 text = 'nonmatching text'
189 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000190 self.assertEqual(str(w[-1].message), text)
191 self.assert_(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000192
193class CFilterTests(BaseTest, FilterTests):
194 module = c_warnings
195
196class PyFilterTests(BaseTest, FilterTests):
197 module = py_warnings
198
199
200class WarnTests(unittest.TestCase):
201
202 """Test warnings.warn() and warnings.warn_explicit()."""
203
204 def test_message(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000205 with original_warnings.catch_warnings(record=True,
206 module=self.module) as w:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000207 for i in range(4):
Christian Heimes33fe8092008-04-13 13:53:33 +0000208 text = 'multi %d' %i # Different text on each call.
209 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000210 self.assertEqual(str(w[-1].message), text)
211 self.assert_(w[-1].category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000212
Brett Cannon54bd41d2008-09-02 04:01:42 +0000213 # Issue 3639
214 def test_warn_nonstandard_types(self):
215 # warn() should handle non-standard types without issue.
216 for ob in (Warning, None, 42):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000217 with original_warnings.catch_warnings(record=True,
218 module=self.module) as w:
Brett Cannon54bd41d2008-09-02 04:01:42 +0000219 self.module.warn(ob)
220 # Don't directly compare objects since
221 # ``Warning() != Warning()``.
Brett Cannon1cd02472008-09-09 01:52:27 +0000222 self.assertEquals(str(w[-1].message), str(UserWarning(ob)))
Brett Cannon54bd41d2008-09-02 04:01:42 +0000223
Guido van Rossumd8faa362007-04-27 19:54:29 +0000224 def test_filename(self):
Christian Heimes33fe8092008-04-13 13:53:33 +0000225 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000226 with original_warnings.catch_warnings(record=True,
227 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000228 warning_tests.inner("spam1")
Brett Cannon1cd02472008-09-09 01:52:27 +0000229 self.assertEqual(os.path.basename(w[-1].filename),
230 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000231 warning_tests.outer("spam2")
Brett Cannon1cd02472008-09-09 01:52:27 +0000232 self.assertEqual(os.path.basename(w[-1].filename),
233 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000234
235 def test_stacklevel(self):
236 # Test stacklevel argument
237 # make sure all messages are different, so the warning won't be skipped
Christian Heimes33fe8092008-04-13 13:53:33 +0000238 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000239 with original_warnings.catch_warnings(record=True,
240 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000241 warning_tests.inner("spam3", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000242 self.assertEqual(os.path.basename(w[-1].filename),
243 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000244 warning_tests.outer("spam4", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000245 self.assertEqual(os.path.basename(w[-1].filename),
246 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000247
Christian Heimes33fe8092008-04-13 13:53:33 +0000248 warning_tests.inner("spam5", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000249 self.assertEqual(os.path.basename(w[-1].filename),
250 "test_warnings.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000251 warning_tests.outer("spam6", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000252 self.assertEqual(os.path.basename(w[-1].filename),
253 "warning_tests.py")
Christian Heimes5d8da202008-05-06 13:58:24 +0000254 warning_tests.outer("spam6.5", stacklevel=3)
Brett Cannon1cd02472008-09-09 01:52:27 +0000255 self.assertEqual(os.path.basename(w[-1].filename),
256 "test_warnings.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000257
Christian Heimes33fe8092008-04-13 13:53:33 +0000258 warning_tests.inner("spam7", stacklevel=9999)
Brett Cannon1cd02472008-09-09 01:52:27 +0000259 self.assertEqual(os.path.basename(w[-1].filename),
260 "sys")
Christian Heimes33fe8092008-04-13 13:53:33 +0000261
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000262 def test_missing_filename_not_main(self):
263 # If __file__ is not specified and __main__ is not the module name,
264 # then __file__ should be set to the module name.
265 filename = warning_tests.__file__
266 try:
267 del warning_tests.__file__
268 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000269 with original_warnings.catch_warnings(record=True,
270 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000271 warning_tests.inner("spam8", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000272 self.assertEqual(w[-1].filename, warning_tests.__name__)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000273 finally:
274 warning_tests.__file__ = filename
275
276 def test_missing_filename_main_with_argv(self):
277 # If __file__ is not specified and the caller is __main__ and sys.argv
278 # exists, then use sys.argv[0] as the file.
279 if not hasattr(sys, 'argv'):
280 return
281 filename = warning_tests.__file__
282 module_name = warning_tests.__name__
283 try:
284 del warning_tests.__file__
285 warning_tests.__name__ = '__main__'
286 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000287 with original_warnings.catch_warnings(record=True,
288 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000289 warning_tests.inner('spam9', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000290 self.assertEqual(w[-1].filename, sys.argv[0])
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000291 finally:
292 warning_tests.__file__ = filename
293 warning_tests.__name__ = module_name
294
295 def test_missing_filename_main_without_argv(self):
296 # If __file__ is not specified, the caller is __main__, and sys.argv
297 # is not set, then '__main__' is the file name.
298 filename = warning_tests.__file__
299 module_name = warning_tests.__name__
300 argv = sys.argv
301 try:
302 del warning_tests.__file__
303 warning_tests.__name__ = '__main__'
304 del sys.argv
305 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000306 with original_warnings.catch_warnings(record=True,
307 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000308 warning_tests.inner('spam10', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000309 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000310 finally:
311 warning_tests.__file__ = filename
312 warning_tests.__name__ = module_name
313 sys.argv = argv
314
Christian Heimesdaaf8ee2008-05-04 23:58:41 +0000315 def test_missing_filename_main_with_argv_empty_string(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000316 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
317 # is the empty string, then '__main__ is the file name.
318 # Tests issue 2743.
319 file_name = warning_tests.__file__
320 module_name = warning_tests.__name__
321 argv = sys.argv
322 try:
323 del warning_tests.__file__
324 warning_tests.__name__ = '__main__'
325 sys.argv = ['']
326 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000327 with original_warnings.catch_warnings(record=True,
328 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000329 warning_tests.inner('spam11', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000330 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000331 finally:
332 warning_tests.__file__ = file_name
333 warning_tests.__name__ = module_name
334 sys.argv = argv
335
Brett Cannondb734912008-06-27 00:52:15 +0000336 def test_warn_explicit_type_errors(self):
337 # warn_explicit() shoud error out gracefully if it is given objects
338 # of the wrong types.
339 # lineno is expected to be an integer.
340 self.assertRaises(TypeError, self.module.warn_explicit,
341 None, UserWarning, None, None)
342 # Either 'message' needs to be an instance of Warning or 'category'
343 # needs to be a subclass.
344 self.assertRaises(TypeError, self.module.warn_explicit,
345 None, None, None, 1)
346 # 'registry' must be a dict or None.
347 self.assertRaises((TypeError, AttributeError),
348 self.module.warn_explicit,
349 None, Warning, None, 1, registry=42)
350
Christian Heimes33fe8092008-04-13 13:53:33 +0000351class CWarnTests(BaseTest, WarnTests):
352 module = c_warnings
353
354class PyWarnTests(BaseTest, WarnTests):
355 module = py_warnings
356
357
358class WCmdLineTests(unittest.TestCase):
359
360 def test_improper_input(self):
361 # Uses the private _setoption() function to test the parsing
362 # of command-line warning arguments
Brett Cannon1cd02472008-09-09 01:52:27 +0000363 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000364 self.assertRaises(self.module._OptionError,
365 self.module._setoption, '1:2:3:4:5:6')
366 self.assertRaises(self.module._OptionError,
367 self.module._setoption, 'bogus::Warning')
368 self.assertRaises(self.module._OptionError,
369 self.module._setoption, 'ignore:2::4:-5')
370 self.module._setoption('error::Warning::0')
371 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
372
373class CWCmdLineTests(BaseTest, WCmdLineTests):
374 module = c_warnings
375
376class PyWCmdLineTests(BaseTest, WCmdLineTests):
377 module = py_warnings
378
379
380class _WarningsTests(BaseTest):
381
382 """Tests specific to the _warnings module."""
383
384 module = c_warnings
385
386 def test_filter(self):
387 # Everything should function even if 'filters' is not in warnings.
Brett Cannon1cd02472008-09-09 01:52:27 +0000388 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000389 self.module.filterwarnings("error", "", Warning, "", 0)
390 self.assertRaises(UserWarning, self.module.warn,
391 'convert to error')
392 del self.module.filters
393 self.assertRaises(UserWarning, self.module.warn,
394 'convert to error')
395
396 def test_onceregistry(self):
397 # Replacing or removing the onceregistry should be okay.
398 global __warningregistry__
399 message = UserWarning('onceregistry test')
400 try:
401 original_registry = self.module.onceregistry
402 __warningregistry__ = {}
Brett Cannon1cd02472008-09-09 01:52:27 +0000403 with original_warnings.catch_warnings(record=True,
404 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000405 self.module.resetwarnings()
406 self.module.filterwarnings("once", category=UserWarning)
407 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannon1cd02472008-09-09 01:52:27 +0000408 self.failUnlessEqual(w[-1].message, message)
409 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000410 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000411 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000412 # Test the resetting of onceregistry.
413 self.module.onceregistry = {}
414 __warningregistry__ = {}
415 self.module.warn('onceregistry test')
Brett Cannon1cd02472008-09-09 01:52:27 +0000416 self.failUnlessEqual(w[-1].message.args, message.args)
Christian Heimes33fe8092008-04-13 13:53:33 +0000417 # Removal of onceregistry is okay.
Brett Cannon1cd02472008-09-09 01:52:27 +0000418 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000419 del self.module.onceregistry
420 __warningregistry__ = {}
421 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000422 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000423 finally:
424 self.module.onceregistry = original_registry
425
Brett Cannon0759dd62009-04-01 18:13:07 +0000426 def test_default_action(self):
427 # Replacing or removing defaultaction should be okay.
428 message = UserWarning("defaultaction test")
429 original = self.module.defaultaction
430 try:
431 with original_warnings.catch_warnings(record=True,
432 module=self.module) as w:
433 self.module.resetwarnings()
434 registry = {}
435 self.module.warn_explicit(message, UserWarning, "<test>", 42,
436 registry=registry)
437 self.assertEqual(w[-1].message, message)
438 self.assertEqual(len(w), 1)
439 self.assertEqual(len(registry), 1)
440 del w[:]
441 # Test removal.
442 del self.module.defaultaction
443 __warningregistry__ = {}
444 registry = {}
445 self.module.warn_explicit(message, UserWarning, "<test>", 43,
446 registry=registry)
447 self.assertEqual(w[-1].message, message)
448 self.assertEqual(len(w), 1)
449 self.assertEqual(len(registry), 1)
450 del w[:]
451 # Test setting.
452 self.module.defaultaction = "ignore"
453 __warningregistry__ = {}
454 registry = {}
455 self.module.warn_explicit(message, UserWarning, "<test>", 44,
456 registry=registry)
457 self.assertEqual(len(w), 0)
458 finally:
459 self.module.defaultaction = original
460
Christian Heimes33fe8092008-04-13 13:53:33 +0000461 def test_showwarning_missing(self):
462 # Test that showwarning() missing is okay.
463 text = 'del showwarning test'
Brett Cannon1cd02472008-09-09 01:52:27 +0000464 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000465 self.module.filterwarnings("always", category=UserWarning)
466 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000467 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000468 self.module.warn(text)
469 result = stream.getvalue()
470 self.failUnless(text in result)
471
Christian Heimes8dc226f2008-05-06 23:45:46 +0000472 def test_showwarning_not_callable(self):
473 self.module.filterwarnings("always", category=UserWarning)
474 old_showwarning = self.module.showwarning
475 self.module.showwarning = 23
476 try:
477 self.assertRaises(TypeError, self.module.warn, "Warning!")
478 finally:
479 self.module.showwarning = old_showwarning
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000480 self.module.resetwarnings()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000481
Christian Heimes33fe8092008-04-13 13:53:33 +0000482 def test_show_warning_output(self):
483 # With showarning() missing, make sure that output is okay.
484 text = 'test show_warning'
Brett Cannon1cd02472008-09-09 01:52:27 +0000485 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000486 self.module.filterwarnings("always", category=UserWarning)
487 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000488 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000489 warning_tests.inner(text)
490 result = stream.getvalue()
491 self.failUnlessEqual(result.count('\n'), 2,
492 "Too many newlines in %r" % result)
493 first_line, second_line = result.split('\n', 1)
494 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Neal Norwitz32dde222008-04-15 06:43:13 +0000495 first_line_parts = first_line.rsplit(':', 3)
496 path, line, warning_class, message = first_line_parts
Christian Heimes33fe8092008-04-13 13:53:33 +0000497 line = int(line)
498 self.failUnlessEqual(expected_file, path)
499 self.failUnlessEqual(warning_class, ' ' + UserWarning.__name__)
500 self.failUnlessEqual(message, ' ' + text)
501 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
502 assert expected_line
503 self.failUnlessEqual(second_line, expected_line)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000504
505
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000506class WarningsDisplayTests(unittest.TestCase):
507
Christian Heimes33fe8092008-04-13 13:53:33 +0000508 """Test the displaying of warnings and the ability to overload functions
509 related to displaying warnings."""
510
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000511 def test_formatwarning(self):
512 message = "msg"
513 category = Warning
514 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
515 line_num = 3
516 file_line = linecache.getline(file_name, line_num).strip()
Christian Heimes33fe8092008-04-13 13:53:33 +0000517 format = "%s:%s: %s: %s\n %s\n"
518 expect = format % (file_name, line_num, category.__name__, message,
519 file_line)
520 self.failUnlessEqual(expect, self.module.formatwarning(message,
521 category, file_name, line_num))
522 # Test the 'line' argument.
523 file_line += " for the win!"
524 expect = format % (file_name, line_num, category.__name__, message,
525 file_line)
526 self.failUnlessEqual(expect, self.module.formatwarning(message,
527 category, file_name, line_num, file_line))
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000528
529 def test_showwarning(self):
530 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
531 line_num = 3
532 expected_file_line = linecache.getline(file_name, line_num).strip()
533 message = 'msg'
534 category = Warning
535 file_object = StringIO()
Christian Heimes33fe8092008-04-13 13:53:33 +0000536 expect = self.module.formatwarning(message, category, file_name,
537 line_num)
538 self.module.showwarning(message, category, file_name, line_num,
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000539 file_object)
540 self.failUnlessEqual(file_object.getvalue(), expect)
Christian Heimes33fe8092008-04-13 13:53:33 +0000541 # Test 'line' argument.
542 expected_file_line += "for the win!"
543 expect = self.module.formatwarning(message, category, file_name,
544 line_num, expected_file_line)
545 file_object = StringIO()
546 self.module.showwarning(message, category, file_name, line_num,
547 file_object, expected_file_line)
548 self.failUnlessEqual(expect, file_object.getvalue())
549
550class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
551 module = c_warnings
552
553class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
554 module = py_warnings
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000555
Brett Cannon1cd02472008-09-09 01:52:27 +0000556
Brett Cannonec92e182008-09-02 02:46:59 +0000557class CatchWarningTests(BaseTest):
Nick Coghlanb1304932008-07-13 12:25:08 +0000558
Brett Cannonec92e182008-09-02 02:46:59 +0000559 """Test catch_warnings()."""
560
561 def test_catch_warnings_restore(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000562 wmod = self.module
563 orig_filters = wmod.filters
564 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000565 # Ensure both showwarning and filters are restored when recording
566 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlanb1304932008-07-13 12:25:08 +0000567 wmod.filters = wmod.showwarning = object()
568 self.assert_(wmod.filters is orig_filters)
569 self.assert_(wmod.showwarning is orig_showwarning)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000570 # Same test, but with recording disabled
571 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlanb1304932008-07-13 12:25:08 +0000572 wmod.filters = wmod.showwarning = object()
573 self.assert_(wmod.filters is orig_filters)
574 self.assert_(wmod.showwarning is orig_showwarning)
575
Brett Cannonec92e182008-09-02 02:46:59 +0000576 def test_catch_warnings_recording(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000577 wmod = self.module
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000578 # Ensure warnings are recorded when requested
579 with wmod.catch_warnings(module=wmod, record=True) as w:
Brett Cannonec92e182008-09-02 02:46:59 +0000580 self.assertEqual(w, [])
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000581 self.assert_(type(w) is list)
Nick Coghlanb1304932008-07-13 12:25:08 +0000582 wmod.simplefilter("always")
583 wmod.warn("foo")
Brett Cannon1cd02472008-09-09 01:52:27 +0000584 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlanb1304932008-07-13 12:25:08 +0000585 wmod.warn("bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000586 self.assertEqual(str(w[-1].message), "bar")
Brett Cannonec92e182008-09-02 02:46:59 +0000587 self.assertEqual(str(w[0].message), "foo")
588 self.assertEqual(str(w[1].message), "bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000589 del w[:]
Brett Cannonec92e182008-09-02 02:46:59 +0000590 self.assertEqual(w, [])
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000591 # Ensure warnings are not recorded when not requested
Nick Coghlanb1304932008-07-13 12:25:08 +0000592 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000593 with wmod.catch_warnings(module=wmod, record=False) as w:
Nick Coghlanb1304932008-07-13 12:25:08 +0000594 self.assert_(w is None)
595 self.assert_(wmod.showwarning is orig_showwarning)
596
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000597 def test_catch_warnings_reentry_guard(self):
598 wmod = self.module
599 # Ensure catch_warnings is protected against incorrect usage
600 x = wmod.catch_warnings(module=wmod, record=True)
601 self.assertRaises(RuntimeError, x.__exit__)
602 with x:
603 self.assertRaises(RuntimeError, x.__enter__)
604 # Same test, but with recording disabled
605 x = wmod.catch_warnings(module=wmod, record=False)
606 self.assertRaises(RuntimeError, x.__exit__)
607 with x:
608 self.assertRaises(RuntimeError, x.__enter__)
609
610 def test_catch_warnings_defaults(self):
611 wmod = self.module
612 orig_filters = wmod.filters
613 orig_showwarning = wmod.showwarning
614 # Ensure default behaviour is not to record warnings
615 with wmod.catch_warnings(module=wmod) as w:
616 self.assert_(w is None)
617 self.assert_(wmod.showwarning is orig_showwarning)
618 self.assert_(wmod.filters is not orig_filters)
619 self.assert_(wmod.filters is orig_filters)
620 if wmod is sys.modules['warnings']:
621 # Ensure the default module is this one
622 with wmod.catch_warnings() as w:
623 self.assert_(w is None)
624 self.assert_(wmod.showwarning is orig_showwarning)
625 self.assert_(wmod.filters is not orig_filters)
626 self.assert_(wmod.filters is orig_filters)
627
628 def test_check_warnings(self):
629 # Explicit tests for the test.support convenience wrapper
630 wmod = self.module
631 if wmod is sys.modules['warnings']:
632 with support.check_warnings() as w:
633 self.assertEqual(w.warnings, [])
634 wmod.simplefilter("always")
635 wmod.warn("foo")
636 self.assertEqual(str(w.message), "foo")
637 wmod.warn("bar")
638 self.assertEqual(str(w.message), "bar")
639 self.assertEqual(str(w.warnings[0].message), "foo")
640 self.assertEqual(str(w.warnings[1].message), "bar")
641 w.reset()
642 self.assertEqual(w.warnings, [])
643
Brett Cannonec92e182008-09-02 02:46:59 +0000644class CCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000645 module = c_warnings
646
Brett Cannonec92e182008-09-02 02:46:59 +0000647class PyCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000648 module = py_warnings
649
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000650
Christian Heimes33fe8092008-04-13 13:53:33 +0000651def test_main():
Christian Heimesdae2a892008-04-19 00:55:37 +0000652 py_warnings.onceregistry.clear()
653 c_warnings.onceregistry.clear()
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000654 support.run_unittest(CFilterTests,
Christian Heimes33fe8092008-04-13 13:53:33 +0000655 PyFilterTests,
656 CWarnTests,
657 PyWarnTests,
658 CWCmdLineTests, PyWCmdLineTests,
659 _WarningsTests,
660 CWarningsDisplayTests, PyWarningsDisplayTests,
Brett Cannonec92e182008-09-02 02:46:59 +0000661 CCatchWarningTests, PyCatchWarningTests,
Christian Heimes33fe8092008-04-13 13:53:33 +0000662 )
663
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000664
665if __name__ == "__main__":
Christian Heimes33fe8092008-04-13 13:53:33 +0000666 test_main()