blob: 7a9459a47e2b39f6276ac7720dc29888c28b1904 [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
Brett Cannon01408452014-08-22 10:50:47 -040065class PublicAPITests(BaseTest):
66
67 """Ensures that the correct values are exposed in the
68 public API.
69 """
70
71 def test_module_all_attribute(self):
72 self.assertTrue(hasattr(self.module, '__all__'))
73 target_api = ["warn", "warn_explicit", "showwarning",
74 "formatwarning", "filterwarnings", "simplefilter",
75 "resetwarnings", "catch_warnings"]
76 self.assertSetEqual(set(self.module.__all__),
77 set(target_api))
78
79class CPublicAPITests(PublicAPITests, unittest.TestCase):
80 module = c_warnings
81
82class PyPublicAPITests(PublicAPITests, unittest.TestCase):
83 module = py_warnings
Brett Cannon667bb4f2008-04-13 02:42:36 +000084
85class FilterTests(object):
86
87 """Testing the filtering functionality."""
Brett Cannone9746892008-04-12 23:44:07 +000088
89 def test_error(self):
Brett Cannon672237d2008-09-09 00:49:16 +000090 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +000091 self.module.resetwarnings()
92 self.module.filterwarnings("error", category=UserWarning)
93 self.assertRaises(UserWarning, self.module.warn,
94 "FilterTests.test_error")
95
96 def test_ignore(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("ignore", category=UserWarning)
101 self.module.warn("FilterTests.test_ignore", UserWarning)
Ezio Melotti2623a372010-11-21 13:34:58 +0000102 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000103
104 def test_always(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000105 with original_warnings.catch_warnings(record=True,
106 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000107 self.module.resetwarnings()
108 self.module.filterwarnings("always", category=UserWarning)
109 message = "FilterTests.test_always"
110 self.module.warn(message, UserWarning)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000111 self.assertTrue(message, w[-1].message)
Brett Cannone9746892008-04-12 23:44:07 +0000112 self.module.warn(message, UserWarning)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000113 self.assertTrue(w[-1].message, message)
Brett Cannone9746892008-04-12 23:44:07 +0000114
115 def test_default(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000116 with original_warnings.catch_warnings(record=True,
117 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000118 self.module.resetwarnings()
119 self.module.filterwarnings("default", category=UserWarning)
120 message = UserWarning("FilterTests.test_default")
121 for x in xrange(2):
122 self.module.warn(message, UserWarning)
123 if x == 0:
Ezio Melotti2623a372010-11-21 13:34:58 +0000124 self.assertEqual(w[-1].message, message)
Brett Cannon672237d2008-09-09 00:49:16 +0000125 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000126 elif x == 1:
Ezio Melotti2623a372010-11-21 13:34:58 +0000127 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000128 else:
129 raise ValueError("loop variant unhandled")
130
131 def test_module(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000132 with original_warnings.catch_warnings(record=True,
133 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000134 self.module.resetwarnings()
135 self.module.filterwarnings("module", category=UserWarning)
136 message = UserWarning("FilterTests.test_module")
137 self.module.warn(message, UserWarning)
Ezio Melotti2623a372010-11-21 13:34:58 +0000138 self.assertEqual(w[-1].message, message)
Brett Cannon672237d2008-09-09 00:49:16 +0000139 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000140 self.module.warn(message, UserWarning)
Ezio Melotti2623a372010-11-21 13:34:58 +0000141 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000142
143 def test_once(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000144 with original_warnings.catch_warnings(record=True,
145 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000146 self.module.resetwarnings()
147 self.module.filterwarnings("once", category=UserWarning)
148 message = UserWarning("FilterTests.test_once")
149 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
150 42)
Ezio Melotti2623a372010-11-21 13:34:58 +0000151 self.assertEqual(w[-1].message, message)
Brett Cannon672237d2008-09-09 00:49:16 +0000152 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000153 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
154 13)
Ezio Melotti2623a372010-11-21 13:34:58 +0000155 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000156 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
157 42)
Ezio Melotti2623a372010-11-21 13:34:58 +0000158 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000159
160 def test_inheritance(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000161 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000162 self.module.resetwarnings()
163 self.module.filterwarnings("error", category=Warning)
164 self.assertRaises(UserWarning, self.module.warn,
165 "FilterTests.test_inheritance", UserWarning)
166
167 def test_ordering(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000168 with original_warnings.catch_warnings(record=True,
169 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000170 self.module.resetwarnings()
171 self.module.filterwarnings("ignore", category=UserWarning)
172 self.module.filterwarnings("error", category=UserWarning,
173 append=True)
Brett Cannon672237d2008-09-09 00:49:16 +0000174 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000175 try:
176 self.module.warn("FilterTests.test_ordering", UserWarning)
177 except UserWarning:
178 self.fail("order handling for actions failed")
Ezio Melotti2623a372010-11-21 13:34:58 +0000179 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000180
181 def test_filterwarnings(self):
182 # Test filterwarnings().
183 # Implicitly also tests resetwarnings().
Brett Cannon672237d2008-09-09 00:49:16 +0000184 with original_warnings.catch_warnings(record=True,
185 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000186 self.module.filterwarnings("error", "", Warning, "", 0)
187 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
188
189 self.module.resetwarnings()
190 text = 'handle normally'
191 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000192 self.assertEqual(str(w[-1].message), text)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000193 self.assertTrue(w[-1].category is UserWarning)
Brett Cannone9746892008-04-12 23:44:07 +0000194
195 self.module.filterwarnings("ignore", "", Warning, "", 0)
196 text = 'filtered out'
197 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000198 self.assertNotEqual(str(w[-1].message), text)
Brett Cannone9746892008-04-12 23:44:07 +0000199
200 self.module.resetwarnings()
201 self.module.filterwarnings("error", "hex*", Warning, "", 0)
202 self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
203 text = 'nonmatching text'
204 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000205 self.assertEqual(str(w[-1].message), text)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000206 self.assertTrue(w[-1].category is UserWarning)
Brett Cannone9746892008-04-12 23:44:07 +0000207
Brett Cannon667bb4f2008-04-13 02:42:36 +0000208class CFilterTests(BaseTest, FilterTests):
Brett Cannone9746892008-04-12 23:44:07 +0000209 module = c_warnings
210
Brett Cannon667bb4f2008-04-13 02:42:36 +0000211class PyFilterTests(BaseTest, FilterTests):
Brett Cannone9746892008-04-12 23:44:07 +0000212 module = py_warnings
213
214
215class WarnTests(unittest.TestCase):
216
217 """Test warnings.warn() and warnings.warn_explicit()."""
218
219 def test_message(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000220 with original_warnings.catch_warnings(record=True,
221 module=self.module) as w:
Florent Xiclunafd37dd42010-03-25 20:39:10 +0000222 self.module.simplefilter("once")
Walter Dörwalde6dae6c2007-04-03 18:33:29 +0000223 for i in range(4):
Brett Cannone9746892008-04-12 23:44:07 +0000224 text = 'multi %d' %i # Different text on each call.
225 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000226 self.assertEqual(str(w[-1].message), text)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000227 self.assertTrue(w[-1].category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000228
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000229 def test_filename(self):
Brett Cannone9746892008-04-12 23:44:07 +0000230 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000231 with original_warnings.catch_warnings(record=True,
232 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000233 warning_tests.inner("spam1")
Brett Cannon672237d2008-09-09 00:49:16 +0000234 self.assertEqual(os.path.basename(w[-1].filename),
235 "warning_tests.py")
Brett Cannone9746892008-04-12 23:44:07 +0000236 warning_tests.outer("spam2")
Brett Cannon672237d2008-09-09 00:49:16 +0000237 self.assertEqual(os.path.basename(w[-1].filename),
238 "warning_tests.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000239
240 def test_stacklevel(self):
241 # Test stacklevel argument
242 # make sure all messages are different, so the warning won't be skipped
Brett Cannone9746892008-04-12 23:44:07 +0000243 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000244 with original_warnings.catch_warnings(record=True,
245 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000246 warning_tests.inner("spam3", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000247 self.assertEqual(os.path.basename(w[-1].filename),
248 "warning_tests.py")
Brett Cannone9746892008-04-12 23:44:07 +0000249 warning_tests.outer("spam4", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000250 self.assertEqual(os.path.basename(w[-1].filename),
251 "warning_tests.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000252
Brett Cannone9746892008-04-12 23:44:07 +0000253 warning_tests.inner("spam5", stacklevel=2)
Brett Cannon672237d2008-09-09 00:49:16 +0000254 self.assertEqual(os.path.basename(w[-1].filename),
255 "test_warnings.py")
Brett Cannone9746892008-04-12 23:44:07 +0000256 warning_tests.outer("spam6", stacklevel=2)
Brett Cannon672237d2008-09-09 00:49:16 +0000257 self.assertEqual(os.path.basename(w[-1].filename),
258 "warning_tests.py")
Brett Cannone3dcb012008-05-06 04:37:31 +0000259 warning_tests.outer("spam6.5", stacklevel=3)
Brett Cannon672237d2008-09-09 00:49:16 +0000260 self.assertEqual(os.path.basename(w[-1].filename),
261 "test_warnings.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000262
Brett Cannone9746892008-04-12 23:44:07 +0000263 warning_tests.inner("spam7", stacklevel=9999)
Brett Cannon672237d2008-09-09 00:49:16 +0000264 self.assertEqual(os.path.basename(w[-1].filename),
265 "sys")
Brett Cannone9746892008-04-12 23:44:07 +0000266
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000267 def test_missing_filename_not_main(self):
268 # If __file__ is not specified and __main__ is not the module name,
269 # then __file__ should be set to the module name.
270 filename = warning_tests.__file__
271 try:
272 del warning_tests.__file__
273 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000274 with original_warnings.catch_warnings(record=True,
275 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000276 warning_tests.inner("spam8", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000277 self.assertEqual(w[-1].filename, warning_tests.__name__)
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000278 finally:
279 warning_tests.__file__ = filename
280
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200281 @unittest.skipUnless(hasattr(sys, 'argv'), 'test needs sys.argv')
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000282 def test_missing_filename_main_with_argv(self):
283 # If __file__ is not specified and the caller is __main__ and sys.argv
284 # exists, then use sys.argv[0] as the file.
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000285 filename = warning_tests.__file__
286 module_name = warning_tests.__name__
287 try:
288 del warning_tests.__file__
289 warning_tests.__name__ = '__main__'
290 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000291 with original_warnings.catch_warnings(record=True,
292 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000293 warning_tests.inner('spam9', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000294 self.assertEqual(w[-1].filename, sys.argv[0])
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000295 finally:
296 warning_tests.__file__ = filename
297 warning_tests.__name__ = module_name
298
299 def test_missing_filename_main_without_argv(self):
300 # If __file__ is not specified, the caller is __main__, and sys.argv
301 # is not set, then '__main__' is the file name.
302 filename = warning_tests.__file__
303 module_name = warning_tests.__name__
304 argv = sys.argv
305 try:
306 del warning_tests.__file__
307 warning_tests.__name__ = '__main__'
308 del sys.argv
309 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000310 with original_warnings.catch_warnings(record=True,
311 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000312 warning_tests.inner('spam10', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000313 self.assertEqual(w[-1].filename, '__main__')
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000314 finally:
315 warning_tests.__file__ = filename
316 warning_tests.__name__ = module_name
317 sys.argv = argv
318
319 def test_missing_filename_main_with_argv_empty_string(self):
320 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
321 # is the empty string, then '__main__ is the file name.
322 # Tests issue 2743.
323 file_name = warning_tests.__file__
324 module_name = warning_tests.__name__
325 argv = sys.argv
326 try:
327 del warning_tests.__file__
328 warning_tests.__name__ = '__main__'
329 sys.argv = ['']
330 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000331 with original_warnings.catch_warnings(record=True,
332 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000333 warning_tests.inner('spam11', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000334 self.assertEqual(w[-1].filename, '__main__')
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000335 finally:
336 warning_tests.__file__ = file_name
337 warning_tests.__name__ = module_name
338 sys.argv = argv
339
Brett Cannondea1b562008-06-27 00:31:13 +0000340 def test_warn_explicit_type_errors(self):
Ezio Melottic2077b02011-03-16 12:34:31 +0200341 # warn_explicit() should error out gracefully if it is given objects
Brett Cannondea1b562008-06-27 00:31:13 +0000342 # of the wrong types.
343 # lineno is expected to be an integer.
344 self.assertRaises(TypeError, self.module.warn_explicit,
345 None, UserWarning, None, None)
346 # Either 'message' needs to be an instance of Warning or 'category'
347 # needs to be a subclass.
348 self.assertRaises(TypeError, self.module.warn_explicit,
349 None, None, None, 1)
350 # 'registry' must be a dict or None.
351 self.assertRaises((TypeError, AttributeError),
352 self.module.warn_explicit,
353 None, Warning, None, 1, registry=42)
354
Hirokazu Yamamotoe78e5d22009-07-17 06:20:46 +0000355 def test_bad_str(self):
356 # issue 6415
357 # Warnings instance with a bad format string for __str__ should not
358 # trigger a bus error.
359 class BadStrWarning(Warning):
360 """Warning with a bad format string for __str__."""
361 def __str__(self):
362 return ("A bad formatted string %(err)" %
363 {"err" : "there is no %(err)s"})
364
365 with self.assertRaises(ValueError):
366 self.module.warn(BadStrWarning())
367
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000368
Brett Cannon667bb4f2008-04-13 02:42:36 +0000369class CWarnTests(BaseTest, WarnTests):
Brett Cannone9746892008-04-12 23:44:07 +0000370 module = c_warnings
371
Nick Coghlancd2e7042009-04-11 13:31:31 +0000372 # As an early adopter, we sanity check the
373 # test_support.import_fresh_module utility function
374 def test_accelerated(self):
375 self.assertFalse(original_warnings is self.module)
376 self.assertFalse(hasattr(self.module.warn, 'func_code'))
377
Brett Cannon667bb4f2008-04-13 02:42:36 +0000378class PyWarnTests(BaseTest, WarnTests):
Brett Cannone9746892008-04-12 23:44:07 +0000379 module = py_warnings
380
Nick Coghlancd2e7042009-04-11 13:31:31 +0000381 # As an early adopter, we sanity check the
382 # test_support.import_fresh_module utility function
383 def test_pure_python(self):
384 self.assertFalse(original_warnings is self.module)
385 self.assertTrue(hasattr(self.module.warn, 'func_code'))
386
Brett Cannone9746892008-04-12 23:44:07 +0000387
388class WCmdLineTests(unittest.TestCase):
389
390 def test_improper_input(self):
391 # Uses the private _setoption() function to test the parsing
392 # of command-line warning arguments
Brett Cannon672237d2008-09-09 00:49:16 +0000393 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000394 self.assertRaises(self.module._OptionError,
395 self.module._setoption, '1:2:3:4:5:6')
396 self.assertRaises(self.module._OptionError,
397 self.module._setoption, 'bogus::Warning')
398 self.assertRaises(self.module._OptionError,
399 self.module._setoption, 'ignore:2::4:-5')
400 self.module._setoption('error::Warning::0')
401 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
402
Antoine Pitrou9c9e1b92010-11-10 14:03:31 +0000403 def test_improper_option(self):
404 # Same as above, but check that the message is printed out when
405 # the interpreter is executed. This also checks that options are
406 # actually parsed at all.
407 rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")
408 self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)
409
410 def test_warnings_bootstrap(self):
411 # Check that the warnings module does get loaded when -W<some option>
412 # is used (see issue #10372 for an example of silent bootstrap failure).
413 rc, out, err = assert_python_ok("-Wi", "-c",
414 "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
415 # '-Wi' was observed
416 self.assertFalse(out.strip())
417 self.assertNotIn(b'RuntimeWarning', err)
418
Brett Cannon667bb4f2008-04-13 02:42:36 +0000419class CWCmdLineTests(BaseTest, WCmdLineTests):
Brett Cannone9746892008-04-12 23:44:07 +0000420 module = c_warnings
421
Brett Cannon667bb4f2008-04-13 02:42:36 +0000422class PyWCmdLineTests(BaseTest, WCmdLineTests):
Brett Cannone9746892008-04-12 23:44:07 +0000423 module = py_warnings
424
425
Brett Cannon667bb4f2008-04-13 02:42:36 +0000426class _WarningsTests(BaseTest):
Brett Cannone9746892008-04-12 23:44:07 +0000427
428 """Tests specific to the _warnings module."""
429
430 module = c_warnings
431
432 def test_filter(self):
433 # Everything should function even if 'filters' is not in warnings.
Brett Cannon672237d2008-09-09 00:49:16 +0000434 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000435 self.module.filterwarnings("error", "", Warning, "", 0)
436 self.assertRaises(UserWarning, self.module.warn,
437 'convert to error')
438 del self.module.filters
439 self.assertRaises(UserWarning, self.module.warn,
440 'convert to error')
441
442 def test_onceregistry(self):
443 # Replacing or removing the onceregistry should be okay.
444 global __warningregistry__
445 message = UserWarning('onceregistry test')
446 try:
447 original_registry = self.module.onceregistry
448 __warningregistry__ = {}
Brett Cannon672237d2008-09-09 00:49:16 +0000449 with original_warnings.catch_warnings(record=True,
450 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000451 self.module.resetwarnings()
452 self.module.filterwarnings("once", category=UserWarning)
453 self.module.warn_explicit(message, UserWarning, "file", 42)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000454 self.assertEqual(w[-1].message, message)
Brett Cannon672237d2008-09-09 00:49:16 +0000455 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000456 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melotti2623a372010-11-21 13:34:58 +0000457 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000458 # Test the resetting of onceregistry.
459 self.module.onceregistry = {}
460 __warningregistry__ = {}
461 self.module.warn('onceregistry test')
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000462 self.assertEqual(w[-1].message.args, message.args)
Brett Cannone9746892008-04-12 23:44:07 +0000463 # Removal of onceregistry is okay.
Brett Cannon672237d2008-09-09 00:49:16 +0000464 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000465 del self.module.onceregistry
466 __warningregistry__ = {}
467 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melotti2623a372010-11-21 13:34:58 +0000468 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000469 finally:
470 self.module.onceregistry = original_registry
471
Brett Cannon15ba4da2009-04-01 18:03:59 +0000472 def test_default_action(self):
473 # Replacing or removing defaultaction should be okay.
474 message = UserWarning("defaultaction test")
475 original = self.module.defaultaction
476 try:
477 with original_warnings.catch_warnings(record=True,
478 module=self.module) as w:
479 self.module.resetwarnings()
480 registry = {}
481 self.module.warn_explicit(message, UserWarning, "<test>", 42,
482 registry=registry)
483 self.assertEqual(w[-1].message, message)
484 self.assertEqual(len(w), 1)
485 self.assertEqual(len(registry), 1)
486 del w[:]
487 # Test removal.
488 del self.module.defaultaction
489 __warningregistry__ = {}
490 registry = {}
491 self.module.warn_explicit(message, UserWarning, "<test>", 43,
492 registry=registry)
493 self.assertEqual(w[-1].message, message)
494 self.assertEqual(len(w), 1)
495 self.assertEqual(len(registry), 1)
496 del w[:]
497 # Test setting.
498 self.module.defaultaction = "ignore"
499 __warningregistry__ = {}
500 registry = {}
501 self.module.warn_explicit(message, UserWarning, "<test>", 44,
502 registry=registry)
503 self.assertEqual(len(w), 0)
504 finally:
505 self.module.defaultaction = original
506
Brett Cannone9746892008-04-12 23:44:07 +0000507 def test_showwarning_missing(self):
508 # Test that showwarning() missing is okay.
509 text = 'del showwarning test'
Brett Cannon672237d2008-09-09 00:49:16 +0000510 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000511 self.module.filterwarnings("always", category=UserWarning)
512 del self.module.showwarning
513 with test_support.captured_output('stderr') as stream:
514 self.module.warn(text)
515 result = stream.getvalue()
Ezio Melottiaa980582010-01-23 23:04:36 +0000516 self.assertIn(text, result)
Brett Cannone9746892008-04-12 23:44:07 +0000517
Benjamin Petersond2950322008-05-06 22:18:11 +0000518 def test_showwarning_not_callable(self):
Brett Cannonce3d2212009-04-01 20:25:48 +0000519 with original_warnings.catch_warnings(module=self.module):
520 self.module.filterwarnings("always", category=UserWarning)
521 old_showwarning = self.module.showwarning
522 self.module.showwarning = 23
523 try:
524 self.assertRaises(TypeError, self.module.warn, "Warning!")
525 finally:
526 self.module.showwarning = old_showwarning
Benjamin Petersond2950322008-05-06 22:18:11 +0000527
Brett Cannone9746892008-04-12 23:44:07 +0000528 def test_show_warning_output(self):
529 # With showarning() missing, make sure that output is okay.
530 text = 'test show_warning'
Brett Cannon672237d2008-09-09 00:49:16 +0000531 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000532 self.module.filterwarnings("always", category=UserWarning)
533 del self.module.showwarning
534 with test_support.captured_output('stderr') as stream:
535 warning_tests.inner(text)
536 result = stream.getvalue()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000537 self.assertEqual(result.count('\n'), 2,
Brett Cannone9746892008-04-12 23:44:07 +0000538 "Too many newlines in %r" % result)
539 first_line, second_line = result.split('\n', 1)
540 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Brett Cannonc4774272008-04-13 17:41:31 +0000541 first_line_parts = first_line.rsplit(':', 3)
Brett Cannon25bb8182008-04-13 17:09:43 +0000542 path, line, warning_class, message = first_line_parts
Brett Cannone9746892008-04-12 23:44:07 +0000543 line = int(line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000544 self.assertEqual(expected_file, path)
545 self.assertEqual(warning_class, ' ' + UserWarning.__name__)
546 self.assertEqual(message, ' ' + text)
Brett Cannone9746892008-04-12 23:44:07 +0000547 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
548 assert expected_line
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000549 self.assertEqual(second_line, expected_line)
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000550
Victor Stinner65c15352011-07-04 03:05:37 +0200551 def test_filename_none(self):
552 # issue #12467: race condition if a warning is emitted at shutdown
553 globals_dict = globals()
554 oldfile = globals_dict['__file__']
555 try:
556 with original_warnings.catch_warnings(module=self.module) as w:
557 self.module.filterwarnings("always", category=UserWarning)
558 globals_dict['__file__'] = None
559 self.module.warn('test', UserWarning)
560 finally:
561 globals_dict['__file__'] = oldfile
562
Serhiy Storchakae6b42432014-12-10 23:05:33 +0200563 def test_stderr_none(self):
564 rc, stdout, stderr = assert_python_ok("-c",
565 "import sys; sys.stderr = None; "
566 "import warnings; warnings.simplefilter('always'); "
567 "warnings.warn('Warning!')")
568 self.assertEqual(stdout, b'')
569 self.assertNotIn(b'Warning!', stderr)
570 self.assertNotIn(b'Error', stderr)
571
Brett Cannon53ab5b72006-06-22 16:49:14 +0000572
Brett Cannon905c31c2007-12-20 10:09:52 +0000573class WarningsDisplayTests(unittest.TestCase):
574
Brett Cannone9746892008-04-12 23:44:07 +0000575 """Test the displaying of warnings and the ability to overload functions
576 related to displaying warnings."""
577
Brett Cannon905c31c2007-12-20 10:09:52 +0000578 def test_formatwarning(self):
579 message = "msg"
580 category = Warning
581 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
582 line_num = 3
583 file_line = linecache.getline(file_name, line_num).strip()
Brett Cannone9746892008-04-12 23:44:07 +0000584 format = "%s:%s: %s: %s\n %s\n"
585 expect = format % (file_name, line_num, category.__name__, message,
586 file_line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000587 self.assertEqual(expect, self.module.formatwarning(message,
Brett Cannone9746892008-04-12 23:44:07 +0000588 category, file_name, line_num))
589 # Test the 'line' argument.
590 file_line += " for the win!"
591 expect = format % (file_name, line_num, category.__name__, message,
592 file_line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000593 self.assertEqual(expect, self.module.formatwarning(message,
Brett Cannone9746892008-04-12 23:44:07 +0000594 category, file_name, line_num, file_line))
Brett Cannon905c31c2007-12-20 10:09:52 +0000595
596 def test_showwarning(self):
597 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
598 line_num = 3
599 expected_file_line = linecache.getline(file_name, line_num).strip()
600 message = 'msg'
601 category = Warning
602 file_object = StringIO.StringIO()
Brett Cannone9746892008-04-12 23:44:07 +0000603 expect = self.module.formatwarning(message, category, file_name,
604 line_num)
605 self.module.showwarning(message, category, file_name, line_num,
Brett Cannon905c31c2007-12-20 10:09:52 +0000606 file_object)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000607 self.assertEqual(file_object.getvalue(), expect)
Brett Cannone9746892008-04-12 23:44:07 +0000608 # Test 'line' argument.
609 expected_file_line += "for the win!"
610 expect = self.module.formatwarning(message, category, file_name,
611 line_num, expected_file_line)
612 file_object = StringIO.StringIO()
613 self.module.showwarning(message, category, file_name, line_num,
614 file_object, expected_file_line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000615 self.assertEqual(expect, file_object.getvalue())
Brett Cannone9746892008-04-12 23:44:07 +0000616
Brett Cannon667bb4f2008-04-13 02:42:36 +0000617class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
Brett Cannone9746892008-04-12 23:44:07 +0000618 module = c_warnings
619
Brett Cannon667bb4f2008-04-13 02:42:36 +0000620class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
Brett Cannone9746892008-04-12 23:44:07 +0000621 module = py_warnings
Brett Cannon905c31c2007-12-20 10:09:52 +0000622
623
Brett Cannon1eaf0742008-09-02 01:25:16 +0000624class CatchWarningTests(BaseTest):
Nick Coghlan38469e22008-07-13 12:23:47 +0000625
Brett Cannon1eaf0742008-09-02 01:25:16 +0000626 """Test catch_warnings()."""
627
628 def test_catch_warnings_restore(self):
Nick Coghlan38469e22008-07-13 12:23:47 +0000629 wmod = self.module
630 orig_filters = wmod.filters
631 orig_showwarning = wmod.showwarning
Nick Coghland2e09382008-09-11 12:11:06 +0000632 # Ensure both showwarning and filters are restored when recording
633 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlan38469e22008-07-13 12:23:47 +0000634 wmod.filters = wmod.showwarning = object()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000635 self.assertTrue(wmod.filters is orig_filters)
636 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghland2e09382008-09-11 12:11:06 +0000637 # Same test, but with recording disabled
Brett Cannon1eaf0742008-09-02 01:25:16 +0000638 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlan38469e22008-07-13 12:23:47 +0000639 wmod.filters = wmod.showwarning = object()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000640 self.assertTrue(wmod.filters is orig_filters)
641 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlan38469e22008-07-13 12:23:47 +0000642
Brett Cannon1eaf0742008-09-02 01:25:16 +0000643 def test_catch_warnings_recording(self):
Nick Coghlan38469e22008-07-13 12:23:47 +0000644 wmod = self.module
Nick Coghland2e09382008-09-11 12:11:06 +0000645 # Ensure warnings are recorded when requested
Brett Cannon1eaf0742008-09-02 01:25:16 +0000646 with wmod.catch_warnings(module=wmod, record=True) as w:
647 self.assertEqual(w, [])
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000648 self.assertTrue(type(w) is list)
Nick Coghlan38469e22008-07-13 12:23:47 +0000649 wmod.simplefilter("always")
650 wmod.warn("foo")
Brett Cannon672237d2008-09-09 00:49:16 +0000651 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlan38469e22008-07-13 12:23:47 +0000652 wmod.warn("bar")
Brett Cannon672237d2008-09-09 00:49:16 +0000653 self.assertEqual(str(w[-1].message), "bar")
Brett Cannon1eaf0742008-09-02 01:25:16 +0000654 self.assertEqual(str(w[0].message), "foo")
655 self.assertEqual(str(w[1].message), "bar")
Brett Cannon672237d2008-09-09 00:49:16 +0000656 del w[:]
Brett Cannon1eaf0742008-09-02 01:25:16 +0000657 self.assertEqual(w, [])
Nick Coghland2e09382008-09-11 12:11:06 +0000658 # Ensure warnings are not recorded when not requested
Nick Coghlan38469e22008-07-13 12:23:47 +0000659 orig_showwarning = wmod.showwarning
Brett Cannon1eaf0742008-09-02 01:25:16 +0000660 with wmod.catch_warnings(module=wmod, record=False) as w:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000661 self.assertTrue(w is None)
662 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlan38469e22008-07-13 12:23:47 +0000663
Nick Coghland2e09382008-09-11 12:11:06 +0000664 def test_catch_warnings_reentry_guard(self):
665 wmod = self.module
666 # Ensure catch_warnings is protected against incorrect usage
667 x = wmod.catch_warnings(module=wmod, record=True)
668 self.assertRaises(RuntimeError, x.__exit__)
669 with x:
670 self.assertRaises(RuntimeError, x.__enter__)
671 # Same test, but with recording disabled
672 x = wmod.catch_warnings(module=wmod, record=False)
673 self.assertRaises(RuntimeError, x.__exit__)
674 with x:
675 self.assertRaises(RuntimeError, x.__enter__)
676
677 def test_catch_warnings_defaults(self):
678 wmod = self.module
679 orig_filters = wmod.filters
680 orig_showwarning = wmod.showwarning
681 # Ensure default behaviour is not to record warnings
682 with wmod.catch_warnings(module=wmod) as w:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000683 self.assertTrue(w is None)
684 self.assertTrue(wmod.showwarning is orig_showwarning)
685 self.assertTrue(wmod.filters is not orig_filters)
686 self.assertTrue(wmod.filters is orig_filters)
Nick Coghland2e09382008-09-11 12:11:06 +0000687 if wmod is sys.modules['warnings']:
688 # Ensure the default module is this one
689 with wmod.catch_warnings() as w:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000690 self.assertTrue(w is None)
691 self.assertTrue(wmod.showwarning is orig_showwarning)
692 self.assertTrue(wmod.filters is not orig_filters)
693 self.assertTrue(wmod.filters is orig_filters)
Nick Coghland2e09382008-09-11 12:11:06 +0000694
695 def test_check_warnings(self):
696 # Explicit tests for the test_support convenience wrapper
697 wmod = self.module
Florent Xicluna73588542010-03-18 19:51:47 +0000698 if wmod is not sys.modules['warnings']:
Zachary Ware1f702212013-12-10 14:09:20 -0600699 self.skipTest('module to test is not loaded warnings module')
Florent Xicluna73588542010-03-18 19:51:47 +0000700 with test_support.check_warnings(quiet=False) as w:
701 self.assertEqual(w.warnings, [])
702 wmod.simplefilter("always")
703 wmod.warn("foo")
704 self.assertEqual(str(w.message), "foo")
705 wmod.warn("bar")
706 self.assertEqual(str(w.message), "bar")
707 self.assertEqual(str(w.warnings[0].message), "foo")
708 self.assertEqual(str(w.warnings[1].message), "bar")
709 w.reset()
710 self.assertEqual(w.warnings, [])
Nick Coghland2e09382008-09-11 12:11:06 +0000711
Florent Xicluna73588542010-03-18 19:51:47 +0000712 with test_support.check_warnings():
713 # defaults to quiet=True without argument
714 pass
715 with test_support.check_warnings(('foo', UserWarning)):
716 wmod.warn("foo")
717
718 with self.assertRaises(AssertionError):
719 with test_support.check_warnings(('', RuntimeWarning)):
720 # defaults to quiet=False with argument
721 pass
722 with self.assertRaises(AssertionError):
723 with test_support.check_warnings(('foo', RuntimeWarning)):
724 wmod.warn("foo")
Nick Coghland2e09382008-09-11 12:11:06 +0000725
726
Brett Cannon1eaf0742008-09-02 01:25:16 +0000727class CCatchWarningTests(CatchWarningTests):
Nick Coghlan38469e22008-07-13 12:23:47 +0000728 module = c_warnings
729
Brett Cannon1eaf0742008-09-02 01:25:16 +0000730class PyCatchWarningTests(CatchWarningTests):
Nick Coghlan38469e22008-07-13 12:23:47 +0000731 module = py_warnings
732
733
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000734class EnvironmentVariableTests(BaseTest):
735
736 def test_single_warning(self):
737 newenv = os.environ.copy()
738 newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
739 p = subprocess.Popen([sys.executable,
740 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
741 stdout=subprocess.PIPE, env=newenv)
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000742 self.assertEqual(p.communicate()[0], "['ignore::DeprecationWarning']")
743 self.assertEqual(p.wait(), 0)
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000744
745 def test_comma_separated_warnings(self):
746 newenv = os.environ.copy()
747 newenv["PYTHONWARNINGS"] = ("ignore::DeprecationWarning,"
748 "ignore::UnicodeWarning")
749 p = subprocess.Popen([sys.executable,
750 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
751 stdout=subprocess.PIPE, env=newenv)
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000752 self.assertEqual(p.communicate()[0],
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000753 "['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000754 self.assertEqual(p.wait(), 0)
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000755
756 def test_envvar_and_command_line(self):
757 newenv = os.environ.copy()
758 newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
759 p = subprocess.Popen([sys.executable, "-W" "ignore::UnicodeWarning",
760 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
761 stdout=subprocess.PIPE, env=newenv)
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000762 self.assertEqual(p.communicate()[0],
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000763 "['ignore::UnicodeWarning', 'ignore::DeprecationWarning']")
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000764 self.assertEqual(p.wait(), 0)
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000765
766class CEnvironmentVariableTests(EnvironmentVariableTests):
767 module = c_warnings
768
769class PyEnvironmentVariableTests(EnvironmentVariableTests):
770 module = py_warnings
771
772
Brett Cannone9746892008-04-12 23:44:07 +0000773def test_main():
Amaury Forgeot d'Arc607bff12008-04-18 23:31:33 +0000774 py_warnings.onceregistry.clear()
775 c_warnings.onceregistry.clear()
Brett Cannon1eaf0742008-09-02 01:25:16 +0000776 test_support.run_unittest(CFilterTests, PyFilterTests,
777 CWarnTests, PyWarnTests,
Brett Cannone9746892008-04-12 23:44:07 +0000778 CWCmdLineTests, PyWCmdLineTests,
779 _WarningsTests,
780 CWarningsDisplayTests, PyWarningsDisplayTests,
Brett Cannon1eaf0742008-09-02 01:25:16 +0000781 CCatchWarningTests, PyCatchWarningTests,
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000782 CEnvironmentVariableTests,
783 PyEnvironmentVariableTests
Brett Cannone9746892008-04-12 23:44:07 +0000784 )
785
786
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000787if __name__ == "__main__":
Brett Cannone9746892008-04-12 23:44:07 +0000788 test_main()