blob: 087bf3d871aa623f84f7d5aa8f474aa676bd0c3b [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
Brett Cannon54bd41d2008-09-02 04:01:42 +0000205 # Issue 3639
206 def test_warn_nonstandard_types(self):
207 # warn() should handle non-standard types without issue.
208 for ob in (Warning, None, 42):
209 with support.catch_warning(self.module) as w:
210 self.module.warn(ob)
211 # Don't directly compare objects since
212 # ``Warning() != Warning()``.
213 self.assertEquals(str(w.message), str(UserWarning(ob)))
214
Guido van Rossumd8faa362007-04-27 19:54:29 +0000215 def test_filename(self):
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("spam1")
219 self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
220 warning_tests.outer("spam2")
221 self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000222
223 def test_stacklevel(self):
224 # Test stacklevel argument
225 # make sure all messages are different, so the warning won't be skipped
Christian Heimes33fe8092008-04-13 13:53:33 +0000226 with warnings_state(self.module):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000227 with support.catch_warning(self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000228 warning_tests.inner("spam3", stacklevel=1)
229 self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
230 warning_tests.outer("spam4", stacklevel=1)
231 self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000232
Christian Heimes33fe8092008-04-13 13:53:33 +0000233 warning_tests.inner("spam5", stacklevel=2)
234 self.assertEqual(os.path.basename(w.filename), "test_warnings.py")
235 warning_tests.outer("spam6", stacklevel=2)
236 self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
Christian Heimes5d8da202008-05-06 13:58:24 +0000237 warning_tests.outer("spam6.5", stacklevel=3)
238 self.assertEqual(os.path.basename(w.filename), "test_warnings.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000239
Christian Heimes33fe8092008-04-13 13:53:33 +0000240 warning_tests.inner("spam7", stacklevel=9999)
241 self.assertEqual(os.path.basename(w.filename), "sys")
242
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000243 def test_missing_filename_not_main(self):
244 # If __file__ is not specified and __main__ is not the module name,
245 # then __file__ should be set to the module name.
246 filename = warning_tests.__file__
247 try:
248 del warning_tests.__file__
249 with warnings_state(self.module):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000250 with support.catch_warning(self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000251 warning_tests.inner("spam8", stacklevel=1)
252 self.assertEqual(w.filename, warning_tests.__name__)
253 finally:
254 warning_tests.__file__ = filename
255
256 def test_missing_filename_main_with_argv(self):
257 # If __file__ is not specified and the caller is __main__ and sys.argv
258 # exists, then use sys.argv[0] as the file.
259 if not hasattr(sys, 'argv'):
260 return
261 filename = warning_tests.__file__
262 module_name = warning_tests.__name__
263 try:
264 del warning_tests.__file__
265 warning_tests.__name__ = '__main__'
266 with warnings_state(self.module):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000267 with support.catch_warning(self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000268 warning_tests.inner('spam9', stacklevel=1)
269 self.assertEqual(w.filename, sys.argv[0])
270 finally:
271 warning_tests.__file__ = filename
272 warning_tests.__name__ = module_name
273
274 def test_missing_filename_main_without_argv(self):
275 # If __file__ is not specified, the caller is __main__, and sys.argv
276 # is not set, then '__main__' is the file name.
277 filename = warning_tests.__file__
278 module_name = warning_tests.__name__
279 argv = sys.argv
280 try:
281 del warning_tests.__file__
282 warning_tests.__name__ = '__main__'
283 del sys.argv
284 with warnings_state(self.module):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000285 with support.catch_warning(self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000286 warning_tests.inner('spam10', stacklevel=1)
287 self.assertEqual(w.filename, '__main__')
288 finally:
289 warning_tests.__file__ = filename
290 warning_tests.__name__ = module_name
291 sys.argv = argv
292
Christian Heimesdaaf8ee2008-05-04 23:58:41 +0000293 def test_missing_filename_main_with_argv_empty_string(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000294 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
295 # is the empty string, then '__main__ is the file name.
296 # Tests issue 2743.
297 file_name = warning_tests.__file__
298 module_name = warning_tests.__name__
299 argv = sys.argv
300 try:
301 del warning_tests.__file__
302 warning_tests.__name__ = '__main__'
303 sys.argv = ['']
304 with warnings_state(self.module):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000305 with support.catch_warning(self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000306 warning_tests.inner('spam11', stacklevel=1)
307 self.assertEqual(w.filename, '__main__')
308 finally:
309 warning_tests.__file__ = file_name
310 warning_tests.__name__ = module_name
311 sys.argv = argv
312
Brett Cannondb734912008-06-27 00:52:15 +0000313 def test_warn_explicit_type_errors(self):
314 # warn_explicit() shoud error out gracefully if it is given objects
315 # of the wrong types.
316 # lineno is expected to be an integer.
317 self.assertRaises(TypeError, self.module.warn_explicit,
318 None, UserWarning, None, None)
319 # Either 'message' needs to be an instance of Warning or 'category'
320 # needs to be a subclass.
321 self.assertRaises(TypeError, self.module.warn_explicit,
322 None, None, None, 1)
323 # 'registry' must be a dict or None.
324 self.assertRaises((TypeError, AttributeError),
325 self.module.warn_explicit,
326 None, Warning, None, 1, registry=42)
327
Christian Heimes33fe8092008-04-13 13:53:33 +0000328class CWarnTests(BaseTest, WarnTests):
329 module = c_warnings
330
331class PyWarnTests(BaseTest, WarnTests):
332 module = py_warnings
333
334
335class WCmdLineTests(unittest.TestCase):
336
337 def test_improper_input(self):
338 # Uses the private _setoption() function to test the parsing
339 # of command-line warning arguments
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000340 with support.catch_warning(self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000341 self.assertRaises(self.module._OptionError,
342 self.module._setoption, '1:2:3:4:5:6')
343 self.assertRaises(self.module._OptionError,
344 self.module._setoption, 'bogus::Warning')
345 self.assertRaises(self.module._OptionError,
346 self.module._setoption, 'ignore:2::4:-5')
347 self.module._setoption('error::Warning::0')
348 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
349
350class CWCmdLineTests(BaseTest, WCmdLineTests):
351 module = c_warnings
352
353class PyWCmdLineTests(BaseTest, WCmdLineTests):
354 module = py_warnings
355
356
357class _WarningsTests(BaseTest):
358
359 """Tests specific to the _warnings module."""
360
361 module = c_warnings
362
363 def test_filter(self):
364 # Everything should function even if 'filters' is not in warnings.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000365 with support.catch_warning(self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000366 self.module.filterwarnings("error", "", Warning, "", 0)
367 self.assertRaises(UserWarning, self.module.warn,
368 'convert to error')
369 del self.module.filters
370 self.assertRaises(UserWarning, self.module.warn,
371 'convert to error')
372
373 def test_onceregistry(self):
374 # Replacing or removing the onceregistry should be okay.
375 global __warningregistry__
376 message = UserWarning('onceregistry test')
377 try:
378 original_registry = self.module.onceregistry
379 __warningregistry__ = {}
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000380 with support.catch_warning(self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000381 self.module.resetwarnings()
382 self.module.filterwarnings("once", category=UserWarning)
383 self.module.warn_explicit(message, UserWarning, "file", 42)
384 self.failUnlessEqual(w.message, message)
385 w.reset()
386 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000387 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000388 # Test the resetting of onceregistry.
389 self.module.onceregistry = {}
390 __warningregistry__ = {}
391 self.module.warn('onceregistry test')
392 self.failUnlessEqual(w.message.args, message.args)
393 # Removal of onceregistry is okay.
394 w.reset()
395 del self.module.onceregistry
396 __warningregistry__ = {}
397 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000398 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000399 finally:
400 self.module.onceregistry = original_registry
401
402 def test_showwarning_missing(self):
403 # Test that showwarning() missing is okay.
404 text = 'del showwarning test'
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000405 with support.catch_warning(self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000406 self.module.filterwarnings("always", category=UserWarning)
407 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000408 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000409 self.module.warn(text)
410 result = stream.getvalue()
411 self.failUnless(text in result)
412
Christian Heimes8dc226f2008-05-06 23:45:46 +0000413 def test_showwarning_not_callable(self):
414 self.module.filterwarnings("always", category=UserWarning)
415 old_showwarning = self.module.showwarning
416 self.module.showwarning = 23
417 try:
418 self.assertRaises(TypeError, self.module.warn, "Warning!")
419 finally:
420 self.module.showwarning = old_showwarning
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000421 self.module.resetwarnings()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000422
Christian Heimes33fe8092008-04-13 13:53:33 +0000423 def test_show_warning_output(self):
424 # With showarning() missing, make sure that output is okay.
425 text = 'test show_warning'
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000426 with support.catch_warning(self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000427 self.module.filterwarnings("always", category=UserWarning)
428 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000429 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000430 warning_tests.inner(text)
431 result = stream.getvalue()
432 self.failUnlessEqual(result.count('\n'), 2,
433 "Too many newlines in %r" % result)
434 first_line, second_line = result.split('\n', 1)
435 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Neal Norwitz32dde222008-04-15 06:43:13 +0000436 first_line_parts = first_line.rsplit(':', 3)
437 path, line, warning_class, message = first_line_parts
Christian Heimes33fe8092008-04-13 13:53:33 +0000438 line = int(line)
439 self.failUnlessEqual(expected_file, path)
440 self.failUnlessEqual(warning_class, ' ' + UserWarning.__name__)
441 self.failUnlessEqual(message, ' ' + text)
442 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
443 assert expected_line
444 self.failUnlessEqual(second_line, expected_line)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000445
446
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000447class WarningsDisplayTests(unittest.TestCase):
448
Christian Heimes33fe8092008-04-13 13:53:33 +0000449 """Test the displaying of warnings and the ability to overload functions
450 related to displaying warnings."""
451
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000452 def test_formatwarning(self):
453 message = "msg"
454 category = Warning
455 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
456 line_num = 3
457 file_line = linecache.getline(file_name, line_num).strip()
Christian Heimes33fe8092008-04-13 13:53:33 +0000458 format = "%s:%s: %s: %s\n %s\n"
459 expect = format % (file_name, line_num, category.__name__, message,
460 file_line)
461 self.failUnlessEqual(expect, self.module.formatwarning(message,
462 category, file_name, line_num))
463 # Test the 'line' argument.
464 file_line += " for the win!"
465 expect = format % (file_name, line_num, category.__name__, message,
466 file_line)
467 self.failUnlessEqual(expect, self.module.formatwarning(message,
468 category, file_name, line_num, file_line))
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000469
470 def test_showwarning(self):
471 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
472 line_num = 3
473 expected_file_line = linecache.getline(file_name, line_num).strip()
474 message = 'msg'
475 category = Warning
476 file_object = StringIO()
Christian Heimes33fe8092008-04-13 13:53:33 +0000477 expect = self.module.formatwarning(message, category, file_name,
478 line_num)
479 self.module.showwarning(message, category, file_name, line_num,
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000480 file_object)
481 self.failUnlessEqual(file_object.getvalue(), expect)
Christian Heimes33fe8092008-04-13 13:53:33 +0000482 # Test 'line' argument.
483 expected_file_line += "for the win!"
484 expect = self.module.formatwarning(message, category, file_name,
485 line_num, expected_file_line)
486 file_object = StringIO()
487 self.module.showwarning(message, category, file_name, line_num,
488 file_object, expected_file_line)
489 self.failUnlessEqual(expect, file_object.getvalue())
490
491class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
492 module = c_warnings
493
494class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
495 module = py_warnings
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000496
Brett Cannonec92e182008-09-02 02:46:59 +0000497class CatchWarningTests(BaseTest):
Nick Coghlanb1304932008-07-13 12:25:08 +0000498
Brett Cannonec92e182008-09-02 02:46:59 +0000499 """Test catch_warnings()."""
500
501 def test_catch_warnings_restore(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000502 wmod = self.module
503 orig_filters = wmod.filters
504 orig_showwarning = wmod.showwarning
Brett Cannonec92e182008-09-02 02:46:59 +0000505 with support.catch_warning(module=wmod):
Nick Coghlanb1304932008-07-13 12:25:08 +0000506 wmod.filters = wmod.showwarning = object()
507 self.assert_(wmod.filters is orig_filters)
508 self.assert_(wmod.showwarning is orig_showwarning)
Brett Cannonec92e182008-09-02 02:46:59 +0000509 with support.catch_warning(module=wmod, record=False):
Nick Coghlanb1304932008-07-13 12:25:08 +0000510 wmod.filters = wmod.showwarning = object()
511 self.assert_(wmod.filters is orig_filters)
512 self.assert_(wmod.showwarning is orig_showwarning)
513
Brett Cannonec92e182008-09-02 02:46:59 +0000514 def test_catch_warnings_recording(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000515 wmod = self.module
Brett Cannonec92e182008-09-02 02:46:59 +0000516 with support.catch_warning(module=wmod) as w:
517 self.assertEqual(w, [])
Nick Coghlanb1304932008-07-13 12:25:08 +0000518 wmod.simplefilter("always")
519 wmod.warn("foo")
520 self.assertEqual(str(w.message), "foo")
521 wmod.warn("bar")
522 self.assertEqual(str(w.message), "bar")
Brett Cannonec92e182008-09-02 02:46:59 +0000523 self.assertEqual(str(w[0].message), "foo")
524 self.assertEqual(str(w[1].message), "bar")
Nick Coghlanb1304932008-07-13 12:25:08 +0000525 w.reset()
Brett Cannonec92e182008-09-02 02:46:59 +0000526 self.assertEqual(w, [])
Nick Coghlanb1304932008-07-13 12:25:08 +0000527 orig_showwarning = wmod.showwarning
Brett Cannonec92e182008-09-02 02:46:59 +0000528 with support.catch_warning(module=wmod, record=False) as w:
Nick Coghlanb1304932008-07-13 12:25:08 +0000529 self.assert_(w is None)
530 self.assert_(wmod.showwarning is orig_showwarning)
531
Brett Cannonec92e182008-09-02 02:46:59 +0000532class CCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000533 module = c_warnings
534
Brett Cannonec92e182008-09-02 02:46:59 +0000535class PyCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000536 module = py_warnings
537
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000538
Christian Heimes33fe8092008-04-13 13:53:33 +0000539def test_main():
Christian Heimesdae2a892008-04-19 00:55:37 +0000540 py_warnings.onceregistry.clear()
541 c_warnings.onceregistry.clear()
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000542 support.run_unittest(CFilterTests,
Christian Heimes33fe8092008-04-13 13:53:33 +0000543 PyFilterTests,
544 CWarnTests,
545 PyWarnTests,
546 CWCmdLineTests, PyWCmdLineTests,
547 _WarningsTests,
548 CWarningsDisplayTests, PyWarningsDisplayTests,
Brett Cannonec92e182008-09-02 02:46:59 +0000549 CCatchWarningTests, PyCatchWarningTests,
Christian Heimes33fe8092008-04-13 13:53:33 +0000550 )
551
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000552
553if __name__ == "__main__":
Christian Heimes33fe8092008-04-13 13:53:33 +0000554 test_main()