blob: 2b41ba1c960660258d70952a47504ad34f59e742 [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
Victor Stinner148051a2010-05-20 21:00:34 +00007import tempfile
8import subprocess
Benjamin Petersonee8712c2008-05-20 21:35:26 +00009from test import support
Antoine Pitroucb4f9292010-11-10 14:01:16 +000010from test.script_helper import assert_python_ok
Jeremy Hylton85014662003-07-11 15:37:59 +000011
Guido van Rossum805365e2007-05-07 22:24:25 +000012from test import warning_tests
Jeremy Hylton85014662003-07-11 15:37:59 +000013
Christian Heimes33fe8092008-04-13 13:53:33 +000014import warnings as original_warnings
Jeremy Hylton85014662003-07-11 15:37:59 +000015
Nick Coghlan47384702009-04-22 16:13:36 +000016py_warnings = support.import_fresh_module('warnings', blocked=['_warnings'])
17c_warnings = support.import_fresh_module('warnings', fresh=['_warnings'])
Christian Heimes33fe8092008-04-13 13:53:33 +000018
19@contextmanager
20def warnings_state(module):
21 """Use a specific warnings implementation in warning_tests."""
22 global __warningregistry__
23 for to_clear in (sys, warning_tests):
24 try:
25 to_clear.__warningregistry__.clear()
26 except AttributeError:
27 pass
28 try:
29 __warningregistry__.clear()
30 except NameError:
31 pass
32 original_warnings = warning_tests.warnings
Florent Xicluna9b0e9182010-03-28 11:42:38 +000033 original_filters = module.filters
Christian Heimes33fe8092008-04-13 13:53:33 +000034 try:
Florent Xicluna9b0e9182010-03-28 11:42:38 +000035 module.filters = original_filters[:]
36 module.simplefilter("once")
Christian Heimes33fe8092008-04-13 13:53:33 +000037 warning_tests.warnings = module
38 yield
39 finally:
40 warning_tests.warnings = original_warnings
Florent Xicluna9b0e9182010-03-28 11:42:38 +000041 module.filters = original_filters
Christian Heimes33fe8092008-04-13 13:53:33 +000042
43
44class BaseTest(unittest.TestCase):
45
46 """Basic bookkeeping required for testing."""
47
48 def setUp(self):
49 # The __warningregistry__ needs to be in a pristine state for tests
50 # to work properly.
51 if '__warningregistry__' in globals():
52 del globals()['__warningregistry__']
53 if hasattr(warning_tests, '__warningregistry__'):
54 del warning_tests.__warningregistry__
55 if hasattr(sys, '__warningregistry__'):
56 del sys.__warningregistry__
57 # The 'warnings' module must be explicitly set so that the proper
58 # interaction between _warnings and 'warnings' can be controlled.
59 sys.modules['warnings'] = self.module
60 super(BaseTest, self).setUp()
61
62 def tearDown(self):
63 sys.modules['warnings'] = original_warnings
64 super(BaseTest, self).tearDown()
65
66
67class FilterTests(object):
68
69 """Testing the filtering functionality."""
70
71 def test_error(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000072 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000073 self.module.resetwarnings()
74 self.module.filterwarnings("error", category=UserWarning)
75 self.assertRaises(UserWarning, self.module.warn,
76 "FilterTests.test_error")
77
78 def test_ignore(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000079 with original_warnings.catch_warnings(record=True,
80 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000081 self.module.resetwarnings()
82 self.module.filterwarnings("ignore", category=UserWarning)
83 self.module.warn("FilterTests.test_ignore", UserWarning)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +000084 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +000085
86 def test_always(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000087 with original_warnings.catch_warnings(record=True,
88 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000089 self.module.resetwarnings()
90 self.module.filterwarnings("always", category=UserWarning)
91 message = "FilterTests.test_always"
92 self.module.warn(message, UserWarning)
Georg Brandlab91fde2009-08-13 08:51:18 +000093 self.assertTrue(message, w[-1].message)
Christian Heimes33fe8092008-04-13 13:53:33 +000094 self.module.warn(message, UserWarning)
Georg Brandlab91fde2009-08-13 08:51:18 +000095 self.assertTrue(w[-1].message, message)
Christian Heimes33fe8092008-04-13 13:53:33 +000096
97 def test_default(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000098 with original_warnings.catch_warnings(record=True,
99 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000100 self.module.resetwarnings()
101 self.module.filterwarnings("default", category=UserWarning)
102 message = UserWarning("FilterTests.test_default")
103 for x in range(2):
104 self.module.warn(message, UserWarning)
105 if x == 0:
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000106 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000107 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000108 elif x == 1:
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000109 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000110 else:
111 raise ValueError("loop variant unhandled")
112
113 def test_module(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000114 with original_warnings.catch_warnings(record=True,
115 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000116 self.module.resetwarnings()
117 self.module.filterwarnings("module", category=UserWarning)
118 message = UserWarning("FilterTests.test_module")
119 self.module.warn(message, UserWarning)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000120 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000121 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000122 self.module.warn(message, UserWarning)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000123 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000124
125 def test_once(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000126 with original_warnings.catch_warnings(record=True,
127 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000128 self.module.resetwarnings()
129 self.module.filterwarnings("once", category=UserWarning)
130 message = UserWarning("FilterTests.test_once")
131 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
132 42)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000133 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000134 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000135 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
136 13)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000137 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000138 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
139 42)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000140 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000141
142 def test_inheritance(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000143 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000144 self.module.resetwarnings()
145 self.module.filterwarnings("error", category=Warning)
146 self.assertRaises(UserWarning, self.module.warn,
147 "FilterTests.test_inheritance", UserWarning)
148
149 def test_ordering(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000150 with original_warnings.catch_warnings(record=True,
151 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000152 self.module.resetwarnings()
153 self.module.filterwarnings("ignore", category=UserWarning)
154 self.module.filterwarnings("error", category=UserWarning,
155 append=True)
Brett Cannon1cd02472008-09-09 01:52:27 +0000156 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000157 try:
158 self.module.warn("FilterTests.test_ordering", UserWarning)
159 except UserWarning:
160 self.fail("order handling for actions failed")
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000161 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000162
163 def test_filterwarnings(self):
164 # Test filterwarnings().
165 # Implicitly also tests resetwarnings().
Brett Cannon1cd02472008-09-09 01:52:27 +0000166 with original_warnings.catch_warnings(record=True,
167 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000168 self.module.filterwarnings("error", "", Warning, "", 0)
169 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
170
171 self.module.resetwarnings()
172 text = 'handle normally'
173 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000174 self.assertEqual(str(w[-1].message), text)
Georg Brandlab91fde2009-08-13 08:51:18 +0000175 self.assertTrue(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000176
177 self.module.filterwarnings("ignore", "", Warning, "", 0)
178 text = 'filtered out'
179 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000180 self.assertNotEqual(str(w[-1].message), text)
Christian Heimes33fe8092008-04-13 13:53:33 +0000181
182 self.module.resetwarnings()
183 self.module.filterwarnings("error", "hex*", Warning, "", 0)
184 self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
185 text = 'nonmatching text'
186 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000187 self.assertEqual(str(w[-1].message), text)
Georg Brandlab91fde2009-08-13 08:51:18 +0000188 self.assertTrue(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000189
190class CFilterTests(BaseTest, FilterTests):
191 module = c_warnings
192
193class PyFilterTests(BaseTest, FilterTests):
194 module = py_warnings
195
196
197class WarnTests(unittest.TestCase):
198
199 """Test warnings.warn() and warnings.warn_explicit()."""
200
201 def test_message(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000202 with original_warnings.catch_warnings(record=True,
203 module=self.module) as w:
Florent Xicluna9b0e9182010-03-28 11:42:38 +0000204 self.module.simplefilter("once")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000205 for i in range(4):
Christian Heimes33fe8092008-04-13 13:53:33 +0000206 text = 'multi %d' %i # Different text on each call.
207 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000208 self.assertEqual(str(w[-1].message), text)
Georg Brandlab91fde2009-08-13 08:51:18 +0000209 self.assertTrue(w[-1].category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000210
Brett Cannon54bd41d2008-09-02 04:01:42 +0000211 # Issue 3639
212 def test_warn_nonstandard_types(self):
213 # warn() should handle non-standard types without issue.
214 for ob in (Warning, None, 42):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000215 with original_warnings.catch_warnings(record=True,
216 module=self.module) as w:
Florent Xicluna9b0e9182010-03-28 11:42:38 +0000217 self.module.simplefilter("once")
Brett Cannon54bd41d2008-09-02 04:01:42 +0000218 self.module.warn(ob)
219 # Don't directly compare objects since
220 # ``Warning() != Warning()``.
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000221 self.assertEqual(str(w[-1].message), str(UserWarning(ob)))
Brett Cannon54bd41d2008-09-02 04:01:42 +0000222
Guido van Rossumd8faa362007-04-27 19:54:29 +0000223 def test_filename(self):
Christian Heimes33fe8092008-04-13 13:53:33 +0000224 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000225 with original_warnings.catch_warnings(record=True,
226 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000227 warning_tests.inner("spam1")
Brett Cannon1cd02472008-09-09 01:52:27 +0000228 self.assertEqual(os.path.basename(w[-1].filename),
229 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000230 warning_tests.outer("spam2")
Brett Cannon1cd02472008-09-09 01:52:27 +0000231 self.assertEqual(os.path.basename(w[-1].filename),
232 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000233
234 def test_stacklevel(self):
235 # Test stacklevel argument
236 # make sure all messages are different, so the warning won't be skipped
Christian Heimes33fe8092008-04-13 13:53:33 +0000237 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000238 with original_warnings.catch_warnings(record=True,
239 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000240 warning_tests.inner("spam3", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000241 self.assertEqual(os.path.basename(w[-1].filename),
242 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000243 warning_tests.outer("spam4", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000244 self.assertEqual(os.path.basename(w[-1].filename),
245 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000246
Christian Heimes33fe8092008-04-13 13:53:33 +0000247 warning_tests.inner("spam5", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000248 self.assertEqual(os.path.basename(w[-1].filename),
249 "test_warnings.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000250 warning_tests.outer("spam6", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000251 self.assertEqual(os.path.basename(w[-1].filename),
252 "warning_tests.py")
Christian Heimes5d8da202008-05-06 13:58:24 +0000253 warning_tests.outer("spam6.5", stacklevel=3)
Brett Cannon1cd02472008-09-09 01:52:27 +0000254 self.assertEqual(os.path.basename(w[-1].filename),
255 "test_warnings.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000256
Christian Heimes33fe8092008-04-13 13:53:33 +0000257 warning_tests.inner("spam7", stacklevel=9999)
Brett Cannon1cd02472008-09-09 01:52:27 +0000258 self.assertEqual(os.path.basename(w[-1].filename),
259 "sys")
Christian Heimes33fe8092008-04-13 13:53:33 +0000260
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000261 def test_missing_filename_not_main(self):
262 # If __file__ is not specified and __main__ is not the module name,
263 # then __file__ should be set to the module name.
264 filename = warning_tests.__file__
265 try:
266 del warning_tests.__file__
267 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000268 with original_warnings.catch_warnings(record=True,
269 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000270 warning_tests.inner("spam8", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000271 self.assertEqual(w[-1].filename, warning_tests.__name__)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000272 finally:
273 warning_tests.__file__ = filename
274
275 def test_missing_filename_main_with_argv(self):
276 # If __file__ is not specified and the caller is __main__ and sys.argv
277 # exists, then use sys.argv[0] as the file.
278 if not hasattr(sys, 'argv'):
279 return
280 filename = warning_tests.__file__
281 module_name = warning_tests.__name__
282 try:
283 del warning_tests.__file__
284 warning_tests.__name__ = '__main__'
285 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000286 with original_warnings.catch_warnings(record=True,
287 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000288 warning_tests.inner('spam9', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000289 self.assertEqual(w[-1].filename, sys.argv[0])
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000290 finally:
291 warning_tests.__file__ = filename
292 warning_tests.__name__ = module_name
293
294 def test_missing_filename_main_without_argv(self):
295 # If __file__ is not specified, the caller is __main__, and sys.argv
296 # is not set, then '__main__' is the file name.
297 filename = warning_tests.__file__
298 module_name = warning_tests.__name__
299 argv = sys.argv
300 try:
301 del warning_tests.__file__
302 warning_tests.__name__ = '__main__'
303 del sys.argv
304 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000305 with original_warnings.catch_warnings(record=True,
306 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000307 warning_tests.inner('spam10', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000308 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000309 finally:
310 warning_tests.__file__ = filename
311 warning_tests.__name__ = module_name
312 sys.argv = argv
313
Christian Heimesdaaf8ee2008-05-04 23:58:41 +0000314 def test_missing_filename_main_with_argv_empty_string(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000315 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
316 # is the empty string, then '__main__ is the file name.
317 # Tests issue 2743.
318 file_name = warning_tests.__file__
319 module_name = warning_tests.__name__
320 argv = sys.argv
321 try:
322 del warning_tests.__file__
323 warning_tests.__name__ = '__main__'
324 sys.argv = ['']
325 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000326 with original_warnings.catch_warnings(record=True,
327 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000328 warning_tests.inner('spam11', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000329 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000330 finally:
331 warning_tests.__file__ = file_name
332 warning_tests.__name__ = module_name
333 sys.argv = argv
334
Brett Cannondb734912008-06-27 00:52:15 +0000335 def test_warn_explicit_type_errors(self):
336 # warn_explicit() shoud error out gracefully if it is given objects
337 # of the wrong types.
338 # lineno is expected to be an integer.
339 self.assertRaises(TypeError, self.module.warn_explicit,
340 None, UserWarning, None, None)
341 # Either 'message' needs to be an instance of Warning or 'category'
342 # needs to be a subclass.
343 self.assertRaises(TypeError, self.module.warn_explicit,
344 None, None, None, 1)
345 # 'registry' must be a dict or None.
346 self.assertRaises((TypeError, AttributeError),
347 self.module.warn_explicit,
348 None, Warning, None, 1, registry=42)
349
Hirokazu Yamamoto680ac292009-07-17 07:02:18 +0000350 def test_bad_str(self):
351 # issue 6415
352 # Warnings instance with a bad format string for __str__ should not
353 # trigger a bus error.
354 class BadStrWarning(Warning):
355 """Warning with a bad format string for __str__."""
356 def __str__(self):
357 return ("A bad formatted string %(err)" %
358 {"err" : "there is no %(err)s"})
359
360 with self.assertRaises(ValueError):
361 self.module.warn(BadStrWarning())
362
363
Christian Heimes33fe8092008-04-13 13:53:33 +0000364class CWarnTests(BaseTest, WarnTests):
365 module = c_warnings
366
Nick Coghlanfce769e2009-04-11 14:30:59 +0000367 # As an early adopter, we sanity check the
368 # test.support.import_fresh_module utility function
369 def test_accelerated(self):
370 self.assertFalse(original_warnings is self.module)
371 self.assertFalse(hasattr(self.module.warn, '__code__'))
372
Christian Heimes33fe8092008-04-13 13:53:33 +0000373class PyWarnTests(BaseTest, WarnTests):
374 module = py_warnings
375
Nick Coghlanfce769e2009-04-11 14:30:59 +0000376 # As an early adopter, we sanity check the
377 # test.support.import_fresh_module utility function
378 def test_pure_python(self):
379 self.assertFalse(original_warnings is self.module)
380 self.assertTrue(hasattr(self.module.warn, '__code__'))
381
Christian Heimes33fe8092008-04-13 13:53:33 +0000382
383class WCmdLineTests(unittest.TestCase):
384
385 def test_improper_input(self):
386 # Uses the private _setoption() function to test the parsing
387 # of command-line warning arguments
Brett Cannon1cd02472008-09-09 01:52:27 +0000388 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000389 self.assertRaises(self.module._OptionError,
390 self.module._setoption, '1:2:3:4:5:6')
391 self.assertRaises(self.module._OptionError,
392 self.module._setoption, 'bogus::Warning')
393 self.assertRaises(self.module._OptionError,
394 self.module._setoption, 'ignore:2::4:-5')
395 self.module._setoption('error::Warning::0')
396 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
397
Antoine Pitroucb4f9292010-11-10 14:01:16 +0000398 def test_improper_option(self):
399 # Same as above, but check that the message is printed out when
400 # the interpreter is executed. This also checks that options are
401 # actually parsed at all.
402 rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")
403 self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)
404
405 def test_warnings_bootstrap(self):
406 # Check that the warnings module does get loaded when -W<some option>
407 # is used (see issue #10372 for an example of silent bootstrap failure).
408 rc, out, err = assert_python_ok("-Wi", "-c",
409 "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
410 # '-Wi' was observed
411 self.assertFalse(out.strip())
412 self.assertNotIn(b'RuntimeWarning', err)
413
Christian Heimes33fe8092008-04-13 13:53:33 +0000414class CWCmdLineTests(BaseTest, WCmdLineTests):
415 module = c_warnings
416
417class PyWCmdLineTests(BaseTest, WCmdLineTests):
418 module = py_warnings
419
420
421class _WarningsTests(BaseTest):
422
423 """Tests specific to the _warnings module."""
424
425 module = c_warnings
426
427 def test_filter(self):
428 # Everything should function even if 'filters' is not in warnings.
Brett Cannon1cd02472008-09-09 01:52:27 +0000429 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000430 self.module.filterwarnings("error", "", Warning, "", 0)
431 self.assertRaises(UserWarning, self.module.warn,
432 'convert to error')
433 del self.module.filters
434 self.assertRaises(UserWarning, self.module.warn,
435 'convert to error')
436
437 def test_onceregistry(self):
438 # Replacing or removing the onceregistry should be okay.
439 global __warningregistry__
440 message = UserWarning('onceregistry test')
441 try:
442 original_registry = self.module.onceregistry
443 __warningregistry__ = {}
Brett Cannon1cd02472008-09-09 01:52:27 +0000444 with original_warnings.catch_warnings(record=True,
445 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000446 self.module.resetwarnings()
447 self.module.filterwarnings("once", category=UserWarning)
448 self.module.warn_explicit(message, UserWarning, "file", 42)
Georg Brandlab91fde2009-08-13 08:51:18 +0000449 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000450 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000451 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000452 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000453 # Test the resetting of onceregistry.
454 self.module.onceregistry = {}
455 __warningregistry__ = {}
456 self.module.warn('onceregistry test')
Georg Brandlab91fde2009-08-13 08:51:18 +0000457 self.assertEqual(w[-1].message.args, message.args)
Christian Heimes33fe8092008-04-13 13:53:33 +0000458 # Removal of onceregistry is okay.
Brett Cannon1cd02472008-09-09 01:52:27 +0000459 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000460 del self.module.onceregistry
461 __warningregistry__ = {}
462 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000463 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000464 finally:
465 self.module.onceregistry = original_registry
466
Brett Cannon0759dd62009-04-01 18:13:07 +0000467 def test_default_action(self):
468 # Replacing or removing defaultaction should be okay.
469 message = UserWarning("defaultaction test")
470 original = self.module.defaultaction
471 try:
472 with original_warnings.catch_warnings(record=True,
473 module=self.module) as w:
474 self.module.resetwarnings()
475 registry = {}
476 self.module.warn_explicit(message, UserWarning, "<test>", 42,
477 registry=registry)
478 self.assertEqual(w[-1].message, message)
479 self.assertEqual(len(w), 1)
480 self.assertEqual(len(registry), 1)
481 del w[:]
482 # Test removal.
483 del self.module.defaultaction
484 __warningregistry__ = {}
485 registry = {}
486 self.module.warn_explicit(message, UserWarning, "<test>", 43,
487 registry=registry)
488 self.assertEqual(w[-1].message, message)
489 self.assertEqual(len(w), 1)
490 self.assertEqual(len(registry), 1)
491 del w[:]
492 # Test setting.
493 self.module.defaultaction = "ignore"
494 __warningregistry__ = {}
495 registry = {}
496 self.module.warn_explicit(message, UserWarning, "<test>", 44,
497 registry=registry)
498 self.assertEqual(len(w), 0)
499 finally:
500 self.module.defaultaction = original
501
Christian Heimes33fe8092008-04-13 13:53:33 +0000502 def test_showwarning_missing(self):
503 # Test that showwarning() missing is okay.
504 text = 'del showwarning test'
Brett Cannon1cd02472008-09-09 01:52:27 +0000505 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000506 self.module.filterwarnings("always", category=UserWarning)
507 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000508 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000509 self.module.warn(text)
510 result = stream.getvalue()
Georg Brandlab91fde2009-08-13 08:51:18 +0000511 self.assertTrue(text in result)
Christian Heimes33fe8092008-04-13 13:53:33 +0000512
Christian Heimes8dc226f2008-05-06 23:45:46 +0000513 def test_showwarning_not_callable(self):
Brett Cannonfcc05272009-04-01 20:27:29 +0000514 with original_warnings.catch_warnings(module=self.module):
515 self.module.filterwarnings("always", category=UserWarning)
516 old_showwarning = self.module.showwarning
517 self.module.showwarning = 23
518 try:
519 self.assertRaises(TypeError, self.module.warn, "Warning!")
520 finally:
521 self.module.showwarning = old_showwarning
Christian Heimes8dc226f2008-05-06 23:45:46 +0000522
Christian Heimes33fe8092008-04-13 13:53:33 +0000523 def test_show_warning_output(self):
524 # With showarning() missing, make sure that output is okay.
525 text = 'test show_warning'
Brett Cannon1cd02472008-09-09 01:52:27 +0000526 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000527 self.module.filterwarnings("always", category=UserWarning)
528 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000529 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000530 warning_tests.inner(text)
531 result = stream.getvalue()
Georg Brandlab91fde2009-08-13 08:51:18 +0000532 self.assertEqual(result.count('\n'), 2,
Christian Heimes33fe8092008-04-13 13:53:33 +0000533 "Too many newlines in %r" % result)
534 first_line, second_line = result.split('\n', 1)
535 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Neal Norwitz32dde222008-04-15 06:43:13 +0000536 first_line_parts = first_line.rsplit(':', 3)
537 path, line, warning_class, message = first_line_parts
Christian Heimes33fe8092008-04-13 13:53:33 +0000538 line = int(line)
Georg Brandlab91fde2009-08-13 08:51:18 +0000539 self.assertEqual(expected_file, path)
540 self.assertEqual(warning_class, ' ' + UserWarning.__name__)
541 self.assertEqual(message, ' ' + text)
Christian Heimes33fe8092008-04-13 13:53:33 +0000542 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
543 assert expected_line
Georg Brandlab91fde2009-08-13 08:51:18 +0000544 self.assertEqual(second_line, expected_line)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000545
546
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000547class WarningsDisplayTests(unittest.TestCase):
548
Christian Heimes33fe8092008-04-13 13:53:33 +0000549 """Test the displaying of warnings and the ability to overload functions
550 related to displaying warnings."""
551
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000552 def test_formatwarning(self):
553 message = "msg"
554 category = Warning
555 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
556 line_num = 3
557 file_line = linecache.getline(file_name, line_num).strip()
Christian Heimes33fe8092008-04-13 13:53:33 +0000558 format = "%s:%s: %s: %s\n %s\n"
559 expect = format % (file_name, line_num, category.__name__, message,
560 file_line)
Georg Brandlab91fde2009-08-13 08:51:18 +0000561 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000562 category, file_name, line_num))
563 # Test the 'line' argument.
564 file_line += " for the win!"
565 expect = format % (file_name, line_num, category.__name__, message,
566 file_line)
Georg Brandlab91fde2009-08-13 08:51:18 +0000567 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000568 category, file_name, line_num, file_line))
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000569
570 def test_showwarning(self):
571 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
572 line_num = 3
573 expected_file_line = linecache.getline(file_name, line_num).strip()
574 message = 'msg'
575 category = Warning
576 file_object = StringIO()
Christian Heimes33fe8092008-04-13 13:53:33 +0000577 expect = self.module.formatwarning(message, category, file_name,
578 line_num)
579 self.module.showwarning(message, category, file_name, line_num,
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000580 file_object)
Georg Brandlab91fde2009-08-13 08:51:18 +0000581 self.assertEqual(file_object.getvalue(), expect)
Christian Heimes33fe8092008-04-13 13:53:33 +0000582 # Test 'line' argument.
583 expected_file_line += "for the win!"
584 expect = self.module.formatwarning(message, category, file_name,
585 line_num, expected_file_line)
586 file_object = StringIO()
587 self.module.showwarning(message, category, file_name, line_num,
588 file_object, expected_file_line)
Georg Brandlab91fde2009-08-13 08:51:18 +0000589 self.assertEqual(expect, file_object.getvalue())
Christian Heimes33fe8092008-04-13 13:53:33 +0000590
591class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
592 module = c_warnings
593
594class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
595 module = py_warnings
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000596
Brett Cannon1cd02472008-09-09 01:52:27 +0000597
Brett Cannonec92e182008-09-02 02:46:59 +0000598class CatchWarningTests(BaseTest):
Nick Coghlanb1304932008-07-13 12:25:08 +0000599
Brett Cannonec92e182008-09-02 02:46:59 +0000600 """Test catch_warnings()."""
601
602 def test_catch_warnings_restore(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000603 wmod = self.module
604 orig_filters = wmod.filters
605 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000606 # Ensure both showwarning and filters are restored when recording
607 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlanb1304932008-07-13 12:25:08 +0000608 wmod.filters = wmod.showwarning = object()
Georg Brandlab91fde2009-08-13 08:51:18 +0000609 self.assertTrue(wmod.filters is orig_filters)
610 self.assertTrue(wmod.showwarning is orig_showwarning)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000611 # Same test, but with recording disabled
612 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlanb1304932008-07-13 12:25:08 +0000613 wmod.filters = wmod.showwarning = object()
Georg Brandlab91fde2009-08-13 08:51:18 +0000614 self.assertTrue(wmod.filters is orig_filters)
615 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000616
Brett Cannonec92e182008-09-02 02:46:59 +0000617 def test_catch_warnings_recording(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000618 wmod = self.module
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000619 # Ensure warnings are recorded when requested
620 with wmod.catch_warnings(module=wmod, record=True) as w:
Brett Cannonec92e182008-09-02 02:46:59 +0000621 self.assertEqual(w, [])
Georg Brandlab91fde2009-08-13 08:51:18 +0000622 self.assertTrue(type(w) is list)
Nick Coghlanb1304932008-07-13 12:25:08 +0000623 wmod.simplefilter("always")
624 wmod.warn("foo")
Brett Cannon1cd02472008-09-09 01:52:27 +0000625 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlanb1304932008-07-13 12:25:08 +0000626 wmod.warn("bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000627 self.assertEqual(str(w[-1].message), "bar")
Brett Cannonec92e182008-09-02 02:46:59 +0000628 self.assertEqual(str(w[0].message), "foo")
629 self.assertEqual(str(w[1].message), "bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000630 del w[:]
Brett Cannonec92e182008-09-02 02:46:59 +0000631 self.assertEqual(w, [])
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000632 # Ensure warnings are not recorded when not requested
Nick Coghlanb1304932008-07-13 12:25:08 +0000633 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000634 with wmod.catch_warnings(module=wmod, record=False) as w:
Georg Brandlab91fde2009-08-13 08:51:18 +0000635 self.assertTrue(w is None)
636 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000637
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000638 def test_catch_warnings_reentry_guard(self):
639 wmod = self.module
640 # Ensure catch_warnings is protected against incorrect usage
641 x = wmod.catch_warnings(module=wmod, record=True)
642 self.assertRaises(RuntimeError, x.__exit__)
643 with x:
644 self.assertRaises(RuntimeError, x.__enter__)
645 # Same test, but with recording disabled
646 x = wmod.catch_warnings(module=wmod, record=False)
647 self.assertRaises(RuntimeError, x.__exit__)
648 with x:
649 self.assertRaises(RuntimeError, x.__enter__)
650
651 def test_catch_warnings_defaults(self):
652 wmod = self.module
653 orig_filters = wmod.filters
654 orig_showwarning = wmod.showwarning
655 # Ensure default behaviour is not to record warnings
656 with wmod.catch_warnings(module=wmod) as w:
Georg Brandlab91fde2009-08-13 08:51:18 +0000657 self.assertTrue(w is None)
658 self.assertTrue(wmod.showwarning is orig_showwarning)
659 self.assertTrue(wmod.filters is not orig_filters)
660 self.assertTrue(wmod.filters is orig_filters)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000661 if wmod is sys.modules['warnings']:
662 # Ensure the default module is this one
663 with wmod.catch_warnings() as w:
Georg Brandlab91fde2009-08-13 08:51:18 +0000664 self.assertTrue(w is None)
665 self.assertTrue(wmod.showwarning is orig_showwarning)
666 self.assertTrue(wmod.filters is not orig_filters)
667 self.assertTrue(wmod.filters is orig_filters)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000668
669 def test_check_warnings(self):
670 # Explicit tests for the test.support convenience wrapper
671 wmod = self.module
672 if wmod is sys.modules['warnings']:
673 with support.check_warnings() 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, [])
684
Brett Cannonec92e182008-09-02 02:46:59 +0000685class CCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000686 module = c_warnings
687
Brett Cannonec92e182008-09-02 02:46:59 +0000688class PyCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000689 module = py_warnings
690
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000691
Victor Stinner148051a2010-05-20 21:00:34 +0000692class BootstrapTest(unittest.TestCase):
693 def test_issue_8766(self):
694 # "import encodings" emits a warning whereas the warnings is not loaded
695 # or not completly loaded (warnings imports indirectly encodings by
696 # importing linecache) yet
Victor Stinnerd6563542010-05-20 21:42:00 +0000697 cwd = tempfile.mkdtemp()
Victor Stinner148051a2010-05-20 21:00:34 +0000698 try:
Victor Stinnerd6563542010-05-20 21:42:00 +0000699 encodings = os.path.join(cwd, 'encodings')
700 os.mkdir(encodings)
Victor Stinner148051a2010-05-20 21:00:34 +0000701 try:
Victor Stinner148051a2010-05-20 21:00:34 +0000702 env = os.environ.copy()
703 env['PYTHONPATH'] = cwd
704
705 # encodings loaded by initfsencoding()
706 retcode = subprocess.call([sys.executable, '-c', 'pass'], env=env)
707 self.assertEqual(retcode, 0)
708
709 # Use -W to load warnings module at startup
710 retcode = subprocess.call(
711 [sys.executable, '-c', 'pass', '-W', 'always'],
712 env=env)
713 self.assertEqual(retcode, 0)
714 finally:
Victor Stinnerd6563542010-05-20 21:42:00 +0000715 os.rmdir(encodings)
Victor Stinner148051a2010-05-20 21:00:34 +0000716 finally:
Victor Stinnerd6563542010-05-20 21:42:00 +0000717 os.rmdir(cwd)
Victor Stinner148051a2010-05-20 21:00:34 +0000718
Christian Heimes33fe8092008-04-13 13:53:33 +0000719def test_main():
Christian Heimesdae2a892008-04-19 00:55:37 +0000720 py_warnings.onceregistry.clear()
721 c_warnings.onceregistry.clear()
Victor Stinner148051a2010-05-20 21:00:34 +0000722 support.run_unittest(
723 CFilterTests, PyFilterTests,
724 CWarnTests, PyWarnTests,
725 CWCmdLineTests, PyWCmdLineTests,
726 _WarningsTests,
727 CWarningsDisplayTests, PyWarningsDisplayTests,
728 CCatchWarningTests, PyCatchWarningTests,
729 BootstrapTest,
730 )
Christian Heimes33fe8092008-04-13 13:53:33 +0000731
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000732
733if __name__ == "__main__":
Christian Heimes33fe8092008-04-13 13:53:33 +0000734 test_main()