blob: 199e6fca3d96e3948d3cbbff046f9f2d0758275a [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):
217 with support.catch_warning(self.module) as w:
218 self.module.warn(ob)
219 # Don't directly compare objects since
220 # ``Warning() != Warning()``.
Brett Cannon1cd02472008-09-09 01:52:27 +0000221 self.assertEquals(str(w[-1].message), str(UserWarning(ob)))
Brett Cannon54bd41d2008-09-02 04:01:42 +0000222
Guido van Rossumd8faa362007-04-27 19:54:29 +0000223 def test_filename(self):
Christian Heimes33fe8092008-04-13 13:53:33 +0000224 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000225 with original_warnings.catch_warnings(record=True,
226 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000227 warning_tests.inner("spam1")
Brett Cannon1cd02472008-09-09 01:52:27 +0000228 self.assertEqual(os.path.basename(w[-1].filename),
229 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000230 warning_tests.outer("spam2")
Brett Cannon1cd02472008-09-09 01:52:27 +0000231 self.assertEqual(os.path.basename(w[-1].filename),
232 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000233
234 def test_stacklevel(self):
235 # Test stacklevel argument
236 # make sure all messages are different, so the warning won't be skipped
Christian Heimes33fe8092008-04-13 13:53:33 +0000237 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000238 with original_warnings.catch_warnings(record=True,
239 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000240 warning_tests.inner("spam3", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000241 self.assertEqual(os.path.basename(w[-1].filename),
242 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000243 warning_tests.outer("spam4", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000244 self.assertEqual(os.path.basename(w[-1].filename),
245 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000246
Christian Heimes33fe8092008-04-13 13:53:33 +0000247 warning_tests.inner("spam5", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000248 self.assertEqual(os.path.basename(w[-1].filename),
249 "test_warnings.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000250 warning_tests.outer("spam6", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000251 self.assertEqual(os.path.basename(w[-1].filename),
252 "warning_tests.py")
Christian Heimes5d8da202008-05-06 13:58:24 +0000253 warning_tests.outer("spam6.5", stacklevel=3)
Brett Cannon1cd02472008-09-09 01:52:27 +0000254 self.assertEqual(os.path.basename(w[-1].filename),
255 "test_warnings.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000256
Christian Heimes33fe8092008-04-13 13:53:33 +0000257 warning_tests.inner("spam7", stacklevel=9999)
Brett Cannon1cd02472008-09-09 01:52:27 +0000258 self.assertEqual(os.path.basename(w[-1].filename),
259 "sys")
Christian Heimes33fe8092008-04-13 13:53:33 +0000260
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000261 def test_missing_filename_not_main(self):
262 # If __file__ is not specified and __main__ is not the module name,
263 # then __file__ should be set to the module name.
264 filename = warning_tests.__file__
265 try:
266 del warning_tests.__file__
267 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000268 with original_warnings.catch_warnings(record=True,
269 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000270 warning_tests.inner("spam8", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000271 self.assertEqual(w[-1].filename, warning_tests.__name__)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000272 finally:
273 warning_tests.__file__ = filename
274
275 def test_missing_filename_main_with_argv(self):
276 # If __file__ is not specified and the caller is __main__ and sys.argv
277 # exists, then use sys.argv[0] as the file.
278 if not hasattr(sys, 'argv'):
279 return
280 filename = warning_tests.__file__
281 module_name = warning_tests.__name__
282 try:
283 del warning_tests.__file__
284 warning_tests.__name__ = '__main__'
285 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000286 with original_warnings.catch_warnings(record=True,
287 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000288 warning_tests.inner('spam9', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000289 self.assertEqual(w[-1].filename, sys.argv[0])
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000290 finally:
291 warning_tests.__file__ = filename
292 warning_tests.__name__ = module_name
293
294 def test_missing_filename_main_without_argv(self):
295 # If __file__ is not specified, the caller is __main__, and sys.argv
296 # is not set, then '__main__' is the file name.
297 filename = 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 del sys.argv
304 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000305 with original_warnings.catch_warnings(record=True,
306 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000307 warning_tests.inner('spam10', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000308 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000309 finally:
310 warning_tests.__file__ = filename
311 warning_tests.__name__ = module_name
312 sys.argv = argv
313
Christian Heimesdaaf8ee2008-05-04 23:58:41 +0000314 def test_missing_filename_main_with_argv_empty_string(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000315 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
316 # is the empty string, then '__main__ is the file name.
317 # Tests issue 2743.
318 file_name = warning_tests.__file__
319 module_name = warning_tests.__name__
320 argv = sys.argv
321 try:
322 del warning_tests.__file__
323 warning_tests.__name__ = '__main__'
324 sys.argv = ['']
325 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000326 with original_warnings.catch_warnings(record=True,
327 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000328 warning_tests.inner('spam11', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000329 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000330 finally:
331 warning_tests.__file__ = file_name
332 warning_tests.__name__ = module_name
333 sys.argv = argv
334
Brett Cannondb734912008-06-27 00:52:15 +0000335 def test_warn_explicit_type_errors(self):
336 # warn_explicit() shoud error out gracefully if it is given objects
337 # of the wrong types.
338 # lineno is expected to be an integer.
339 self.assertRaises(TypeError, self.module.warn_explicit,
340 None, UserWarning, None, None)
341 # Either 'message' needs to be an instance of Warning or 'category'
342 # needs to be a subclass.
343 self.assertRaises(TypeError, self.module.warn_explicit,
344 None, None, None, 1)
345 # 'registry' must be a dict or None.
346 self.assertRaises((TypeError, AttributeError),
347 self.module.warn_explicit,
348 None, Warning, None, 1, registry=42)
349
Christian Heimes33fe8092008-04-13 13:53:33 +0000350class CWarnTests(BaseTest, WarnTests):
351 module = c_warnings
352
353class PyWarnTests(BaseTest, WarnTests):
354 module = py_warnings
355
356
357class WCmdLineTests(unittest.TestCase):
358
359 def test_improper_input(self):
360 # Uses the private _setoption() function to test the parsing
361 # of command-line warning arguments
Brett Cannon1cd02472008-09-09 01:52:27 +0000362 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000363 self.assertRaises(self.module._OptionError,
364 self.module._setoption, '1:2:3:4:5:6')
365 self.assertRaises(self.module._OptionError,
366 self.module._setoption, 'bogus::Warning')
367 self.assertRaises(self.module._OptionError,
368 self.module._setoption, 'ignore:2::4:-5')
369 self.module._setoption('error::Warning::0')
370 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
371
372class CWCmdLineTests(BaseTest, WCmdLineTests):
373 module = c_warnings
374
375class PyWCmdLineTests(BaseTest, WCmdLineTests):
376 module = py_warnings
377
378
379class _WarningsTests(BaseTest):
380
381 """Tests specific to the _warnings module."""
382
383 module = c_warnings
384
385 def test_filter(self):
386 # Everything should function even if 'filters' is not in warnings.
Brett Cannon1cd02472008-09-09 01:52:27 +0000387 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000388 self.module.filterwarnings("error", "", Warning, "", 0)
389 self.assertRaises(UserWarning, self.module.warn,
390 'convert to error')
391 del self.module.filters
392 self.assertRaises(UserWarning, self.module.warn,
393 'convert to error')
394
395 def test_onceregistry(self):
396 # Replacing or removing the onceregistry should be okay.
397 global __warningregistry__
398 message = UserWarning('onceregistry test')
399 try:
400 original_registry = self.module.onceregistry
401 __warningregistry__ = {}
Brett Cannon1cd02472008-09-09 01:52:27 +0000402 with original_warnings.catch_warnings(record=True,
403 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000404 self.module.resetwarnings()
405 self.module.filterwarnings("once", category=UserWarning)
406 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannon1cd02472008-09-09 01:52:27 +0000407 self.failUnlessEqual(w[-1].message, message)
408 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000409 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000410 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000411 # Test the resetting of onceregistry.
412 self.module.onceregistry = {}
413 __warningregistry__ = {}
414 self.module.warn('onceregistry test')
Brett Cannon1cd02472008-09-09 01:52:27 +0000415 self.failUnlessEqual(w[-1].message.args, message.args)
Christian Heimes33fe8092008-04-13 13:53:33 +0000416 # Removal of onceregistry is okay.
Brett Cannon1cd02472008-09-09 01:52:27 +0000417 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000418 del self.module.onceregistry
419 __warningregistry__ = {}
420 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000421 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000422 finally:
423 self.module.onceregistry = original_registry
424
425 def test_showwarning_missing(self):
426 # Test that showwarning() missing is okay.
427 text = 'del showwarning test'
Brett Cannon1cd02472008-09-09 01:52:27 +0000428 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000429 self.module.filterwarnings("always", category=UserWarning)
430 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000431 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000432 self.module.warn(text)
433 result = stream.getvalue()
434 self.failUnless(text in result)
435
Christian Heimes8dc226f2008-05-06 23:45:46 +0000436 def test_showwarning_not_callable(self):
437 self.module.filterwarnings("always", category=UserWarning)
438 old_showwarning = self.module.showwarning
439 self.module.showwarning = 23
440 try:
441 self.assertRaises(TypeError, self.module.warn, "Warning!")
442 finally:
443 self.module.showwarning = old_showwarning
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000444 self.module.resetwarnings()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000445
Christian Heimes33fe8092008-04-13 13:53:33 +0000446 def test_show_warning_output(self):
447 # With showarning() missing, make sure that output is okay.
448 text = 'test show_warning'
Brett Cannon1cd02472008-09-09 01:52:27 +0000449 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000450 self.module.filterwarnings("always", category=UserWarning)
451 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000452 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000453 warning_tests.inner(text)
454 result = stream.getvalue()
455 self.failUnlessEqual(result.count('\n'), 2,
456 "Too many newlines in %r" % result)
457 first_line, second_line = result.split('\n', 1)
458 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Neal Norwitz32dde222008-04-15 06:43:13 +0000459 first_line_parts = first_line.rsplit(':', 3)
460 path, line, warning_class, message = first_line_parts
Christian Heimes33fe8092008-04-13 13:53:33 +0000461 line = int(line)
462 self.failUnlessEqual(expected_file, path)
463 self.failUnlessEqual(warning_class, ' ' + UserWarning.__name__)
464 self.failUnlessEqual(message, ' ' + text)
465 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
466 assert expected_line
467 self.failUnlessEqual(second_line, expected_line)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000468
469
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000470class WarningsDisplayTests(unittest.TestCase):
471
Christian Heimes33fe8092008-04-13 13:53:33 +0000472 """Test the displaying of warnings and the ability to overload functions
473 related to displaying warnings."""
474
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000475 def test_formatwarning(self):
476 message = "msg"
477 category = Warning
478 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
479 line_num = 3
480 file_line = linecache.getline(file_name, line_num).strip()
Christian Heimes33fe8092008-04-13 13:53:33 +0000481 format = "%s:%s: %s: %s\n %s\n"
482 expect = format % (file_name, line_num, category.__name__, message,
483 file_line)
484 self.failUnlessEqual(expect, self.module.formatwarning(message,
485 category, file_name, line_num))
486 # Test the 'line' argument.
487 file_line += " for the win!"
488 expect = format % (file_name, line_num, category.__name__, message,
489 file_line)
490 self.failUnlessEqual(expect, self.module.formatwarning(message,
491 category, file_name, line_num, file_line))
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000492
493 def test_showwarning(self):
494 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
495 line_num = 3
496 expected_file_line = linecache.getline(file_name, line_num).strip()
497 message = 'msg'
498 category = Warning
499 file_object = StringIO()
Christian Heimes33fe8092008-04-13 13:53:33 +0000500 expect = self.module.formatwarning(message, category, file_name,
501 line_num)
502 self.module.showwarning(message, category, file_name, line_num,
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000503 file_object)
504 self.failUnlessEqual(file_object.getvalue(), expect)
Christian Heimes33fe8092008-04-13 13:53:33 +0000505 # Test 'line' argument.
506 expected_file_line += "for the win!"
507 expect = self.module.formatwarning(message, category, file_name,
508 line_num, expected_file_line)
509 file_object = StringIO()
510 self.module.showwarning(message, category, file_name, line_num,
511 file_object, expected_file_line)
512 self.failUnlessEqual(expect, file_object.getvalue())
513
514class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
515 module = c_warnings
516
517class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
518 module = py_warnings
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000519
Brett Cannon1cd02472008-09-09 01:52:27 +0000520
Brett Cannonec92e182008-09-02 02:46:59 +0000521class CatchWarningTests(BaseTest):
Nick Coghlanb1304932008-07-13 12:25:08 +0000522
Brett Cannonec92e182008-09-02 02:46:59 +0000523 """Test catch_warnings()."""
524
525 def test_catch_warnings_restore(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000526 wmod = self.module
527 orig_filters = wmod.filters
528 orig_showwarning = wmod.showwarning
Brett Cannonec92e182008-09-02 02:46:59 +0000529 with support.catch_warning(module=wmod):
Nick Coghlanb1304932008-07-13 12:25:08 +0000530 wmod.filters = wmod.showwarning = object()
531 self.assert_(wmod.filters is orig_filters)
532 self.assert_(wmod.showwarning is orig_showwarning)
Brett Cannonec92e182008-09-02 02:46:59 +0000533 with support.catch_warning(module=wmod, record=False):
Nick Coghlanb1304932008-07-13 12:25:08 +0000534 wmod.filters = wmod.showwarning = object()
535 self.assert_(wmod.filters is orig_filters)
536 self.assert_(wmod.showwarning is orig_showwarning)
537
Brett Cannonec92e182008-09-02 02:46:59 +0000538 def test_catch_warnings_recording(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000539 wmod = self.module
Brett Cannonec92e182008-09-02 02:46:59 +0000540 with support.catch_warning(module=wmod) as w:
541 self.assertEqual(w, [])
Nick Coghlanb1304932008-07-13 12:25:08 +0000542 wmod.simplefilter("always")
543 wmod.warn("foo")
Brett Cannon1cd02472008-09-09 01:52:27 +0000544 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlanb1304932008-07-13 12:25:08 +0000545 wmod.warn("bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000546 self.assertEqual(str(w[-1].message), "bar")
Brett Cannonec92e182008-09-02 02:46:59 +0000547 self.assertEqual(str(w[0].message), "foo")
548 self.assertEqual(str(w[1].message), "bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000549 del w[:]
Brett Cannonec92e182008-09-02 02:46:59 +0000550 self.assertEqual(w, [])
Nick Coghlanb1304932008-07-13 12:25:08 +0000551 orig_showwarning = wmod.showwarning
Brett Cannonec92e182008-09-02 02:46:59 +0000552 with support.catch_warning(module=wmod, record=False) as w:
Nick Coghlanb1304932008-07-13 12:25:08 +0000553 self.assert_(w is None)
554 self.assert_(wmod.showwarning is orig_showwarning)
555
Brett Cannonec92e182008-09-02 02:46:59 +0000556class CCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000557 module = c_warnings
558
Brett Cannonec92e182008-09-02 02:46:59 +0000559class PyCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000560 module = py_warnings
561
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000562
Christian Heimes33fe8092008-04-13 13:53:33 +0000563def test_main():
Christian Heimesdae2a892008-04-19 00:55:37 +0000564 py_warnings.onceregistry.clear()
565 c_warnings.onceregistry.clear()
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000566 support.run_unittest(CFilterTests,
Christian Heimes33fe8092008-04-13 13:53:33 +0000567 PyFilterTests,
568 CWarnTests,
569 PyWarnTests,
570 CWCmdLineTests, PyWCmdLineTests,
571 _WarningsTests,
572 CWarningsDisplayTests, PyWarningsDisplayTests,
Brett Cannonec92e182008-09-02 02:46:59 +0000573 CCatchWarningTests, PyCatchWarningTests,
Christian Heimes33fe8092008-04-13 13:53:33 +0000574 )
575
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000576
577if __name__ == "__main__":
Christian Heimes33fe8092008-04-13 13:53:33 +0000578 test_main()