blob: 0f3ee8b36f2d5cbda3a75bfc8b35811b492c01af [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
7from test import test_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):
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):
82 with test_support.catch_warning(self.module) as w:
83 self.module.resetwarnings()
84 self.module.filterwarnings("ignore", category=UserWarning)
85 self.module.warn("FilterTests.test_ignore", UserWarning)
86 self.assert_(not w.message)
87
88 def test_always(self):
89 with test_support.catch_warning(self.module) as w:
90 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)
95 w.message = None # Reset.
96 self.module.warn(message, UserWarning)
97 self.assert_(w.message, message)
98
99 def test_default(self):
100 with test_support.catch_warning(self.module) as w:
101 self.module.resetwarnings()
102 self.module.filterwarnings("default", category=UserWarning)
103 message = UserWarning("FilterTests.test_default")
104 for x in range(2):
105 self.module.warn(message, UserWarning)
106 if x == 0:
107 self.assertEquals(w.message, message)
108 w.reset()
109 elif x == 1:
110 self.assert_(not w.message, "unexpected warning: " + str(w))
111 else:
112 raise ValueError("loop variant unhandled")
113
114 def test_module(self):
115 with test_support.catch_warning(self.module) as w:
116 self.module.resetwarnings()
117 self.module.filterwarnings("module", category=UserWarning)
118 message = UserWarning("FilterTests.test_module")
119 self.module.warn(message, UserWarning)
120 self.assertEquals(w.message, message)
121 w.reset()
122 self.module.warn(message, UserWarning)
123 self.assert_(not w.message, "unexpected message: " + str(w))
124
125 def test_once(self):
126 with test_support.catch_warning(self.module) as w:
127 self.module.resetwarnings()
128 self.module.filterwarnings("once", category=UserWarning)
129 message = UserWarning("FilterTests.test_once")
130 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
131 42)
132 self.assertEquals(w.message, message)
133 w.reset()
134 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
135 13)
136 self.assert_(not w.message)
137 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
138 42)
139 self.assert_(not w.message)
140
141 def test_inheritance(self):
142 with test_support.catch_warning(self.module) as w:
143 self.module.resetwarnings()
144 self.module.filterwarnings("error", category=Warning)
145 self.assertRaises(UserWarning, self.module.warn,
146 "FilterTests.test_inheritance", UserWarning)
147
148 def test_ordering(self):
149 with test_support.catch_warning(self.module) as w:
150 self.module.resetwarnings()
151 self.module.filterwarnings("ignore", category=UserWarning)
152 self.module.filterwarnings("error", category=UserWarning,
153 append=True)
154 w.reset()
155 try:
156 self.module.warn("FilterTests.test_ordering", UserWarning)
157 except UserWarning:
158 self.fail("order handling for actions failed")
159 self.assert_(not w.message)
160
161 def test_filterwarnings(self):
162 # Test filterwarnings().
163 # Implicitly also tests resetwarnings().
164 with test_support.catch_warning(self.module) as w:
165 self.module.filterwarnings("error", "", Warning, "", 0)
166 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
167
168 self.module.resetwarnings()
169 text = 'handle normally'
170 self.module.warn(text)
171 self.assertEqual(str(w.message), text)
172 self.assert_(w.category is UserWarning)
173
174 self.module.filterwarnings("ignore", "", Warning, "", 0)
175 text = 'filtered out'
176 self.module.warn(text)
177 self.assertNotEqual(str(w.message), text)
178
179 self.module.resetwarnings()
180 self.module.filterwarnings("error", "hex*", Warning, "", 0)
181 self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
182 text = 'nonmatching text'
183 self.module.warn(text)
184 self.assertEqual(str(w.message), text)
185 self.assert_(w.category is UserWarning)
186
187class CFilterTests(BaseTest, FilterTests):
188 module = c_warnings
189
190class PyFilterTests(BaseTest, FilterTests):
191 module = py_warnings
192
193
194class WarnTests(unittest.TestCase):
195
196 """Test warnings.warn() and warnings.warn_explicit()."""
197
198 def test_message(self):
199 with test_support.catch_warning(self.module) as w:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000200 for i in range(4):
Christian Heimes33fe8092008-04-13 13:53:33 +0000201 text = 'multi %d' %i # Different text on each call.
202 self.module.warn(text)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000203 self.assertEqual(str(w.message), text)
204 self.assert_(w.category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000205
Guido van Rossumd8faa362007-04-27 19:54:29 +0000206 def test_filename(self):
Christian Heimes33fe8092008-04-13 13:53:33 +0000207 with warnings_state(self.module):
208 with test_support.catch_warning(self.module) as w:
209 warning_tests.inner("spam1")
210 self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
211 warning_tests.outer("spam2")
212 self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000213
214 def test_stacklevel(self):
215 # Test stacklevel argument
216 # make sure all messages are different, so the warning won't be skipped
Christian Heimes33fe8092008-04-13 13:53:33 +0000217 with warnings_state(self.module):
218 with test_support.catch_warning(self.module) as w:
219 warning_tests.inner("spam3", stacklevel=1)
220 self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
221 warning_tests.outer("spam4", stacklevel=1)
222 self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000223
Christian Heimes33fe8092008-04-13 13:53:33 +0000224 warning_tests.inner("spam5", stacklevel=2)
225 self.assertEqual(os.path.basename(w.filename), "test_warnings.py")
226 warning_tests.outer("spam6", stacklevel=2)
227 self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000228
Christian Heimes33fe8092008-04-13 13:53:33 +0000229 warning_tests.inner("spam7", stacklevel=9999)
230 self.assertEqual(os.path.basename(w.filename), "sys")
231
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000232 def test_missing_filename_not_main(self):
233 # If __file__ is not specified and __main__ is not the module name,
234 # then __file__ should be set to the module name.
235 filename = warning_tests.__file__
236 try:
237 del warning_tests.__file__
238 with warnings_state(self.module):
239 with test_support.catch_warning(self.module) as w:
240 warning_tests.inner("spam8", stacklevel=1)
241 self.assertEqual(w.filename, warning_tests.__name__)
242 finally:
243 warning_tests.__file__ = filename
244
245 def test_missing_filename_main_with_argv(self):
246 # If __file__ is not specified and the caller is __main__ and sys.argv
247 # exists, then use sys.argv[0] as the file.
248 if not hasattr(sys, 'argv'):
249 return
250 filename = warning_tests.__file__
251 module_name = warning_tests.__name__
252 try:
253 del warning_tests.__file__
254 warning_tests.__name__ = '__main__'
255 with warnings_state(self.module):
256 with test_support.catch_warning(self.module) as w:
257 warning_tests.inner('spam9', stacklevel=1)
258 self.assertEqual(w.filename, sys.argv[0])
259 finally:
260 warning_tests.__file__ = filename
261 warning_tests.__name__ = module_name
262
263 def test_missing_filename_main_without_argv(self):
264 # If __file__ is not specified, the caller is __main__, and sys.argv
265 # is not set, then '__main__' is the file name.
266 filename = warning_tests.__file__
267 module_name = warning_tests.__name__
268 argv = sys.argv
269 try:
270 del warning_tests.__file__
271 warning_tests.__name__ = '__main__'
272 del sys.argv
273 with warnings_state(self.module):
274 with test_support.catch_warning(self.module) as w:
275 warning_tests.inner('spam10', stacklevel=1)
276 self.assertEqual(w.filename, '__main__')
277 finally:
278 warning_tests.__file__ = filename
279 warning_tests.__name__ = module_name
280 sys.argv = argv
281
282 def BROKEN_test_missing_filename_main_with_argv_empty_string(self):
283 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
284 # is the empty string, then '__main__ is the file name.
285 # Tests issue 2743.
286 file_name = warning_tests.__file__
287 module_name = warning_tests.__name__
288 argv = sys.argv
289 try:
290 del warning_tests.__file__
291 warning_tests.__name__ = '__main__'
292 sys.argv = ['']
293 with warnings_state(self.module):
294 with test_support.catch_warning(self.module) as w:
295 warning_tests.inner('spam11', stacklevel=1)
296 self.assertEqual(w.filename, '__main__')
297 finally:
298 warning_tests.__file__ = file_name
299 warning_tests.__name__ = module_name
300 sys.argv = argv
301
302
Christian Heimes33fe8092008-04-13 13:53:33 +0000303
304class CWarnTests(BaseTest, WarnTests):
305 module = c_warnings
306
307class PyWarnTests(BaseTest, WarnTests):
308 module = py_warnings
309
310
311class WCmdLineTests(unittest.TestCase):
312
313 def test_improper_input(self):
314 # Uses the private _setoption() function to test the parsing
315 # of command-line warning arguments
316 with test_support.catch_warning(self.module):
317 self.assertRaises(self.module._OptionError,
318 self.module._setoption, '1:2:3:4:5:6')
319 self.assertRaises(self.module._OptionError,
320 self.module._setoption, 'bogus::Warning')
321 self.assertRaises(self.module._OptionError,
322 self.module._setoption, 'ignore:2::4:-5')
323 self.module._setoption('error::Warning::0')
324 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
325
326class CWCmdLineTests(BaseTest, WCmdLineTests):
327 module = c_warnings
328
329class PyWCmdLineTests(BaseTest, WCmdLineTests):
330 module = py_warnings
331
332
333class _WarningsTests(BaseTest):
334
335 """Tests specific to the _warnings module."""
336
337 module = c_warnings
338
339 def test_filter(self):
340 # Everything should function even if 'filters' is not in warnings.
341 with test_support.catch_warning(self.module) as w:
342 self.module.filterwarnings("error", "", Warning, "", 0)
343 self.assertRaises(UserWarning, self.module.warn,
344 'convert to error')
345 del self.module.filters
346 self.assertRaises(UserWarning, self.module.warn,
347 'convert to error')
348
349 def test_onceregistry(self):
350 # Replacing or removing the onceregistry should be okay.
351 global __warningregistry__
352 message = UserWarning('onceregistry test')
353 try:
354 original_registry = self.module.onceregistry
355 __warningregistry__ = {}
356 with test_support.catch_warning(self.module) as w:
357 self.module.resetwarnings()
358 self.module.filterwarnings("once", category=UserWarning)
359 self.module.warn_explicit(message, UserWarning, "file", 42)
360 self.failUnlessEqual(w.message, message)
361 w.reset()
362 self.module.warn_explicit(message, UserWarning, "file", 42)
363 self.assert_(not w.message)
364 # Test the resetting of onceregistry.
365 self.module.onceregistry = {}
366 __warningregistry__ = {}
367 self.module.warn('onceregistry test')
368 self.failUnlessEqual(w.message.args, message.args)
369 # Removal of onceregistry is okay.
370 w.reset()
371 del self.module.onceregistry
372 __warningregistry__ = {}
373 self.module.warn_explicit(message, UserWarning, "file", 42)
374 self.failUnless(not w.message)
375 finally:
376 self.module.onceregistry = original_registry
377
378 def test_showwarning_missing(self):
379 # Test that showwarning() missing is okay.
380 text = 'del showwarning test'
381 with test_support.catch_warning(self.module):
382 self.module.filterwarnings("always", category=UserWarning)
383 del self.module.showwarning
384 with test_support.captured_output('stderr') as stream:
385 self.module.warn(text)
386 result = stream.getvalue()
387 self.failUnless(text in result)
388
389 def test_show_warning_output(self):
390 # With showarning() missing, make sure that output is okay.
391 text = 'test show_warning'
392 with test_support.catch_warning(self.module):
393 self.module.filterwarnings("always", category=UserWarning)
394 del self.module.showwarning
395 with test_support.captured_output('stderr') as stream:
396 warning_tests.inner(text)
397 result = stream.getvalue()
398 self.failUnlessEqual(result.count('\n'), 2,
399 "Too many newlines in %r" % result)
400 first_line, second_line = result.split('\n', 1)
401 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Neal Norwitz32dde222008-04-15 06:43:13 +0000402 first_line_parts = first_line.rsplit(':', 3)
403 path, line, warning_class, message = first_line_parts
Christian Heimes33fe8092008-04-13 13:53:33 +0000404 line = int(line)
405 self.failUnlessEqual(expected_file, path)
406 self.failUnlessEqual(warning_class, ' ' + UserWarning.__name__)
407 self.failUnlessEqual(message, ' ' + text)
408 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
409 assert expected_line
410 self.failUnlessEqual(second_line, expected_line)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000411
412
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000413class WarningsDisplayTests(unittest.TestCase):
414
Christian Heimes33fe8092008-04-13 13:53:33 +0000415 """Test the displaying of warnings and the ability to overload functions
416 related to displaying warnings."""
417
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000418 def test_formatwarning(self):
419 message = "msg"
420 category = Warning
421 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
422 line_num = 3
423 file_line = linecache.getline(file_name, line_num).strip()
Christian Heimes33fe8092008-04-13 13:53:33 +0000424 format = "%s:%s: %s: %s\n %s\n"
425 expect = format % (file_name, line_num, category.__name__, message,
426 file_line)
427 self.failUnlessEqual(expect, self.module.formatwarning(message,
428 category, file_name, line_num))
429 # Test the 'line' argument.
430 file_line += " for the win!"
431 expect = format % (file_name, line_num, category.__name__, message,
432 file_line)
433 self.failUnlessEqual(expect, self.module.formatwarning(message,
434 category, file_name, line_num, file_line))
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000435
436 def test_showwarning(self):
437 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
438 line_num = 3
439 expected_file_line = linecache.getline(file_name, line_num).strip()
440 message = 'msg'
441 category = Warning
442 file_object = StringIO()
Christian Heimes33fe8092008-04-13 13:53:33 +0000443 expect = self.module.formatwarning(message, category, file_name,
444 line_num)
445 self.module.showwarning(message, category, file_name, line_num,
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000446 file_object)
447 self.failUnlessEqual(file_object.getvalue(), expect)
Christian Heimes33fe8092008-04-13 13:53:33 +0000448 # Test 'line' argument.
449 expected_file_line += "for the win!"
450 expect = self.module.formatwarning(message, category, file_name,
451 line_num, expected_file_line)
452 file_object = StringIO()
453 self.module.showwarning(message, category, file_name, line_num,
454 file_object, expected_file_line)
455 self.failUnlessEqual(expect, file_object.getvalue())
456
457class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
458 module = c_warnings
459
460class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
461 module = py_warnings
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000462
463
Christian Heimes33fe8092008-04-13 13:53:33 +0000464def test_main():
Christian Heimesdae2a892008-04-19 00:55:37 +0000465 py_warnings.onceregistry.clear()
466 c_warnings.onceregistry.clear()
Christian Heimes33fe8092008-04-13 13:53:33 +0000467 test_support.run_unittest(CFilterTests,
468 PyFilterTests,
469 CWarnTests,
470 PyWarnTests,
471 CWCmdLineTests, PyWCmdLineTests,
472 _WarningsTests,
473 CWarningsDisplayTests, PyWarningsDisplayTests,
474 )
475
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000476
477if __name__ == "__main__":
Christian Heimes33fe8092008-04-13 13:53:33 +0000478 test_main()