blob: 9980f2497d66bb804d6040342c281c24eb36e013 [file] [log] [blame]
Brett Cannone9746892008-04-12 23:44:07 +00001from contextlib import contextmanager
Brett Cannon905c31c2007-12-20 10:09:52 +00002import linecache
Raymond Hettingerdc9dcf12003-07-13 06:15:11 +00003import os
Brett Cannon905c31c2007-12-20 10:09:52 +00004import StringIO
Brett Cannon855da6c2007-08-17 20:16:15 +00005import sys
Raymond Hettingerd6f6e502003-07-13 08:37:40 +00006import unittest
7from test import test_support
Jeremy Hylton85014662003-07-11 15:37:59 +00008
Walter Dörwalde1a9b422007-04-03 16:53:43 +00009import warning_tests
10
Brett Cannon667bb4f2008-04-13 02:42:36 +000011import warnings as original_warnings
12
Brett Cannone9746892008-04-12 23:44:07 +000013sys.modules['_warnings'] = 0
Brett Cannon667bb4f2008-04-13 02:42:36 +000014del sys.modules['warnings']
Jeremy Hylton85014662003-07-11 15:37:59 +000015
Brett Cannone9746892008-04-12 23:44:07 +000016import warnings as py_warnings
17
18del sys.modules['_warnings']
19del sys.modules['warnings']
20
21import warnings as c_warnings
22
Brett Cannon667bb4f2008-04-13 02:42:36 +000023sys.modules['warnings'] = original_warnings
24
25
Brett Cannone9746892008-04-12 23:44:07 +000026@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
Brett Cannon667bb4f2008-04-13 02:42:36 +000047class BaseTest(unittest.TestCase):
Brett Cannone9746892008-04-12 23:44:07 +000048
Brett Cannon667bb4f2008-04-13 02:42:36 +000049 """Basic bookkeeping required for testing."""
Brett Cannone9746892008-04-12 23:44:07 +000050
51 def setUp(self):
Brett Cannon667bb4f2008-04-13 02:42:36 +000052 # 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."""
Brett Cannone9746892008-04-12 23:44:07 +000073
74 def test_error(self):
75 with test_support.catch_warning(self.module) as w:
76 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 Cannon1eaf0742008-09-02 01:25:16 +000082 with test_support.catch_warning(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +000083 self.module.resetwarnings()
84 self.module.filterwarnings("ignore", category=UserWarning)
85 self.module.warn("FilterTests.test_ignore", UserWarning)
Brett Cannon1eaf0742008-09-02 01:25:16 +000086 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +000087
88 def test_always(self):
Brett Cannon1eaf0742008-09-02 01:25:16 +000089 with test_support.catch_warning(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +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)
Brett Cannone9746892008-04-12 23:44:07 +000095 self.module.warn(message, UserWarning)
96 self.assert_(w.message, message)
97
98 def test_default(self):
99 with test_support.catch_warning(self.module) as w:
100 self.module.resetwarnings()
101 self.module.filterwarnings("default", category=UserWarning)
102 message = UserWarning("FilterTests.test_default")
103 for x in xrange(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 Cannon1eaf0742008-09-02 01:25:16 +0000109 self.assert_(not len(w), "unexpected warning: " + str(w))
Brett Cannone9746892008-04-12 23:44:07 +0000110 else:
111 raise ValueError("loop variant unhandled")
112
113 def test_module(self):
114 with test_support.catch_warning(self.module) as w:
115 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 Cannon1eaf0742008-09-02 01:25:16 +0000122 self.assert_(not len(w), "unexpected message: " + str(w))
Brett Cannone9746892008-04-12 23:44:07 +0000123
124 def test_once(self):
125 with test_support.catch_warning(self.module) as w:
126 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 Cannon1eaf0742008-09-02 01:25:16 +0000135 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000136 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
137 42)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000138 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000139
140 def test_inheritance(self):
141 with test_support.catch_warning(self.module) as w:
142 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):
148 with test_support.catch_warning(self.module) as w:
149 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 Cannon1eaf0742008-09-02 01:25:16 +0000158 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000159
160 def test_filterwarnings(self):
161 # Test filterwarnings().
162 # Implicitly also tests resetwarnings().
163 with test_support.catch_warning(self.module) as w:
164 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
Brett Cannon667bb4f2008-04-13 02:42:36 +0000186class CFilterTests(BaseTest, FilterTests):
Brett Cannone9746892008-04-12 23:44:07 +0000187 module = c_warnings
188
Brett Cannon667bb4f2008-04-13 02:42:36 +0000189class PyFilterTests(BaseTest, FilterTests):
Brett Cannone9746892008-04-12 23:44:07 +0000190 module = py_warnings
191
192
193class WarnTests(unittest.TestCase):
194
195 """Test warnings.warn() and warnings.warn_explicit()."""
196
197 def test_message(self):
198 with test_support.catch_warning(self.module) as w:
Walter Dörwalde6dae6c2007-04-03 18:33:29 +0000199 for i in range(4):
Brett Cannone9746892008-04-12 23:44:07 +0000200 text = 'multi %d' %i # Different text on each call.
201 self.module.warn(text)
Walter Dörwalde6dae6c2007-04-03 18:33:29 +0000202 self.assertEqual(str(w.message), text)
203 self.assert_(w.category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000204
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000205 def test_filename(self):
Brett Cannone9746892008-04-12 23:44:07 +0000206 with warnings_state(self.module):
207 with test_support.catch_warning(self.module) as w:
208 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")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000212
213 def test_stacklevel(self):
214 # Test stacklevel argument
215 # make sure all messages are different, so the warning won't be skipped
Brett Cannone9746892008-04-12 23:44:07 +0000216 with warnings_state(self.module):
217 with test_support.catch_warning(self.module) as w:
218 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")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000222
Brett Cannone9746892008-04-12 23:44:07 +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")
Brett Cannone3dcb012008-05-06 04:37:31 +0000227 warning_tests.outer("spam6.5", stacklevel=3)
228 self.assertEqual(os.path.basename(w.filename), "test_warnings.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000229
Brett Cannone9746892008-04-12 23:44:07 +0000230 warning_tests.inner("spam7", stacklevel=9999)
231 self.assertEqual(os.path.basename(w.filename), "sys")
232
Brett Cannon64a4bbe2008-05-03 03:19:39 +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):
240 with test_support.catch_warning(self.module) as w:
241 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):
257 with test_support.catch_warning(self.module) as w:
258 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):
275 with test_support.catch_warning(self.module) as w:
276 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
283 def test_missing_filename_main_with_argv_empty_string(self):
284 # 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):
295 with test_support.catch_warning(self.module) as w:
296 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 Cannondea1b562008-06-27 00:31:13 +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
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000318
Brett Cannon667bb4f2008-04-13 02:42:36 +0000319class CWarnTests(BaseTest, WarnTests):
Brett Cannone9746892008-04-12 23:44:07 +0000320 module = c_warnings
321
Brett Cannon667bb4f2008-04-13 02:42:36 +0000322class PyWarnTests(BaseTest, WarnTests):
Brett Cannone9746892008-04-12 23:44:07 +0000323 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
331 with test_support.catch_warning(self.module):
332 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
Brett Cannon667bb4f2008-04-13 02:42:36 +0000341class CWCmdLineTests(BaseTest, WCmdLineTests):
Brett Cannone9746892008-04-12 23:44:07 +0000342 module = c_warnings
343
Brett Cannon667bb4f2008-04-13 02:42:36 +0000344class PyWCmdLineTests(BaseTest, WCmdLineTests):
Brett Cannone9746892008-04-12 23:44:07 +0000345 module = py_warnings
346
347
Brett Cannon667bb4f2008-04-13 02:42:36 +0000348class _WarningsTests(BaseTest):
Brett Cannone9746892008-04-12 23:44:07 +0000349
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.
356 with test_support.catch_warning(self.module) as w:
357 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__ = {}
371 with test_support.catch_warning(self.module) as w:
372 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 Cannon1eaf0742008-09-02 01:25:16 +0000378 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +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 Cannon1eaf0742008-09-02 01:25:16 +0000389 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +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'
396 with test_support.catch_warning(self.module):
397 self.module.filterwarnings("always", category=UserWarning)
398 del self.module.showwarning
399 with test_support.captured_output('stderr') as stream:
400 self.module.warn(text)
401 result = stream.getvalue()
402 self.failUnless(text in result)
403
Benjamin Petersond2950322008-05-06 22:18:11 +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
Georg Brandl88598222008-05-14 07:18:22 +0000412 self.module.resetwarnings()
Benjamin Petersond2950322008-05-06 22:18:11 +0000413
Brett Cannone9746892008-04-12 23:44:07 +0000414 def test_show_warning_output(self):
415 # With showarning() missing, make sure that output is okay.
416 text = 'test show_warning'
417 with test_support.catch_warning(self.module):
418 self.module.filterwarnings("always", category=UserWarning)
419 del self.module.showwarning
420 with test_support.captured_output('stderr') as stream:
421 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'
Brett Cannonc4774272008-04-13 17:41:31 +0000427 first_line_parts = first_line.rsplit(':', 3)
Brett Cannon25bb8182008-04-13 17:09:43 +0000428 path, line, warning_class, message = first_line_parts
Brett Cannone9746892008-04-12 23:44:07 +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)
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000436
Brett Cannon53ab5b72006-06-22 16:49:14 +0000437
Brett Cannon905c31c2007-12-20 10:09:52 +0000438class WarningsDisplayTests(unittest.TestCase):
439
Brett Cannone9746892008-04-12 23:44:07 +0000440 """Test the displaying of warnings and the ability to overload functions
441 related to displaying warnings."""
442
Brett Cannon905c31c2007-12-20 10:09:52 +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()
Brett Cannone9746892008-04-12 23:44:07 +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))
Brett Cannon905c31c2007-12-20 10:09:52 +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.StringIO()
Brett Cannone9746892008-04-12 23:44:07 +0000468 expect = self.module.formatwarning(message, category, file_name,
469 line_num)
470 self.module.showwarning(message, category, file_name, line_num,
Brett Cannon905c31c2007-12-20 10:09:52 +0000471 file_object)
472 self.failUnlessEqual(file_object.getvalue(), expect)
Brett Cannone9746892008-04-12 23:44:07 +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.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
Brett Cannon667bb4f2008-04-13 02:42:36 +0000482class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
Brett Cannone9746892008-04-12 23:44:07 +0000483 module = c_warnings
484
Brett Cannon667bb4f2008-04-13 02:42:36 +0000485class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
Brett Cannone9746892008-04-12 23:44:07 +0000486 module = py_warnings
Brett Cannon905c31c2007-12-20 10:09:52 +0000487
488
Nick Coghlan38469e22008-07-13 12:23:47 +0000489
Brett Cannon1eaf0742008-09-02 01:25:16 +0000490class CatchWarningTests(BaseTest):
Nick Coghlan38469e22008-07-13 12:23:47 +0000491
Brett Cannon1eaf0742008-09-02 01:25:16 +0000492 """Test catch_warnings()."""
493
494 def test_catch_warnings_restore(self):
Nick Coghlan38469e22008-07-13 12:23:47 +0000495 wmod = self.module
496 orig_filters = wmod.filters
497 orig_showwarning = wmod.showwarning
Brett Cannon1eaf0742008-09-02 01:25:16 +0000498 with wmod.catch_warnings(record=True, module=wmod):
Nick Coghlan38469e22008-07-13 12:23:47 +0000499 wmod.filters = wmod.showwarning = object()
500 self.assert_(wmod.filters is orig_filters)
501 self.assert_(wmod.showwarning is orig_showwarning)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000502 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlan38469e22008-07-13 12:23:47 +0000503 wmod.filters = wmod.showwarning = object()
504 self.assert_(wmod.filters is orig_filters)
505 self.assert_(wmod.showwarning is orig_showwarning)
506
Brett Cannon1eaf0742008-09-02 01:25:16 +0000507 def test_catch_warnings_recording(self):
Nick Coghlan38469e22008-07-13 12:23:47 +0000508 wmod = self.module
Brett Cannon1eaf0742008-09-02 01:25:16 +0000509 with wmod.catch_warnings(module=wmod, record=True) as w:
510 self.assertEqual(w, [])
Brett Cannon32476fc2008-09-05 18:33:51 +0000511 self.assertRaises(AttributeError, getattr, w, 'message')
Nick Coghlan38469e22008-07-13 12:23:47 +0000512 wmod.simplefilter("always")
513 wmod.warn("foo")
514 self.assertEqual(str(w.message), "foo")
515 wmod.warn("bar")
516 self.assertEqual(str(w.message), "bar")
Brett Cannon1eaf0742008-09-02 01:25:16 +0000517 self.assertEqual(str(w[0].message), "foo")
518 self.assertEqual(str(w[1].message), "bar")
Nick Coghlan38469e22008-07-13 12:23:47 +0000519 w.reset()
Brett Cannon1eaf0742008-09-02 01:25:16 +0000520 self.assertEqual(w, [])
Nick Coghlan38469e22008-07-13 12:23:47 +0000521 orig_showwarning = wmod.showwarning
Brett Cannon1eaf0742008-09-02 01:25:16 +0000522 with wmod.catch_warnings(module=wmod, record=False) as w:
Nick Coghlan38469e22008-07-13 12:23:47 +0000523 self.assert_(w is None)
524 self.assert_(wmod.showwarning is orig_showwarning)
525
Brett Cannon1eaf0742008-09-02 01:25:16 +0000526class CCatchWarningTests(CatchWarningTests):
Nick Coghlan38469e22008-07-13 12:23:47 +0000527 module = c_warnings
528
Brett Cannon1eaf0742008-09-02 01:25:16 +0000529class PyCatchWarningTests(CatchWarningTests):
Nick Coghlan38469e22008-07-13 12:23:47 +0000530 module = py_warnings
531
532
Brett Cannon8a232cc2008-05-05 05:32:07 +0000533class ShowwarningDeprecationTests(BaseTest):
534
535 """Test the deprecation of the old warnings.showwarning() API works."""
536
537 @staticmethod
538 def bad_showwarning(message, category, filename, lineno, file=None):
539 pass
540
Brett Cannon1eaf0742008-09-02 01:25:16 +0000541 @staticmethod
542 def ok_showwarning(*args):
543 pass
544
Brett Cannon8a232cc2008-05-05 05:32:07 +0000545 def test_deprecation(self):
546 # message, category, filename, lineno[, file[, line]]
547 args = ("message", UserWarning, "file name", 42)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000548 with test_support.catch_warning(module=self.module):
Brett Cannon8a232cc2008-05-05 05:32:07 +0000549 self.module.filterwarnings("error", category=DeprecationWarning)
550 self.module.showwarning = self.bad_showwarning
551 self.assertRaises(DeprecationWarning, self.module.warn_explicit,
552 *args)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000553 self.module.showwarning = self.ok_showwarning
554 try:
555 self.module.warn_explicit(*args)
556 except DeprecationWarning as exc:
557 self.fail('showwarning(*args) should not trigger a '
558 'DeprecationWarning')
Brett Cannon8a232cc2008-05-05 05:32:07 +0000559
560class CShowwarningDeprecationTests(ShowwarningDeprecationTests):
561 module = c_warnings
562
563
564class PyShowwarningDeprecationTests(ShowwarningDeprecationTests):
565 module = py_warnings
566
567
Brett Cannone9746892008-04-12 23:44:07 +0000568def test_main():
Amaury Forgeot d'Arc607bff12008-04-18 23:31:33 +0000569 py_warnings.onceregistry.clear()
570 c_warnings.onceregistry.clear()
Brett Cannon1eaf0742008-09-02 01:25:16 +0000571 test_support.run_unittest(CFilterTests, PyFilterTests,
572 CWarnTests, PyWarnTests,
Brett Cannone9746892008-04-12 23:44:07 +0000573 CWCmdLineTests, PyWCmdLineTests,
574 _WarningsTests,
575 CWarningsDisplayTests, PyWarningsDisplayTests,
Brett Cannon1eaf0742008-09-02 01:25:16 +0000576 CCatchWarningTests, PyCatchWarningTests,
Brett Cannon8a232cc2008-05-05 05:32:07 +0000577 CShowwarningDeprecationTests,
Brett Cannon1eaf0742008-09-02 01:25:16 +0000578 PyShowwarningDeprecationTests,
Brett Cannone9746892008-04-12 23:44:07 +0000579 )
580
581
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000582if __name__ == "__main__":
Brett Cannone9746892008-04-12 23:44:07 +0000583 test_main()