blob: e502ed8f222d454bbdc22942d46dede518c4574f [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
Philip Jenveyaebbaeb2010-04-06 23:24:45 +00007import subprocess
Raymond Hettingerd6f6e502003-07-13 08:37:40 +00008from test import test_support
Antoine Pitrou9c9e1b92010-11-10 14:03:31 +00009from test.script_helper import assert_python_ok
Jeremy Hylton85014662003-07-11 15:37:59 +000010
Walter Dörwalde1a9b422007-04-03 16:53:43 +000011import warning_tests
12
Brett Cannon667bb4f2008-04-13 02:42:36 +000013import warnings as original_warnings
14
Nick Coghlan5533ff62009-04-22 15:26:04 +000015py_warnings = test_support.import_fresh_module('warnings', blocked=['_warnings'])
16c_warnings = test_support.import_fresh_module('warnings', fresh=['_warnings'])
Brett Cannon667bb4f2008-04-13 02:42:36 +000017
Brett Cannone9746892008-04-12 23:44:07 +000018@contextmanager
19def warnings_state(module):
20 """Use a specific warnings implementation in warning_tests."""
21 global __warningregistry__
22 for to_clear in (sys, warning_tests):
23 try:
24 to_clear.__warningregistry__.clear()
25 except AttributeError:
26 pass
27 try:
28 __warningregistry__.clear()
29 except NameError:
30 pass
31 original_warnings = warning_tests.warnings
Florent Xiclunafd37dd42010-03-25 20:39:10 +000032 original_filters = module.filters
Brett Cannone9746892008-04-12 23:44:07 +000033 try:
Florent Xiclunafd37dd42010-03-25 20:39:10 +000034 module.filters = original_filters[:]
35 module.simplefilter("once")
Brett Cannone9746892008-04-12 23:44:07 +000036 warning_tests.warnings = module
37 yield
38 finally:
39 warning_tests.warnings = original_warnings
Florent Xiclunafd37dd42010-03-25 20:39:10 +000040 module.filters = original_filters
Brett Cannone9746892008-04-12 23:44:07 +000041
42
Brett Cannon667bb4f2008-04-13 02:42:36 +000043class BaseTest(unittest.TestCase):
Brett Cannone9746892008-04-12 23:44:07 +000044
Brett Cannon667bb4f2008-04-13 02:42:36 +000045 """Basic bookkeeping required for testing."""
Brett Cannone9746892008-04-12 23:44:07 +000046
47 def setUp(self):
Brett Cannon667bb4f2008-04-13 02:42:36 +000048 # The __warningregistry__ needs to be in a pristine state for tests
49 # to work properly.
50 if '__warningregistry__' in globals():
51 del globals()['__warningregistry__']
52 if hasattr(warning_tests, '__warningregistry__'):
53 del warning_tests.__warningregistry__
54 if hasattr(sys, '__warningregistry__'):
55 del sys.__warningregistry__
56 # The 'warnings' module must be explicitly set so that the proper
57 # interaction between _warnings and 'warnings' can be controlled.
58 sys.modules['warnings'] = self.module
59 super(BaseTest, self).setUp()
60
61 def tearDown(self):
62 sys.modules['warnings'] = original_warnings
63 super(BaseTest, self).tearDown()
64
65
66class FilterTests(object):
67
68 """Testing the filtering functionality."""
Brett Cannone9746892008-04-12 23:44:07 +000069
70 def test_error(self):
Brett Cannon672237d2008-09-09 00:49:16 +000071 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +000072 self.module.resetwarnings()
73 self.module.filterwarnings("error", category=UserWarning)
74 self.assertRaises(UserWarning, self.module.warn,
75 "FilterTests.test_error")
76
77 def test_ignore(self):
Brett Cannon672237d2008-09-09 00:49:16 +000078 with original_warnings.catch_warnings(record=True,
79 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +000080 self.module.resetwarnings()
81 self.module.filterwarnings("ignore", category=UserWarning)
82 self.module.warn("FilterTests.test_ignore", UserWarning)
Ezio Melotti2623a372010-11-21 13:34:58 +000083 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +000084
85 def test_always(self):
Brett Cannon672237d2008-09-09 00:49:16 +000086 with original_warnings.catch_warnings(record=True,
87 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +000088 self.module.resetwarnings()
89 self.module.filterwarnings("always", category=UserWarning)
90 message = "FilterTests.test_always"
91 self.module.warn(message, UserWarning)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000092 self.assertTrue(message, w[-1].message)
Brett Cannone9746892008-04-12 23:44:07 +000093 self.module.warn(message, UserWarning)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000094 self.assertTrue(w[-1].message, message)
Brett Cannone9746892008-04-12 23:44:07 +000095
96 def test_default(self):
Brett Cannon672237d2008-09-09 00:49:16 +000097 with original_warnings.catch_warnings(record=True,
98 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +000099 self.module.resetwarnings()
100 self.module.filterwarnings("default", category=UserWarning)
101 message = UserWarning("FilterTests.test_default")
102 for x in xrange(2):
103 self.module.warn(message, UserWarning)
104 if x == 0:
Ezio Melotti2623a372010-11-21 13:34:58 +0000105 self.assertEqual(w[-1].message, message)
Brett Cannon672237d2008-09-09 00:49:16 +0000106 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000107 elif x == 1:
Ezio Melotti2623a372010-11-21 13:34:58 +0000108 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000109 else:
110 raise ValueError("loop variant unhandled")
111
112 def test_module(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000113 with original_warnings.catch_warnings(record=True,
114 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000115 self.module.resetwarnings()
116 self.module.filterwarnings("module", category=UserWarning)
117 message = UserWarning("FilterTests.test_module")
118 self.module.warn(message, UserWarning)
Ezio Melotti2623a372010-11-21 13:34:58 +0000119 self.assertEqual(w[-1].message, message)
Brett Cannon672237d2008-09-09 00:49:16 +0000120 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000121 self.module.warn(message, UserWarning)
Ezio Melotti2623a372010-11-21 13:34:58 +0000122 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000123
124 def test_once(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000125 with original_warnings.catch_warnings(record=True,
126 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000127 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)
Ezio Melotti2623a372010-11-21 13:34:58 +0000132 self.assertEqual(w[-1].message, message)
Brett Cannon672237d2008-09-09 00:49:16 +0000133 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000134 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
135 13)
Ezio Melotti2623a372010-11-21 13:34:58 +0000136 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000137 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
138 42)
Ezio Melotti2623a372010-11-21 13:34:58 +0000139 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000140
141 def test_inheritance(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000142 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000143 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):
Brett Cannon672237d2008-09-09 00:49:16 +0000149 with original_warnings.catch_warnings(record=True,
150 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000151 self.module.resetwarnings()
152 self.module.filterwarnings("ignore", category=UserWarning)
153 self.module.filterwarnings("error", category=UserWarning,
154 append=True)
Brett Cannon672237d2008-09-09 00:49:16 +0000155 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000156 try:
157 self.module.warn("FilterTests.test_ordering", UserWarning)
158 except UserWarning:
159 self.fail("order handling for actions failed")
Ezio Melotti2623a372010-11-21 13:34:58 +0000160 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000161
162 def test_filterwarnings(self):
163 # Test filterwarnings().
164 # Implicitly also tests resetwarnings().
Brett Cannon672237d2008-09-09 00:49:16 +0000165 with original_warnings.catch_warnings(record=True,
166 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000167 self.module.filterwarnings("error", "", Warning, "", 0)
168 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
169
170 self.module.resetwarnings()
171 text = 'handle normally'
172 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000173 self.assertEqual(str(w[-1].message), text)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000174 self.assertTrue(w[-1].category is UserWarning)
Brett Cannone9746892008-04-12 23:44:07 +0000175
176 self.module.filterwarnings("ignore", "", Warning, "", 0)
177 text = 'filtered out'
178 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000179 self.assertNotEqual(str(w[-1].message), text)
Brett Cannone9746892008-04-12 23:44:07 +0000180
181 self.module.resetwarnings()
182 self.module.filterwarnings("error", "hex*", Warning, "", 0)
183 self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
184 text = 'nonmatching text'
185 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000186 self.assertEqual(str(w[-1].message), text)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000187 self.assertTrue(w[-1].category is UserWarning)
Brett Cannone9746892008-04-12 23:44:07 +0000188
Brett Cannon667bb4f2008-04-13 02:42:36 +0000189class CFilterTests(BaseTest, FilterTests):
Brett Cannone9746892008-04-12 23:44:07 +0000190 module = c_warnings
191
Brett Cannon667bb4f2008-04-13 02:42:36 +0000192class PyFilterTests(BaseTest, FilterTests):
Brett Cannone9746892008-04-12 23:44:07 +0000193 module = py_warnings
194
195
196class WarnTests(unittest.TestCase):
197
198 """Test warnings.warn() and warnings.warn_explicit()."""
199
200 def test_message(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000201 with original_warnings.catch_warnings(record=True,
202 module=self.module) as w:
Florent Xiclunafd37dd42010-03-25 20:39:10 +0000203 self.module.simplefilter("once")
Walter Dörwalde6dae6c2007-04-03 18:33:29 +0000204 for i in range(4):
Brett Cannone9746892008-04-12 23:44:07 +0000205 text = 'multi %d' %i # Different text on each call.
206 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000207 self.assertEqual(str(w[-1].message), text)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000208 self.assertTrue(w[-1].category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000209
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000210 def test_filename(self):
Brett Cannone9746892008-04-12 23:44:07 +0000211 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000212 with original_warnings.catch_warnings(record=True,
213 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000214 warning_tests.inner("spam1")
Brett Cannon672237d2008-09-09 00:49:16 +0000215 self.assertEqual(os.path.basename(w[-1].filename),
216 "warning_tests.py")
Brett Cannone9746892008-04-12 23:44:07 +0000217 warning_tests.outer("spam2")
Brett Cannon672237d2008-09-09 00:49:16 +0000218 self.assertEqual(os.path.basename(w[-1].filename),
219 "warning_tests.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000220
221 def test_stacklevel(self):
222 # Test stacklevel argument
223 # make sure all messages are different, so the warning won't be skipped
Brett Cannone9746892008-04-12 23:44:07 +0000224 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000225 with original_warnings.catch_warnings(record=True,
226 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000227 warning_tests.inner("spam3", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000228 self.assertEqual(os.path.basename(w[-1].filename),
229 "warning_tests.py")
Brett Cannone9746892008-04-12 23:44:07 +0000230 warning_tests.outer("spam4", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000231 self.assertEqual(os.path.basename(w[-1].filename),
232 "warning_tests.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000233
Brett Cannone9746892008-04-12 23:44:07 +0000234 warning_tests.inner("spam5", stacklevel=2)
Brett Cannon672237d2008-09-09 00:49:16 +0000235 self.assertEqual(os.path.basename(w[-1].filename),
236 "test_warnings.py")
Brett Cannone9746892008-04-12 23:44:07 +0000237 warning_tests.outer("spam6", stacklevel=2)
Brett Cannon672237d2008-09-09 00:49:16 +0000238 self.assertEqual(os.path.basename(w[-1].filename),
239 "warning_tests.py")
Brett Cannone3dcb012008-05-06 04:37:31 +0000240 warning_tests.outer("spam6.5", stacklevel=3)
Brett Cannon672237d2008-09-09 00:49:16 +0000241 self.assertEqual(os.path.basename(w[-1].filename),
242 "test_warnings.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000243
Brett Cannone9746892008-04-12 23:44:07 +0000244 warning_tests.inner("spam7", stacklevel=9999)
Brett Cannon672237d2008-09-09 00:49:16 +0000245 self.assertEqual(os.path.basename(w[-1].filename),
246 "sys")
Brett Cannone9746892008-04-12 23:44:07 +0000247
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000248 def test_missing_filename_not_main(self):
249 # If __file__ is not specified and __main__ is not the module name,
250 # then __file__ should be set to the module name.
251 filename = warning_tests.__file__
252 try:
253 del warning_tests.__file__
254 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000255 with original_warnings.catch_warnings(record=True,
256 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000257 warning_tests.inner("spam8", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000258 self.assertEqual(w[-1].filename, warning_tests.__name__)
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000259 finally:
260 warning_tests.__file__ = filename
261
262 def test_missing_filename_main_with_argv(self):
263 # If __file__ is not specified and the caller is __main__ and sys.argv
264 # exists, then use sys.argv[0] as the file.
265 if not hasattr(sys, 'argv'):
266 return
267 filename = warning_tests.__file__
268 module_name = warning_tests.__name__
269 try:
270 del warning_tests.__file__
271 warning_tests.__name__ = '__main__'
272 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000273 with original_warnings.catch_warnings(record=True,
274 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000275 warning_tests.inner('spam9', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000276 self.assertEqual(w[-1].filename, sys.argv[0])
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000277 finally:
278 warning_tests.__file__ = filename
279 warning_tests.__name__ = module_name
280
281 def test_missing_filename_main_without_argv(self):
282 # If __file__ is not specified, the caller is __main__, and sys.argv
283 # is not set, then '__main__' is the file name.
284 filename = warning_tests.__file__
285 module_name = warning_tests.__name__
286 argv = sys.argv
287 try:
288 del warning_tests.__file__
289 warning_tests.__name__ = '__main__'
290 del sys.argv
291 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000292 with original_warnings.catch_warnings(record=True,
293 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000294 warning_tests.inner('spam10', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000295 self.assertEqual(w[-1].filename, '__main__')
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000296 finally:
297 warning_tests.__file__ = filename
298 warning_tests.__name__ = module_name
299 sys.argv = argv
300
301 def test_missing_filename_main_with_argv_empty_string(self):
302 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
303 # is the empty string, then '__main__ is the file name.
304 # Tests issue 2743.
305 file_name = warning_tests.__file__
306 module_name = warning_tests.__name__
307 argv = sys.argv
308 try:
309 del warning_tests.__file__
310 warning_tests.__name__ = '__main__'
311 sys.argv = ['']
312 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000313 with original_warnings.catch_warnings(record=True,
314 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000315 warning_tests.inner('spam11', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000316 self.assertEqual(w[-1].filename, '__main__')
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000317 finally:
318 warning_tests.__file__ = file_name
319 warning_tests.__name__ = module_name
320 sys.argv = argv
321
Brett Cannondea1b562008-06-27 00:31:13 +0000322 def test_warn_explicit_type_errors(self):
Ezio Melottic2077b02011-03-16 12:34:31 +0200323 # warn_explicit() should error out gracefully if it is given objects
Brett Cannondea1b562008-06-27 00:31:13 +0000324 # of the wrong types.
325 # lineno is expected to be an integer.
326 self.assertRaises(TypeError, self.module.warn_explicit,
327 None, UserWarning, None, None)
328 # Either 'message' needs to be an instance of Warning or 'category'
329 # needs to be a subclass.
330 self.assertRaises(TypeError, self.module.warn_explicit,
331 None, None, None, 1)
332 # 'registry' must be a dict or None.
333 self.assertRaises((TypeError, AttributeError),
334 self.module.warn_explicit,
335 None, Warning, None, 1, registry=42)
336
Hirokazu Yamamotoe78e5d22009-07-17 06:20:46 +0000337 def test_bad_str(self):
338 # issue 6415
339 # Warnings instance with a bad format string for __str__ should not
340 # trigger a bus error.
341 class BadStrWarning(Warning):
342 """Warning with a bad format string for __str__."""
343 def __str__(self):
344 return ("A bad formatted string %(err)" %
345 {"err" : "there is no %(err)s"})
346
347 with self.assertRaises(ValueError):
348 self.module.warn(BadStrWarning())
349
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000350
Brett Cannon667bb4f2008-04-13 02:42:36 +0000351class CWarnTests(BaseTest, WarnTests):
Brett Cannone9746892008-04-12 23:44:07 +0000352 module = c_warnings
353
Nick Coghlancd2e7042009-04-11 13:31:31 +0000354 # As an early adopter, we sanity check the
355 # test_support.import_fresh_module utility function
356 def test_accelerated(self):
357 self.assertFalse(original_warnings is self.module)
358 self.assertFalse(hasattr(self.module.warn, 'func_code'))
359
Brett Cannon667bb4f2008-04-13 02:42:36 +0000360class PyWarnTests(BaseTest, WarnTests):
Brett Cannone9746892008-04-12 23:44:07 +0000361 module = py_warnings
362
Nick Coghlancd2e7042009-04-11 13:31:31 +0000363 # As an early adopter, we sanity check the
364 # test_support.import_fresh_module utility function
365 def test_pure_python(self):
366 self.assertFalse(original_warnings is self.module)
367 self.assertTrue(hasattr(self.module.warn, 'func_code'))
368
Brett Cannone9746892008-04-12 23:44:07 +0000369
370class WCmdLineTests(unittest.TestCase):
371
372 def test_improper_input(self):
373 # Uses the private _setoption() function to test the parsing
374 # of command-line warning arguments
Brett Cannon672237d2008-09-09 00:49:16 +0000375 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000376 self.assertRaises(self.module._OptionError,
377 self.module._setoption, '1:2:3:4:5:6')
378 self.assertRaises(self.module._OptionError,
379 self.module._setoption, 'bogus::Warning')
380 self.assertRaises(self.module._OptionError,
381 self.module._setoption, 'ignore:2::4:-5')
382 self.module._setoption('error::Warning::0')
383 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
384
Antoine Pitrou9c9e1b92010-11-10 14:03:31 +0000385 def test_improper_option(self):
386 # Same as above, but check that the message is printed out when
387 # the interpreter is executed. This also checks that options are
388 # actually parsed at all.
389 rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")
390 self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)
391
392 def test_warnings_bootstrap(self):
393 # Check that the warnings module does get loaded when -W<some option>
394 # is used (see issue #10372 for an example of silent bootstrap failure).
395 rc, out, err = assert_python_ok("-Wi", "-c",
396 "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
397 # '-Wi' was observed
398 self.assertFalse(out.strip())
399 self.assertNotIn(b'RuntimeWarning', err)
400
Brett Cannon667bb4f2008-04-13 02:42:36 +0000401class CWCmdLineTests(BaseTest, WCmdLineTests):
Brett Cannone9746892008-04-12 23:44:07 +0000402 module = c_warnings
403
Brett Cannon667bb4f2008-04-13 02:42:36 +0000404class PyWCmdLineTests(BaseTest, WCmdLineTests):
Brett Cannone9746892008-04-12 23:44:07 +0000405 module = py_warnings
406
407
Brett Cannon667bb4f2008-04-13 02:42:36 +0000408class _WarningsTests(BaseTest):
Brett Cannone9746892008-04-12 23:44:07 +0000409
410 """Tests specific to the _warnings module."""
411
412 module = c_warnings
413
414 def test_filter(self):
415 # Everything should function even if 'filters' is not in warnings.
Brett Cannon672237d2008-09-09 00:49:16 +0000416 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000417 self.module.filterwarnings("error", "", Warning, "", 0)
418 self.assertRaises(UserWarning, self.module.warn,
419 'convert to error')
420 del self.module.filters
421 self.assertRaises(UserWarning, self.module.warn,
422 'convert to error')
423
424 def test_onceregistry(self):
425 # Replacing or removing the onceregistry should be okay.
426 global __warningregistry__
427 message = UserWarning('onceregistry test')
428 try:
429 original_registry = self.module.onceregistry
430 __warningregistry__ = {}
Brett Cannon672237d2008-09-09 00:49:16 +0000431 with original_warnings.catch_warnings(record=True,
432 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000433 self.module.resetwarnings()
434 self.module.filterwarnings("once", category=UserWarning)
435 self.module.warn_explicit(message, UserWarning, "file", 42)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000436 self.assertEqual(w[-1].message, message)
Brett Cannon672237d2008-09-09 00:49:16 +0000437 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000438 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melotti2623a372010-11-21 13:34:58 +0000439 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000440 # Test the resetting of onceregistry.
441 self.module.onceregistry = {}
442 __warningregistry__ = {}
443 self.module.warn('onceregistry test')
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000444 self.assertEqual(w[-1].message.args, message.args)
Brett Cannone9746892008-04-12 23:44:07 +0000445 # Removal of onceregistry is okay.
Brett Cannon672237d2008-09-09 00:49:16 +0000446 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000447 del self.module.onceregistry
448 __warningregistry__ = {}
449 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melotti2623a372010-11-21 13:34:58 +0000450 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000451 finally:
452 self.module.onceregistry = original_registry
453
Brett Cannon15ba4da2009-04-01 18:03:59 +0000454 def test_default_action(self):
455 # Replacing or removing defaultaction should be okay.
456 message = UserWarning("defaultaction test")
457 original = self.module.defaultaction
458 try:
459 with original_warnings.catch_warnings(record=True,
460 module=self.module) as w:
461 self.module.resetwarnings()
462 registry = {}
463 self.module.warn_explicit(message, UserWarning, "<test>", 42,
464 registry=registry)
465 self.assertEqual(w[-1].message, message)
466 self.assertEqual(len(w), 1)
467 self.assertEqual(len(registry), 1)
468 del w[:]
469 # Test removal.
470 del self.module.defaultaction
471 __warningregistry__ = {}
472 registry = {}
473 self.module.warn_explicit(message, UserWarning, "<test>", 43,
474 registry=registry)
475 self.assertEqual(w[-1].message, message)
476 self.assertEqual(len(w), 1)
477 self.assertEqual(len(registry), 1)
478 del w[:]
479 # Test setting.
480 self.module.defaultaction = "ignore"
481 __warningregistry__ = {}
482 registry = {}
483 self.module.warn_explicit(message, UserWarning, "<test>", 44,
484 registry=registry)
485 self.assertEqual(len(w), 0)
486 finally:
487 self.module.defaultaction = original
488
Brett Cannone9746892008-04-12 23:44:07 +0000489 def test_showwarning_missing(self):
490 # Test that showwarning() missing is okay.
491 text = 'del showwarning test'
Brett Cannon672237d2008-09-09 00:49:16 +0000492 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000493 self.module.filterwarnings("always", category=UserWarning)
494 del self.module.showwarning
495 with test_support.captured_output('stderr') as stream:
496 self.module.warn(text)
497 result = stream.getvalue()
Ezio Melottiaa980582010-01-23 23:04:36 +0000498 self.assertIn(text, result)
Brett Cannone9746892008-04-12 23:44:07 +0000499
Benjamin Petersond2950322008-05-06 22:18:11 +0000500 def test_showwarning_not_callable(self):
Brett Cannonce3d2212009-04-01 20:25:48 +0000501 with original_warnings.catch_warnings(module=self.module):
502 self.module.filterwarnings("always", category=UserWarning)
503 old_showwarning = self.module.showwarning
504 self.module.showwarning = 23
505 try:
506 self.assertRaises(TypeError, self.module.warn, "Warning!")
507 finally:
508 self.module.showwarning = old_showwarning
Benjamin Petersond2950322008-05-06 22:18:11 +0000509
Brett Cannone9746892008-04-12 23:44:07 +0000510 def test_show_warning_output(self):
511 # With showarning() missing, make sure that output is okay.
512 text = 'test show_warning'
Brett Cannon672237d2008-09-09 00:49:16 +0000513 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000514 self.module.filterwarnings("always", category=UserWarning)
515 del self.module.showwarning
516 with test_support.captured_output('stderr') as stream:
517 warning_tests.inner(text)
518 result = stream.getvalue()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000519 self.assertEqual(result.count('\n'), 2,
Brett Cannone9746892008-04-12 23:44:07 +0000520 "Too many newlines in %r" % result)
521 first_line, second_line = result.split('\n', 1)
522 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Brett Cannonc4774272008-04-13 17:41:31 +0000523 first_line_parts = first_line.rsplit(':', 3)
Brett Cannon25bb8182008-04-13 17:09:43 +0000524 path, line, warning_class, message = first_line_parts
Brett Cannone9746892008-04-12 23:44:07 +0000525 line = int(line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000526 self.assertEqual(expected_file, path)
527 self.assertEqual(warning_class, ' ' + UserWarning.__name__)
528 self.assertEqual(message, ' ' + text)
Brett Cannone9746892008-04-12 23:44:07 +0000529 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
530 assert expected_line
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000531 self.assertEqual(second_line, expected_line)
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000532
Victor Stinner65c15352011-07-04 03:05:37 +0200533 def test_filename_none(self):
534 # issue #12467: race condition if a warning is emitted at shutdown
535 globals_dict = globals()
536 oldfile = globals_dict['__file__']
537 try:
538 with original_warnings.catch_warnings(module=self.module) as w:
539 self.module.filterwarnings("always", category=UserWarning)
540 globals_dict['__file__'] = None
541 self.module.warn('test', UserWarning)
542 finally:
543 globals_dict['__file__'] = oldfile
544
Brett Cannon53ab5b72006-06-22 16:49:14 +0000545
Brett Cannon905c31c2007-12-20 10:09:52 +0000546class WarningsDisplayTests(unittest.TestCase):
547
Brett Cannone9746892008-04-12 23:44:07 +0000548 """Test the displaying of warnings and the ability to overload functions
549 related to displaying warnings."""
550
Brett Cannon905c31c2007-12-20 10:09:52 +0000551 def test_formatwarning(self):
552 message = "msg"
553 category = Warning
554 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
555 line_num = 3
556 file_line = linecache.getline(file_name, line_num).strip()
Brett Cannone9746892008-04-12 23:44:07 +0000557 format = "%s:%s: %s: %s\n %s\n"
558 expect = format % (file_name, line_num, category.__name__, message,
559 file_line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000560 self.assertEqual(expect, self.module.formatwarning(message,
Brett Cannone9746892008-04-12 23:44:07 +0000561 category, file_name, line_num))
562 # Test the 'line' argument.
563 file_line += " for the win!"
564 expect = format % (file_name, line_num, category.__name__, message,
565 file_line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000566 self.assertEqual(expect, self.module.formatwarning(message,
Brett Cannone9746892008-04-12 23:44:07 +0000567 category, file_name, line_num, file_line))
Brett Cannon905c31c2007-12-20 10:09:52 +0000568
569 def test_showwarning(self):
570 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
571 line_num = 3
572 expected_file_line = linecache.getline(file_name, line_num).strip()
573 message = 'msg'
574 category = Warning
575 file_object = StringIO.StringIO()
Brett Cannone9746892008-04-12 23:44:07 +0000576 expect = self.module.formatwarning(message, category, file_name,
577 line_num)
578 self.module.showwarning(message, category, file_name, line_num,
Brett Cannon905c31c2007-12-20 10:09:52 +0000579 file_object)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000580 self.assertEqual(file_object.getvalue(), expect)
Brett Cannone9746892008-04-12 23:44:07 +0000581 # Test 'line' argument.
582 expected_file_line += "for the win!"
583 expect = self.module.formatwarning(message, category, file_name,
584 line_num, expected_file_line)
585 file_object = StringIO.StringIO()
586 self.module.showwarning(message, category, file_name, line_num,
587 file_object, expected_file_line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000588 self.assertEqual(expect, file_object.getvalue())
Brett Cannone9746892008-04-12 23:44:07 +0000589
Brett Cannon667bb4f2008-04-13 02:42:36 +0000590class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
Brett Cannone9746892008-04-12 23:44:07 +0000591 module = c_warnings
592
Brett Cannon667bb4f2008-04-13 02:42:36 +0000593class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
Brett Cannone9746892008-04-12 23:44:07 +0000594 module = py_warnings
Brett Cannon905c31c2007-12-20 10:09:52 +0000595
596
Brett Cannon1eaf0742008-09-02 01:25:16 +0000597class CatchWarningTests(BaseTest):
Nick Coghlan38469e22008-07-13 12:23:47 +0000598
Brett Cannon1eaf0742008-09-02 01:25:16 +0000599 """Test catch_warnings()."""
600
601 def test_catch_warnings_restore(self):
Nick Coghlan38469e22008-07-13 12:23:47 +0000602 wmod = self.module
603 orig_filters = wmod.filters
604 orig_showwarning = wmod.showwarning
Nick Coghland2e09382008-09-11 12:11:06 +0000605 # Ensure both showwarning and filters are restored when recording
606 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlan38469e22008-07-13 12:23:47 +0000607 wmod.filters = wmod.showwarning = object()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000608 self.assertTrue(wmod.filters is orig_filters)
609 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghland2e09382008-09-11 12:11:06 +0000610 # Same test, but with recording disabled
Brett Cannon1eaf0742008-09-02 01:25:16 +0000611 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlan38469e22008-07-13 12:23:47 +0000612 wmod.filters = wmod.showwarning = object()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000613 self.assertTrue(wmod.filters is orig_filters)
614 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlan38469e22008-07-13 12:23:47 +0000615
Brett Cannon1eaf0742008-09-02 01:25:16 +0000616 def test_catch_warnings_recording(self):
Nick Coghlan38469e22008-07-13 12:23:47 +0000617 wmod = self.module
Nick Coghland2e09382008-09-11 12:11:06 +0000618 # Ensure warnings are recorded when requested
Brett Cannon1eaf0742008-09-02 01:25:16 +0000619 with wmod.catch_warnings(module=wmod, record=True) as w:
620 self.assertEqual(w, [])
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000621 self.assertTrue(type(w) is list)
Nick Coghlan38469e22008-07-13 12:23:47 +0000622 wmod.simplefilter("always")
623 wmod.warn("foo")
Brett Cannon672237d2008-09-09 00:49:16 +0000624 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlan38469e22008-07-13 12:23:47 +0000625 wmod.warn("bar")
Brett Cannon672237d2008-09-09 00:49:16 +0000626 self.assertEqual(str(w[-1].message), "bar")
Brett Cannon1eaf0742008-09-02 01:25:16 +0000627 self.assertEqual(str(w[0].message), "foo")
628 self.assertEqual(str(w[1].message), "bar")
Brett Cannon672237d2008-09-09 00:49:16 +0000629 del w[:]
Brett Cannon1eaf0742008-09-02 01:25:16 +0000630 self.assertEqual(w, [])
Nick Coghland2e09382008-09-11 12:11:06 +0000631 # Ensure warnings are not recorded when not requested
Nick Coghlan38469e22008-07-13 12:23:47 +0000632 orig_showwarning = wmod.showwarning
Brett Cannon1eaf0742008-09-02 01:25:16 +0000633 with wmod.catch_warnings(module=wmod, record=False) as w:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000634 self.assertTrue(w is None)
635 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlan38469e22008-07-13 12:23:47 +0000636
Nick Coghland2e09382008-09-11 12:11:06 +0000637 def test_catch_warnings_reentry_guard(self):
638 wmod = self.module
639 # Ensure catch_warnings is protected against incorrect usage
640 x = wmod.catch_warnings(module=wmod, record=True)
641 self.assertRaises(RuntimeError, x.__exit__)
642 with x:
643 self.assertRaises(RuntimeError, x.__enter__)
644 # Same test, but with recording disabled
645 x = wmod.catch_warnings(module=wmod, record=False)
646 self.assertRaises(RuntimeError, x.__exit__)
647 with x:
648 self.assertRaises(RuntimeError, x.__enter__)
649
650 def test_catch_warnings_defaults(self):
651 wmod = self.module
652 orig_filters = wmod.filters
653 orig_showwarning = wmod.showwarning
654 # Ensure default behaviour is not to record warnings
655 with wmod.catch_warnings(module=wmod) as w:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000656 self.assertTrue(w is None)
657 self.assertTrue(wmod.showwarning is orig_showwarning)
658 self.assertTrue(wmod.filters is not orig_filters)
659 self.assertTrue(wmod.filters is orig_filters)
Nick Coghland2e09382008-09-11 12:11:06 +0000660 if wmod is sys.modules['warnings']:
661 # Ensure the default module is this one
662 with wmod.catch_warnings() as w:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000663 self.assertTrue(w is None)
664 self.assertTrue(wmod.showwarning is orig_showwarning)
665 self.assertTrue(wmod.filters is not orig_filters)
666 self.assertTrue(wmod.filters is orig_filters)
Nick Coghland2e09382008-09-11 12:11:06 +0000667
668 def test_check_warnings(self):
669 # Explicit tests for the test_support convenience wrapper
670 wmod = self.module
Florent Xicluna73588542010-03-18 19:51:47 +0000671 if wmod is not sys.modules['warnings']:
672 return
673 with test_support.check_warnings(quiet=False) as w:
674 self.assertEqual(w.warnings, [])
675 wmod.simplefilter("always")
676 wmod.warn("foo")
677 self.assertEqual(str(w.message), "foo")
678 wmod.warn("bar")
679 self.assertEqual(str(w.message), "bar")
680 self.assertEqual(str(w.warnings[0].message), "foo")
681 self.assertEqual(str(w.warnings[1].message), "bar")
682 w.reset()
683 self.assertEqual(w.warnings, [])
Nick Coghland2e09382008-09-11 12:11:06 +0000684
Florent Xicluna73588542010-03-18 19:51:47 +0000685 with test_support.check_warnings():
686 # defaults to quiet=True without argument
687 pass
688 with test_support.check_warnings(('foo', UserWarning)):
689 wmod.warn("foo")
690
691 with self.assertRaises(AssertionError):
692 with test_support.check_warnings(('', RuntimeWarning)):
693 # defaults to quiet=False with argument
694 pass
695 with self.assertRaises(AssertionError):
696 with test_support.check_warnings(('foo', RuntimeWarning)):
697 wmod.warn("foo")
Nick Coghland2e09382008-09-11 12:11:06 +0000698
699
Brett Cannon1eaf0742008-09-02 01:25:16 +0000700class CCatchWarningTests(CatchWarningTests):
Nick Coghlan38469e22008-07-13 12:23:47 +0000701 module = c_warnings
702
Brett Cannon1eaf0742008-09-02 01:25:16 +0000703class PyCatchWarningTests(CatchWarningTests):
Nick Coghlan38469e22008-07-13 12:23:47 +0000704 module = py_warnings
705
706
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000707class EnvironmentVariableTests(BaseTest):
708
709 def test_single_warning(self):
710 newenv = os.environ.copy()
711 newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
712 p = subprocess.Popen([sys.executable,
713 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
714 stdout=subprocess.PIPE, env=newenv)
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000715 self.assertEqual(p.communicate()[0], "['ignore::DeprecationWarning']")
716 self.assertEqual(p.wait(), 0)
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000717
718 def test_comma_separated_warnings(self):
719 newenv = os.environ.copy()
720 newenv["PYTHONWARNINGS"] = ("ignore::DeprecationWarning,"
721 "ignore::UnicodeWarning")
722 p = subprocess.Popen([sys.executable,
723 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
724 stdout=subprocess.PIPE, env=newenv)
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000725 self.assertEqual(p.communicate()[0],
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000726 "['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000727 self.assertEqual(p.wait(), 0)
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000728
729 def test_envvar_and_command_line(self):
730 newenv = os.environ.copy()
731 newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
732 p = subprocess.Popen([sys.executable, "-W" "ignore::UnicodeWarning",
733 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
734 stdout=subprocess.PIPE, env=newenv)
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000735 self.assertEqual(p.communicate()[0],
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000736 "['ignore::UnicodeWarning', 'ignore::DeprecationWarning']")
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000737 self.assertEqual(p.wait(), 0)
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000738
739class CEnvironmentVariableTests(EnvironmentVariableTests):
740 module = c_warnings
741
742class PyEnvironmentVariableTests(EnvironmentVariableTests):
743 module = py_warnings
744
745
Brett Cannone9746892008-04-12 23:44:07 +0000746def test_main():
Amaury Forgeot d'Arc607bff12008-04-18 23:31:33 +0000747 py_warnings.onceregistry.clear()
748 c_warnings.onceregistry.clear()
Brett Cannon1eaf0742008-09-02 01:25:16 +0000749 test_support.run_unittest(CFilterTests, PyFilterTests,
750 CWarnTests, PyWarnTests,
Brett Cannone9746892008-04-12 23:44:07 +0000751 CWCmdLineTests, PyWCmdLineTests,
752 _WarningsTests,
753 CWarningsDisplayTests, PyWarningsDisplayTests,
Brett Cannon1eaf0742008-09-02 01:25:16 +0000754 CCatchWarningTests, PyCatchWarningTests,
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000755 CEnvironmentVariableTests,
756 PyEnvironmentVariableTests
Brett Cannone9746892008-04-12 23:44:07 +0000757 )
758
759
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000760if __name__ == "__main__":
Brett Cannone9746892008-04-12 23:44:07 +0000761 test_main()