blob: cd408cf145b4fc8021a143424d900b0eac8e5e26 [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):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000075 with support.catch_warning(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 Cannonec92e182008-09-02 02:46:59 +000082 with support.catch_warning(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000083 self.module.resetwarnings()
84 self.module.filterwarnings("ignore", category=UserWarning)
85 self.module.warn("FilterTests.test_ignore", UserWarning)
Brett Cannonec92e182008-09-02 02:46:59 +000086 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +000087
88 def test_always(self):
Brett Cannonec92e182008-09-02 02:46:59 +000089 with support.catch_warning(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000090 self.module.resetwarnings()
91 self.module.filterwarnings("always", category=UserWarning)
92 message = "FilterTests.test_always"
93 self.module.warn(message, UserWarning)
94 self.assert_(message, w.message)
Christian Heimes33fe8092008-04-13 13:53:33 +000095 self.module.warn(message, UserWarning)
96 self.assert_(w.message, message)
97
98 def test_default(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +000099 with support.catch_warning(self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000100 self.module.resetwarnings()
101 self.module.filterwarnings("default", category=UserWarning)
102 message = UserWarning("FilterTests.test_default")
103 for x in range(2):
104 self.module.warn(message, UserWarning)
105 if x == 0:
106 self.assertEquals(w.message, message)
107 w.reset()
108 elif x == 1:
Brett Cannonec92e182008-09-02 02:46:59 +0000109 self.assert_(not len(w), "unexpected warning: " + str(w))
Christian Heimes33fe8092008-04-13 13:53:33 +0000110 else:
111 raise ValueError("loop variant unhandled")
112
113 def test_module(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000114 with support.catch_warning(self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000115 self.module.resetwarnings()
116 self.module.filterwarnings("module", category=UserWarning)
117 message = UserWarning("FilterTests.test_module")
118 self.module.warn(message, UserWarning)
119 self.assertEquals(w.message, message)
120 w.reset()
121 self.module.warn(message, UserWarning)
Brett Cannonec92e182008-09-02 02:46:59 +0000122 self.assert_(not len(w), "unexpected message: " + str(w))
Christian Heimes33fe8092008-04-13 13:53:33 +0000123
124 def test_once(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000125 with support.catch_warning(self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000126 self.module.resetwarnings()
127 self.module.filterwarnings("once", category=UserWarning)
128 message = UserWarning("FilterTests.test_once")
129 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
130 42)
131 self.assertEquals(w.message, message)
132 w.reset()
133 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
134 13)
Brett Cannonec92e182008-09-02 02:46:59 +0000135 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000136 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
137 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000138 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000139
140 def test_inheritance(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000141 with support.catch_warning(self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000142 self.module.resetwarnings()
143 self.module.filterwarnings("error", category=Warning)
144 self.assertRaises(UserWarning, self.module.warn,
145 "FilterTests.test_inheritance", UserWarning)
146
147 def test_ordering(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000148 with support.catch_warning(self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000149 self.module.resetwarnings()
150 self.module.filterwarnings("ignore", category=UserWarning)
151 self.module.filterwarnings("error", category=UserWarning,
152 append=True)
153 w.reset()
154 try:
155 self.module.warn("FilterTests.test_ordering", UserWarning)
156 except UserWarning:
157 self.fail("order handling for actions failed")
Brett Cannonec92e182008-09-02 02:46:59 +0000158 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000159
160 def test_filterwarnings(self):
161 # Test filterwarnings().
162 # Implicitly also tests resetwarnings().
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000163 with support.catch_warning(self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000164 self.module.filterwarnings("error", "", Warning, "", 0)
165 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
166
167 self.module.resetwarnings()
168 text = 'handle normally'
169 self.module.warn(text)
170 self.assertEqual(str(w.message), text)
171 self.assert_(w.category is UserWarning)
172
173 self.module.filterwarnings("ignore", "", Warning, "", 0)
174 text = 'filtered out'
175 self.module.warn(text)
176 self.assertNotEqual(str(w.message), text)
177
178 self.module.resetwarnings()
179 self.module.filterwarnings("error", "hex*", Warning, "", 0)
180 self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
181 text = 'nonmatching text'
182 self.module.warn(text)
183 self.assertEqual(str(w.message), text)
184 self.assert_(w.category is UserWarning)
185
186class CFilterTests(BaseTest, FilterTests):
187 module = c_warnings
188
189class PyFilterTests(BaseTest, FilterTests):
190 module = py_warnings
191
192
193class WarnTests(unittest.TestCase):
194
195 """Test warnings.warn() and warnings.warn_explicit()."""
196
197 def test_message(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000198 with support.catch_warning(self.module) as w:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000199 for i in range(4):
Christian Heimes33fe8092008-04-13 13:53:33 +0000200 text = 'multi %d' %i # Different text on each call.
201 self.module.warn(text)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000202 self.assertEqual(str(w.message), text)
203 self.assert_(w.category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000204
Guido van Rossumd8faa362007-04-27 19:54:29 +0000205 def test_filename(self):
Christian Heimes33fe8092008-04-13 13:53:33 +0000206 with warnings_state(self.module):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000207 with support.catch_warning(self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000208 warning_tests.inner("spam1")
209 self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
210 warning_tests.outer("spam2")
211 self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000212
213 def test_stacklevel(self):
214 # Test stacklevel argument
215 # make sure all messages are different, so the warning won't be skipped
Christian Heimes33fe8092008-04-13 13:53:33 +0000216 with warnings_state(self.module):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000217 with support.catch_warning(self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000218 warning_tests.inner("spam3", stacklevel=1)
219 self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
220 warning_tests.outer("spam4", stacklevel=1)
221 self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000222
Christian Heimes33fe8092008-04-13 13:53:33 +0000223 warning_tests.inner("spam5", stacklevel=2)
224 self.assertEqual(os.path.basename(w.filename), "test_warnings.py")
225 warning_tests.outer("spam6", stacklevel=2)
226 self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
Christian Heimes5d8da202008-05-06 13:58:24 +0000227 warning_tests.outer("spam6.5", stacklevel=3)
228 self.assertEqual(os.path.basename(w.filename), "test_warnings.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000229
Christian Heimes33fe8092008-04-13 13:53:33 +0000230 warning_tests.inner("spam7", stacklevel=9999)
231 self.assertEqual(os.path.basename(w.filename), "sys")
232
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000233 def test_missing_filename_not_main(self):
234 # If __file__ is not specified and __main__ is not the module name,
235 # then __file__ should be set to the module name.
236 filename = warning_tests.__file__
237 try:
238 del warning_tests.__file__
239 with warnings_state(self.module):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000240 with support.catch_warning(self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000241 warning_tests.inner("spam8", stacklevel=1)
242 self.assertEqual(w.filename, warning_tests.__name__)
243 finally:
244 warning_tests.__file__ = filename
245
246 def test_missing_filename_main_with_argv(self):
247 # If __file__ is not specified and the caller is __main__ and sys.argv
248 # exists, then use sys.argv[0] as the file.
249 if not hasattr(sys, 'argv'):
250 return
251 filename = warning_tests.__file__
252 module_name = warning_tests.__name__
253 try:
254 del warning_tests.__file__
255 warning_tests.__name__ = '__main__'
256 with warnings_state(self.module):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000257 with support.catch_warning(self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000258 warning_tests.inner('spam9', stacklevel=1)
259 self.assertEqual(w.filename, sys.argv[0])
260 finally:
261 warning_tests.__file__ = filename
262 warning_tests.__name__ = module_name
263
264 def test_missing_filename_main_without_argv(self):
265 # If __file__ is not specified, the caller is __main__, and sys.argv
266 # is not set, then '__main__' is the file name.
267 filename = warning_tests.__file__
268 module_name = warning_tests.__name__
269 argv = sys.argv
270 try:
271 del warning_tests.__file__
272 warning_tests.__name__ = '__main__'
273 del sys.argv
274 with warnings_state(self.module):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000275 with support.catch_warning(self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000276 warning_tests.inner('spam10', stacklevel=1)
277 self.assertEqual(w.filename, '__main__')
278 finally:
279 warning_tests.__file__ = filename
280 warning_tests.__name__ = module_name
281 sys.argv = argv
282
Christian Heimesdaaf8ee2008-05-04 23:58:41 +0000283 def test_missing_filename_main_with_argv_empty_string(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000284 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
285 # is the empty string, then '__main__ is the file name.
286 # Tests issue 2743.
287 file_name = warning_tests.__file__
288 module_name = warning_tests.__name__
289 argv = sys.argv
290 try:
291 del warning_tests.__file__
292 warning_tests.__name__ = '__main__'
293 sys.argv = ['']
294 with warnings_state(self.module):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000295 with support.catch_warning(self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000296 warning_tests.inner('spam11', stacklevel=1)
297 self.assertEqual(w.filename, '__main__')
298 finally:
299 warning_tests.__file__ = file_name
300 warning_tests.__name__ = module_name
301 sys.argv = argv
302
Brett Cannondb734912008-06-27 00:52:15 +0000303 def test_warn_explicit_type_errors(self):
304 # warn_explicit() shoud error out gracefully if it is given objects
305 # of the wrong types.
306 # lineno is expected to be an integer.
307 self.assertRaises(TypeError, self.module.warn_explicit,
308 None, UserWarning, None, None)
309 # Either 'message' needs to be an instance of Warning or 'category'
310 # needs to be a subclass.
311 self.assertRaises(TypeError, self.module.warn_explicit,
312 None, None, None, 1)
313 # 'registry' must be a dict or None.
314 self.assertRaises((TypeError, AttributeError),
315 self.module.warn_explicit,
316 None, Warning, None, 1, registry=42)
317
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000318
Christian Heimes33fe8092008-04-13 13:53:33 +0000319class CWarnTests(BaseTest, WarnTests):
320 module = c_warnings
321
322class PyWarnTests(BaseTest, WarnTests):
323 module = py_warnings
324
325
326class WCmdLineTests(unittest.TestCase):
327
328 def test_improper_input(self):
329 # Uses the private _setoption() function to test the parsing
330 # of command-line warning arguments
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000331 with support.catch_warning(self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000332 self.assertRaises(self.module._OptionError,
333 self.module._setoption, '1:2:3:4:5:6')
334 self.assertRaises(self.module._OptionError,
335 self.module._setoption, 'bogus::Warning')
336 self.assertRaises(self.module._OptionError,
337 self.module._setoption, 'ignore:2::4:-5')
338 self.module._setoption('error::Warning::0')
339 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
340
341class CWCmdLineTests(BaseTest, WCmdLineTests):
342 module = c_warnings
343
344class PyWCmdLineTests(BaseTest, WCmdLineTests):
345 module = py_warnings
346
347
348class _WarningsTests(BaseTest):
349
350 """Tests specific to the _warnings module."""
351
352 module = c_warnings
353
354 def test_filter(self):
355 # Everything should function even if 'filters' is not in warnings.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000356 with support.catch_warning(self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000357 self.module.filterwarnings("error", "", Warning, "", 0)
358 self.assertRaises(UserWarning, self.module.warn,
359 'convert to error')
360 del self.module.filters
361 self.assertRaises(UserWarning, self.module.warn,
362 'convert to error')
363
364 def test_onceregistry(self):
365 # Replacing or removing the onceregistry should be okay.
366 global __warningregistry__
367 message = UserWarning('onceregistry test')
368 try:
369 original_registry = self.module.onceregistry
370 __warningregistry__ = {}
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000371 with support.catch_warning(self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000372 self.module.resetwarnings()
373 self.module.filterwarnings("once", category=UserWarning)
374 self.module.warn_explicit(message, UserWarning, "file", 42)
375 self.failUnlessEqual(w.message, message)
376 w.reset()
377 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000378 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000379 # Test the resetting of onceregistry.
380 self.module.onceregistry = {}
381 __warningregistry__ = {}
382 self.module.warn('onceregistry test')
383 self.failUnlessEqual(w.message.args, message.args)
384 # Removal of onceregistry is okay.
385 w.reset()
386 del self.module.onceregistry
387 __warningregistry__ = {}
388 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000389 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000390 finally:
391 self.module.onceregistry = original_registry
392
393 def test_showwarning_missing(self):
394 # Test that showwarning() missing is okay.
395 text = 'del showwarning test'
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000396 with support.catch_warning(self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000397 self.module.filterwarnings("always", category=UserWarning)
398 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000399 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000400 self.module.warn(text)
401 result = stream.getvalue()
402 self.failUnless(text in result)
403
Christian Heimes8dc226f2008-05-06 23:45:46 +0000404 def test_showwarning_not_callable(self):
405 self.module.filterwarnings("always", category=UserWarning)
406 old_showwarning = self.module.showwarning
407 self.module.showwarning = 23
408 try:
409 self.assertRaises(TypeError, self.module.warn, "Warning!")
410 finally:
411 self.module.showwarning = old_showwarning
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000412 self.module.resetwarnings()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000413
Christian Heimes33fe8092008-04-13 13:53:33 +0000414 def test_show_warning_output(self):
415 # With showarning() missing, make sure that output is okay.
416 text = 'test show_warning'
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000417 with support.catch_warning(self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000418 self.module.filterwarnings("always", category=UserWarning)
419 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000420 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000421 warning_tests.inner(text)
422 result = stream.getvalue()
423 self.failUnlessEqual(result.count('\n'), 2,
424 "Too many newlines in %r" % result)
425 first_line, second_line = result.split('\n', 1)
426 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Neal Norwitz32dde222008-04-15 06:43:13 +0000427 first_line_parts = first_line.rsplit(':', 3)
428 path, line, warning_class, message = first_line_parts
Christian Heimes33fe8092008-04-13 13:53:33 +0000429 line = int(line)
430 self.failUnlessEqual(expected_file, path)
431 self.failUnlessEqual(warning_class, ' ' + UserWarning.__name__)
432 self.failUnlessEqual(message, ' ' + text)
433 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
434 assert expected_line
435 self.failUnlessEqual(second_line, expected_line)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000436
437
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000438class WarningsDisplayTests(unittest.TestCase):
439
Christian Heimes33fe8092008-04-13 13:53:33 +0000440 """Test the displaying of warnings and the ability to overload functions
441 related to displaying warnings."""
442
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000443 def test_formatwarning(self):
444 message = "msg"
445 category = Warning
446 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
447 line_num = 3
448 file_line = linecache.getline(file_name, line_num).strip()
Christian Heimes33fe8092008-04-13 13:53:33 +0000449 format = "%s:%s: %s: %s\n %s\n"
450 expect = format % (file_name, line_num, category.__name__, message,
451 file_line)
452 self.failUnlessEqual(expect, self.module.formatwarning(message,
453 category, file_name, line_num))
454 # Test the 'line' argument.
455 file_line += " for the win!"
456 expect = format % (file_name, line_num, category.__name__, message,
457 file_line)
458 self.failUnlessEqual(expect, self.module.formatwarning(message,
459 category, file_name, line_num, file_line))
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000460
461 def test_showwarning(self):
462 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
463 line_num = 3
464 expected_file_line = linecache.getline(file_name, line_num).strip()
465 message = 'msg'
466 category = Warning
467 file_object = StringIO()
Christian Heimes33fe8092008-04-13 13:53:33 +0000468 expect = self.module.formatwarning(message, category, file_name,
469 line_num)
470 self.module.showwarning(message, category, file_name, line_num,
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000471 file_object)
472 self.failUnlessEqual(file_object.getvalue(), expect)
Christian Heimes33fe8092008-04-13 13:53:33 +0000473 # Test 'line' argument.
474 expected_file_line += "for the win!"
475 expect = self.module.formatwarning(message, category, file_name,
476 line_num, expected_file_line)
477 file_object = StringIO()
478 self.module.showwarning(message, category, file_name, line_num,
479 file_object, expected_file_line)
480 self.failUnlessEqual(expect, file_object.getvalue())
481
482class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
483 module = c_warnings
484
485class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
486 module = py_warnings
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000487
Brett Cannonec92e182008-09-02 02:46:59 +0000488class CatchWarningTests(BaseTest):
Nick Coghlanb1304932008-07-13 12:25:08 +0000489
Brett Cannonec92e182008-09-02 02:46:59 +0000490 """Test catch_warnings()."""
491
492 def test_catch_warnings_restore(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000493 wmod = self.module
494 orig_filters = wmod.filters
495 orig_showwarning = wmod.showwarning
Brett Cannonec92e182008-09-02 02:46:59 +0000496 with support.catch_warning(module=wmod):
Nick Coghlanb1304932008-07-13 12:25:08 +0000497 wmod.filters = wmod.showwarning = object()
498 self.assert_(wmod.filters is orig_filters)
499 self.assert_(wmod.showwarning is orig_showwarning)
Brett Cannonec92e182008-09-02 02:46:59 +0000500 with support.catch_warning(module=wmod, record=False):
Nick Coghlanb1304932008-07-13 12:25:08 +0000501 wmod.filters = wmod.showwarning = object()
502 self.assert_(wmod.filters is orig_filters)
503 self.assert_(wmod.showwarning is orig_showwarning)
504
Brett Cannonec92e182008-09-02 02:46:59 +0000505 def test_catch_warnings_recording(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000506 wmod = self.module
Brett Cannonec92e182008-09-02 02:46:59 +0000507 with support.catch_warning(module=wmod) as w:
508 self.assertEqual(w, [])
Nick Coghlanb1304932008-07-13 12:25:08 +0000509 wmod.simplefilter("always")
510 wmod.warn("foo")
511 self.assertEqual(str(w.message), "foo")
512 wmod.warn("bar")
513 self.assertEqual(str(w.message), "bar")
Brett Cannonec92e182008-09-02 02:46:59 +0000514 self.assertEqual(str(w[0].message), "foo")
515 self.assertEqual(str(w[1].message), "bar")
Nick Coghlanb1304932008-07-13 12:25:08 +0000516 w.reset()
Brett Cannonec92e182008-09-02 02:46:59 +0000517 self.assertEqual(w, [])
Nick Coghlanb1304932008-07-13 12:25:08 +0000518 orig_showwarning = wmod.showwarning
Brett Cannonec92e182008-09-02 02:46:59 +0000519 with support.catch_warning(module=wmod, record=False) as w:
Nick Coghlanb1304932008-07-13 12:25:08 +0000520 self.assert_(w is None)
521 self.assert_(wmod.showwarning is orig_showwarning)
522
Brett Cannonec92e182008-09-02 02:46:59 +0000523class CCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000524 module = c_warnings
525
Brett Cannonec92e182008-09-02 02:46:59 +0000526class PyCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000527 module = py_warnings
528
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000529
Christian Heimes33fe8092008-04-13 13:53:33 +0000530def test_main():
Christian Heimesdae2a892008-04-19 00:55:37 +0000531 py_warnings.onceregistry.clear()
532 c_warnings.onceregistry.clear()
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000533 support.run_unittest(CFilterTests,
Christian Heimes33fe8092008-04-13 13:53:33 +0000534 PyFilterTests,
535 CWarnTests,
536 PyWarnTests,
537 CWCmdLineTests, PyWCmdLineTests,
538 _WarningsTests,
539 CWarningsDisplayTests, PyWarningsDisplayTests,
Brett Cannonec92e182008-09-02 02:46:59 +0000540 CCatchWarningTests, PyCatchWarningTests,
Christian Heimes33fe8092008-04-13 13:53:33 +0000541 )
542
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000543
544if __name__ == "__main__":
Christian Heimes33fe8092008-04-13 13:53:33 +0000545 test_main()