blob: 111ff792f502c83f46e523947955ec2828de135c [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
Philip Jenvey0805ca32010-04-07 04:04:10 +00007import subprocess
Benjamin Petersonee8712c2008-05-20 21:35:26 +00008from test import support
Antoine Pitroucf9f9802010-11-10 13:55:25 +00009from test.script_helper import assert_python_ok
Jeremy Hylton85014662003-07-11 15:37:59 +000010
Guido van Rossum805365e2007-05-07 22:24:25 +000011from test import warning_tests
Jeremy Hylton85014662003-07-11 15:37:59 +000012
Christian Heimes33fe8092008-04-13 13:53:33 +000013import warnings as original_warnings
Jeremy Hylton85014662003-07-11 15:37:59 +000014
Nick Coghlan47384702009-04-22 16:13:36 +000015py_warnings = support.import_fresh_module('warnings', blocked=['_warnings'])
16c_warnings = support.import_fresh_module('warnings', fresh=['_warnings'])
Christian Heimes33fe8092008-04-13 13:53:33 +000017
18@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 Xiclunafd1b0932010-03-28 00:25:02 +000032 original_filters = module.filters
Christian Heimes33fe8092008-04-13 13:53:33 +000033 try:
Florent Xiclunafd1b0932010-03-28 00:25:02 +000034 module.filters = original_filters[:]
35 module.simplefilter("once")
Christian Heimes33fe8092008-04-13 13:53:33 +000036 warning_tests.warnings = module
37 yield
38 finally:
39 warning_tests.warnings = original_warnings
Florent Xiclunafd1b0932010-03-28 00:25:02 +000040 module.filters = original_filters
Christian Heimes33fe8092008-04-13 13:53:33 +000041
42
43class BaseTest(unittest.TestCase):
44
45 """Basic bookkeeping required for testing."""
46
47 def setUp(self):
48 # 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."""
69
70 def test_error(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000071 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +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 Cannon1cd02472008-09-09 01:52:27 +000078 with original_warnings.catch_warnings(record=True,
79 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000080 self.module.resetwarnings()
81 self.module.filterwarnings("ignore", category=UserWarning)
82 self.module.warn("FilterTests.test_ignore", UserWarning)
Brett Cannonec92e182008-09-02 02:46:59 +000083 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +000084
85 def test_always(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000086 with original_warnings.catch_warnings(record=True,
87 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000088 self.module.resetwarnings()
89 self.module.filterwarnings("always", category=UserWarning)
90 message = "FilterTests.test_always"
91 self.module.warn(message, UserWarning)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000092 self.assertTrue(message, w[-1].message)
Christian Heimes33fe8092008-04-13 13:53:33 +000093 self.module.warn(message, UserWarning)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000094 self.assertTrue(w[-1].message, message)
Christian Heimes33fe8092008-04-13 13:53:33 +000095
96 def test_default(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000097 with original_warnings.catch_warnings(record=True,
98 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000099 self.module.resetwarnings()
100 self.module.filterwarnings("default", category=UserWarning)
101 message = UserWarning("FilterTests.test_default")
102 for x in range(2):
103 self.module.warn(message, UserWarning)
104 if x == 0:
Brett Cannon1cd02472008-09-09 01:52:27 +0000105 self.assertEquals(w[-1].message, message)
106 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000107 elif x == 1:
Brett Cannon1cd02472008-09-09 01:52:27 +0000108 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000109 else:
110 raise ValueError("loop variant unhandled")
111
112 def test_module(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000113 with original_warnings.catch_warnings(record=True,
114 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000115 self.module.resetwarnings()
116 self.module.filterwarnings("module", category=UserWarning)
117 message = UserWarning("FilterTests.test_module")
118 self.module.warn(message, UserWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +0000119 self.assertEquals(w[-1].message, message)
120 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000121 self.module.warn(message, UserWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +0000122 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000123
124 def test_once(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000125 with original_warnings.catch_warnings(record=True,
126 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +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)
Brett Cannon1cd02472008-09-09 01:52:27 +0000132 self.assertEquals(w[-1].message, message)
133 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000134 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
135 13)
Brett Cannonec92e182008-09-02 02:46:59 +0000136 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000137 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
138 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000139 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000140
141 def test_inheritance(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000142 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +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 Cannon1cd02472008-09-09 01:52:27 +0000149 with original_warnings.catch_warnings(record=True,
150 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000151 self.module.resetwarnings()
152 self.module.filterwarnings("ignore", category=UserWarning)
153 self.module.filterwarnings("error", category=UserWarning,
154 append=True)
Brett Cannon1cd02472008-09-09 01:52:27 +0000155 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000156 try:
157 self.module.warn("FilterTests.test_ordering", UserWarning)
158 except UserWarning:
159 self.fail("order handling for actions failed")
Brett Cannonec92e182008-09-02 02:46:59 +0000160 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000161
162 def test_filterwarnings(self):
163 # Test filterwarnings().
164 # Implicitly also tests resetwarnings().
Brett Cannon1cd02472008-09-09 01:52:27 +0000165 with original_warnings.catch_warnings(record=True,
166 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +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 Cannon1cd02472008-09-09 01:52:27 +0000173 self.assertEqual(str(w[-1].message), text)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000174 self.assertTrue(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000175
176 self.module.filterwarnings("ignore", "", Warning, "", 0)
177 text = 'filtered out'
178 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000179 self.assertNotEqual(str(w[-1].message), text)
Christian Heimes33fe8092008-04-13 13:53:33 +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 Cannon1cd02472008-09-09 01:52:27 +0000186 self.assertEqual(str(w[-1].message), text)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000187 self.assertTrue(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000188
189class CFilterTests(BaseTest, FilterTests):
190 module = c_warnings
191
192class PyFilterTests(BaseTest, FilterTests):
193 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 Cannon1cd02472008-09-09 01:52:27 +0000201 with original_warnings.catch_warnings(record=True,
202 module=self.module) as w:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000203 self.module.simplefilter("once")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000204 for i in range(4):
Christian Heimes33fe8092008-04-13 13:53:33 +0000205 text = 'multi %d' %i # Different text on each call.
206 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000207 self.assertEqual(str(w[-1].message), text)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000208 self.assertTrue(w[-1].category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000209
Brett Cannon54bd41d2008-09-02 04:01:42 +0000210 # Issue 3639
211 def test_warn_nonstandard_types(self):
212 # warn() should handle non-standard types without issue.
213 for ob in (Warning, None, 42):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000214 with original_warnings.catch_warnings(record=True,
215 module=self.module) as w:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000216 self.module.simplefilter("once")
Brett Cannon54bd41d2008-09-02 04:01:42 +0000217 self.module.warn(ob)
218 # Don't directly compare objects since
219 # ``Warning() != Warning()``.
Brett Cannon1cd02472008-09-09 01:52:27 +0000220 self.assertEquals(str(w[-1].message), str(UserWarning(ob)))
Brett Cannon54bd41d2008-09-02 04:01:42 +0000221
Guido van Rossumd8faa362007-04-27 19:54:29 +0000222 def test_filename(self):
Christian Heimes33fe8092008-04-13 13:53:33 +0000223 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000224 with original_warnings.catch_warnings(record=True,
225 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000226 warning_tests.inner("spam1")
Brett Cannon1cd02472008-09-09 01:52:27 +0000227 self.assertEqual(os.path.basename(w[-1].filename),
228 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000229 warning_tests.outer("spam2")
Brett Cannon1cd02472008-09-09 01:52:27 +0000230 self.assertEqual(os.path.basename(w[-1].filename),
231 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000232
233 def test_stacklevel(self):
234 # Test stacklevel argument
235 # make sure all messages are different, so the warning won't be skipped
Christian Heimes33fe8092008-04-13 13:53:33 +0000236 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000237 with original_warnings.catch_warnings(record=True,
238 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000239 warning_tests.inner("spam3", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000240 self.assertEqual(os.path.basename(w[-1].filename),
241 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000242 warning_tests.outer("spam4", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000243 self.assertEqual(os.path.basename(w[-1].filename),
244 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000245
Christian Heimes33fe8092008-04-13 13:53:33 +0000246 warning_tests.inner("spam5", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000247 self.assertEqual(os.path.basename(w[-1].filename),
248 "test_warnings.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000249 warning_tests.outer("spam6", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000250 self.assertEqual(os.path.basename(w[-1].filename),
251 "warning_tests.py")
Christian Heimes5d8da202008-05-06 13:58:24 +0000252 warning_tests.outer("spam6.5", stacklevel=3)
Brett Cannon1cd02472008-09-09 01:52:27 +0000253 self.assertEqual(os.path.basename(w[-1].filename),
254 "test_warnings.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000255
Christian Heimes33fe8092008-04-13 13:53:33 +0000256 warning_tests.inner("spam7", stacklevel=9999)
Brett Cannon1cd02472008-09-09 01:52:27 +0000257 self.assertEqual(os.path.basename(w[-1].filename),
258 "sys")
Christian Heimes33fe8092008-04-13 13:53:33 +0000259
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000260 def test_missing_filename_not_main(self):
261 # If __file__ is not specified and __main__ is not the module name,
262 # then __file__ should be set to the module name.
263 filename = warning_tests.__file__
264 try:
265 del warning_tests.__file__
266 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000267 with original_warnings.catch_warnings(record=True,
268 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000269 warning_tests.inner("spam8", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000270 self.assertEqual(w[-1].filename, warning_tests.__name__)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000271 finally:
272 warning_tests.__file__ = filename
273
274 def test_missing_filename_main_with_argv(self):
275 # If __file__ is not specified and the caller is __main__ and sys.argv
276 # exists, then use sys.argv[0] as the file.
277 if not hasattr(sys, 'argv'):
278 return
279 filename = warning_tests.__file__
280 module_name = warning_tests.__name__
281 try:
282 del warning_tests.__file__
283 warning_tests.__name__ = '__main__'
284 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000285 with original_warnings.catch_warnings(record=True,
286 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000287 warning_tests.inner('spam9', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000288 self.assertEqual(w[-1].filename, sys.argv[0])
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000289 finally:
290 warning_tests.__file__ = filename
291 warning_tests.__name__ = module_name
292
293 def test_missing_filename_main_without_argv(self):
294 # If __file__ is not specified, the caller is __main__, and sys.argv
295 # is not set, then '__main__' is the file name.
296 filename = warning_tests.__file__
297 module_name = warning_tests.__name__
298 argv = sys.argv
299 try:
300 del warning_tests.__file__
301 warning_tests.__name__ = '__main__'
302 del sys.argv
303 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000304 with original_warnings.catch_warnings(record=True,
305 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000306 warning_tests.inner('spam10', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000307 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000308 finally:
309 warning_tests.__file__ = filename
310 warning_tests.__name__ = module_name
311 sys.argv = argv
312
Christian Heimesdaaf8ee2008-05-04 23:58:41 +0000313 def test_missing_filename_main_with_argv_empty_string(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000314 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
315 # is the empty string, then '__main__ is the file name.
316 # Tests issue 2743.
317 file_name = warning_tests.__file__
318 module_name = warning_tests.__name__
319 argv = sys.argv
320 try:
321 del warning_tests.__file__
322 warning_tests.__name__ = '__main__'
323 sys.argv = ['']
324 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000325 with original_warnings.catch_warnings(record=True,
326 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000327 warning_tests.inner('spam11', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000328 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000329 finally:
330 warning_tests.__file__ = file_name
331 warning_tests.__name__ = module_name
332 sys.argv = argv
333
Brett Cannondb734912008-06-27 00:52:15 +0000334 def test_warn_explicit_type_errors(self):
335 # warn_explicit() shoud error out gracefully if it is given objects
336 # of the wrong types.
337 # lineno is expected to be an integer.
338 self.assertRaises(TypeError, self.module.warn_explicit,
339 None, UserWarning, None, None)
340 # Either 'message' needs to be an instance of Warning or 'category'
341 # needs to be a subclass.
342 self.assertRaises(TypeError, self.module.warn_explicit,
343 None, None, None, 1)
344 # 'registry' must be a dict or None.
345 self.assertRaises((TypeError, AttributeError),
346 self.module.warn_explicit,
347 None, Warning, None, 1, registry=42)
348
Hirokazu Yamamoto1c0c0032009-07-17 06:55:42 +0000349 def test_bad_str(self):
350 # issue 6415
351 # Warnings instance with a bad format string for __str__ should not
352 # trigger a bus error.
353 class BadStrWarning(Warning):
354 """Warning with a bad format string for __str__."""
355 def __str__(self):
356 return ("A bad formatted string %(err)" %
357 {"err" : "there is no %(err)s"})
358
359 with self.assertRaises(ValueError):
360 self.module.warn(BadStrWarning())
361
362
Christian Heimes33fe8092008-04-13 13:53:33 +0000363class CWarnTests(BaseTest, WarnTests):
364 module = c_warnings
365
Nick Coghlanfce769e2009-04-11 14:30:59 +0000366 # As an early adopter, we sanity check the
367 # test.support.import_fresh_module utility function
368 def test_accelerated(self):
369 self.assertFalse(original_warnings is self.module)
370 self.assertFalse(hasattr(self.module.warn, '__code__'))
371
Christian Heimes33fe8092008-04-13 13:53:33 +0000372class PyWarnTests(BaseTest, WarnTests):
373 module = py_warnings
374
Nick Coghlanfce769e2009-04-11 14:30:59 +0000375 # As an early adopter, we sanity check the
376 # test.support.import_fresh_module utility function
377 def test_pure_python(self):
378 self.assertFalse(original_warnings is self.module)
379 self.assertTrue(hasattr(self.module.warn, '__code__'))
380
Christian Heimes33fe8092008-04-13 13:53:33 +0000381
382class WCmdLineTests(unittest.TestCase):
383
384 def test_improper_input(self):
385 # Uses the private _setoption() function to test the parsing
386 # of command-line warning arguments
Brett Cannon1cd02472008-09-09 01:52:27 +0000387 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000388 self.assertRaises(self.module._OptionError,
389 self.module._setoption, '1:2:3:4:5:6')
390 self.assertRaises(self.module._OptionError,
391 self.module._setoption, 'bogus::Warning')
392 self.assertRaises(self.module._OptionError,
393 self.module._setoption, 'ignore:2::4:-5')
394 self.module._setoption('error::Warning::0')
395 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
396
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000397 def test_improper_option(self):
398 # Same as above, but check that the message is printed out when
399 # the interpreter is executed. This also checks that options are
400 # actually parsed at all.
401 rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")
402 self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)
403
404 def test_warnings_bootstrap(self):
405 # Check that the warnings module does get loaded when -W<some option>
406 # is used (see issue #10372 for an example of silent bootstrap failure).
407 rc, out, err = assert_python_ok("-Wi", "-c",
408 "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
409 # '-Wi' was observed
410 self.assertFalse(out.strip())
411 self.assertNotIn(b'RuntimeWarning', err)
412
Christian Heimes33fe8092008-04-13 13:53:33 +0000413class CWCmdLineTests(BaseTest, WCmdLineTests):
414 module = c_warnings
415
416class PyWCmdLineTests(BaseTest, WCmdLineTests):
417 module = py_warnings
418
419
420class _WarningsTests(BaseTest):
421
422 """Tests specific to the _warnings module."""
423
424 module = c_warnings
425
426 def test_filter(self):
427 # Everything should function even if 'filters' is not in warnings.
Brett Cannon1cd02472008-09-09 01:52:27 +0000428 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000429 self.module.filterwarnings("error", "", Warning, "", 0)
430 self.assertRaises(UserWarning, self.module.warn,
431 'convert to error')
432 del self.module.filters
433 self.assertRaises(UserWarning, self.module.warn,
434 'convert to error')
435
436 def test_onceregistry(self):
437 # Replacing or removing the onceregistry should be okay.
438 global __warningregistry__
439 message = UserWarning('onceregistry test')
440 try:
441 original_registry = self.module.onceregistry
442 __warningregistry__ = {}
Brett Cannon1cd02472008-09-09 01:52:27 +0000443 with original_warnings.catch_warnings(record=True,
444 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000445 self.module.resetwarnings()
446 self.module.filterwarnings("once", category=UserWarning)
447 self.module.warn_explicit(message, UserWarning, "file", 42)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000448 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000449 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000450 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000451 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000452 # Test the resetting of onceregistry.
453 self.module.onceregistry = {}
454 __warningregistry__ = {}
455 self.module.warn('onceregistry test')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000456 self.assertEqual(w[-1].message.args, message.args)
Christian Heimes33fe8092008-04-13 13:53:33 +0000457 # Removal of onceregistry is okay.
Brett Cannon1cd02472008-09-09 01:52:27 +0000458 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000459 del self.module.onceregistry
460 __warningregistry__ = {}
461 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000462 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000463 finally:
464 self.module.onceregistry = original_registry
465
Brett Cannon0759dd62009-04-01 18:13:07 +0000466 def test_default_action(self):
467 # Replacing or removing defaultaction should be okay.
468 message = UserWarning("defaultaction test")
469 original = self.module.defaultaction
470 try:
471 with original_warnings.catch_warnings(record=True,
472 module=self.module) as w:
473 self.module.resetwarnings()
474 registry = {}
475 self.module.warn_explicit(message, UserWarning, "<test>", 42,
476 registry=registry)
477 self.assertEqual(w[-1].message, message)
478 self.assertEqual(len(w), 1)
479 self.assertEqual(len(registry), 1)
480 del w[:]
481 # Test removal.
482 del self.module.defaultaction
483 __warningregistry__ = {}
484 registry = {}
485 self.module.warn_explicit(message, UserWarning, "<test>", 43,
486 registry=registry)
487 self.assertEqual(w[-1].message, message)
488 self.assertEqual(len(w), 1)
489 self.assertEqual(len(registry), 1)
490 del w[:]
491 # Test setting.
492 self.module.defaultaction = "ignore"
493 __warningregistry__ = {}
494 registry = {}
495 self.module.warn_explicit(message, UserWarning, "<test>", 44,
496 registry=registry)
497 self.assertEqual(len(w), 0)
498 finally:
499 self.module.defaultaction = original
500
Christian Heimes33fe8092008-04-13 13:53:33 +0000501 def test_showwarning_missing(self):
502 # Test that showwarning() missing is okay.
503 text = 'del showwarning test'
Brett Cannon1cd02472008-09-09 01:52:27 +0000504 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000505 self.module.filterwarnings("always", category=UserWarning)
506 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000507 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000508 self.module.warn(text)
509 result = stream.getvalue()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000510 self.assertIn(text, result)
Christian Heimes33fe8092008-04-13 13:53:33 +0000511
Christian Heimes8dc226f2008-05-06 23:45:46 +0000512 def test_showwarning_not_callable(self):
Brett Cannonfcc05272009-04-01 20:27:29 +0000513 with original_warnings.catch_warnings(module=self.module):
514 self.module.filterwarnings("always", category=UserWarning)
515 old_showwarning = self.module.showwarning
516 self.module.showwarning = 23
517 try:
518 self.assertRaises(TypeError, self.module.warn, "Warning!")
519 finally:
520 self.module.showwarning = old_showwarning
Christian Heimes8dc226f2008-05-06 23:45:46 +0000521
Christian Heimes33fe8092008-04-13 13:53:33 +0000522 def test_show_warning_output(self):
523 # With showarning() missing, make sure that output is okay.
524 text = 'test show_warning'
Brett Cannon1cd02472008-09-09 01:52:27 +0000525 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000526 self.module.filterwarnings("always", category=UserWarning)
527 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000528 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000529 warning_tests.inner(text)
530 result = stream.getvalue()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000531 self.assertEqual(result.count('\n'), 2,
Christian Heimes33fe8092008-04-13 13:53:33 +0000532 "Too many newlines in %r" % result)
533 first_line, second_line = result.split('\n', 1)
534 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Neal Norwitz32dde222008-04-15 06:43:13 +0000535 first_line_parts = first_line.rsplit(':', 3)
536 path, line, warning_class, message = first_line_parts
Christian Heimes33fe8092008-04-13 13:53:33 +0000537 line = int(line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000538 self.assertEqual(expected_file, path)
539 self.assertEqual(warning_class, ' ' + UserWarning.__name__)
540 self.assertEqual(message, ' ' + text)
Christian Heimes33fe8092008-04-13 13:53:33 +0000541 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
542 assert expected_line
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000543 self.assertEqual(second_line, expected_line)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000544
545
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000546class WarningsDisplayTests(unittest.TestCase):
547
Christian Heimes33fe8092008-04-13 13:53:33 +0000548 """Test the displaying of warnings and the ability to overload functions
549 related to displaying warnings."""
550
Christian Heimes5fb7c2a2007-12-24 08:52:31 +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()
Christian Heimes33fe8092008-04-13 13:53:33 +0000557 format = "%s:%s: %s: %s\n %s\n"
558 expect = format % (file_name, line_num, category.__name__, message,
559 file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000560 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +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 Petersonc9c0f202009-06-30 23:06:06 +0000566 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000567 category, file_name, line_num, file_line))
Christian Heimes5fb7c2a2007-12-24 08:52:31 +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()
Christian Heimes33fe8092008-04-13 13:53:33 +0000576 expect = self.module.formatwarning(message, category, file_name,
577 line_num)
578 self.module.showwarning(message, category, file_name, line_num,
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000579 file_object)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000580 self.assertEqual(file_object.getvalue(), expect)
Christian Heimes33fe8092008-04-13 13:53:33 +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()
586 self.module.showwarning(message, category, file_name, line_num,
587 file_object, expected_file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000588 self.assertEqual(expect, file_object.getvalue())
Christian Heimes33fe8092008-04-13 13:53:33 +0000589
590class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
591 module = c_warnings
592
593class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
594 module = py_warnings
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000595
Brett Cannon1cd02472008-09-09 01:52:27 +0000596
Brett Cannonec92e182008-09-02 02:46:59 +0000597class CatchWarningTests(BaseTest):
Nick Coghlanb1304932008-07-13 12:25:08 +0000598
Brett Cannonec92e182008-09-02 02:46:59 +0000599 """Test catch_warnings()."""
600
601 def test_catch_warnings_restore(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000602 wmod = self.module
603 orig_filters = wmod.filters
604 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000605 # Ensure both showwarning and filters are restored when recording
606 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlanb1304932008-07-13 12:25:08 +0000607 wmod.filters = wmod.showwarning = object()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000608 self.assertTrue(wmod.filters is orig_filters)
609 self.assertTrue(wmod.showwarning is orig_showwarning)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000610 # Same test, but with recording disabled
611 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlanb1304932008-07-13 12:25:08 +0000612 wmod.filters = wmod.showwarning = object()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000613 self.assertTrue(wmod.filters is orig_filters)
614 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000615
Brett Cannonec92e182008-09-02 02:46:59 +0000616 def test_catch_warnings_recording(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000617 wmod = self.module
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000618 # Ensure warnings are recorded when requested
619 with wmod.catch_warnings(module=wmod, record=True) as w:
Brett Cannonec92e182008-09-02 02:46:59 +0000620 self.assertEqual(w, [])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000621 self.assertTrue(type(w) is list)
Nick Coghlanb1304932008-07-13 12:25:08 +0000622 wmod.simplefilter("always")
623 wmod.warn("foo")
Brett Cannon1cd02472008-09-09 01:52:27 +0000624 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlanb1304932008-07-13 12:25:08 +0000625 wmod.warn("bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000626 self.assertEqual(str(w[-1].message), "bar")
Brett Cannonec92e182008-09-02 02:46:59 +0000627 self.assertEqual(str(w[0].message), "foo")
628 self.assertEqual(str(w[1].message), "bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000629 del w[:]
Brett Cannonec92e182008-09-02 02:46:59 +0000630 self.assertEqual(w, [])
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000631 # Ensure warnings are not recorded when not requested
Nick Coghlanb1304932008-07-13 12:25:08 +0000632 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000633 with wmod.catch_warnings(module=wmod, record=False) as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000634 self.assertTrue(w is None)
635 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000636
Benjamin Petersonfcf5d632008-10-16 23:24:44 +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 Petersonc9c0f202009-06-30 23:06:06 +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)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000660 if wmod is sys.modules['warnings']:
661 # Ensure the default module is this one
662 with wmod.catch_warnings() as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +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)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000667
668 def test_check_warnings(self):
669 # Explicit tests for the test.support convenience wrapper
670 wmod = self.module
Florent Xicluna53b506be2010-03-18 20:00:57 +0000671 if wmod is not sys.modules['warnings']:
672 return
673 with 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, [])
684
685 with support.check_warnings():
686 # defaults to quiet=True without argument
687 pass
688 with support.check_warnings(('foo', UserWarning)):
689 wmod.warn("foo")
690
691 with self.assertRaises(AssertionError):
692 with support.check_warnings(('', RuntimeWarning)):
693 # defaults to quiet=False with argument
694 pass
695 with self.assertRaises(AssertionError):
696 with support.check_warnings(('foo', RuntimeWarning)):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000697 wmod.warn("foo")
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000698
Brett Cannonec92e182008-09-02 02:46:59 +0000699class CCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000700 module = c_warnings
701
Brett Cannonec92e182008-09-02 02:46:59 +0000702class PyCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000703 module = py_warnings
704
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000705
Philip Jenvey0805ca32010-04-07 04:04:10 +0000706class EnvironmentVariableTests(BaseTest):
707
708 def test_single_warning(self):
709 newenv = os.environ.copy()
710 newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
711 p = subprocess.Popen([sys.executable,
712 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
713 stdout=subprocess.PIPE, env=newenv)
Benjamin Petersonad6139a2010-04-11 21:16:33 +0000714 self.assertEqual(p.communicate()[0], b"['ignore::DeprecationWarning']")
715 self.assertEqual(p.wait(), 0)
Philip Jenvey0805ca32010-04-07 04:04:10 +0000716
717 def test_comma_separated_warnings(self):
718 newenv = os.environ.copy()
719 newenv["PYTHONWARNINGS"] = ("ignore::DeprecationWarning,"
720 "ignore::UnicodeWarning")
721 p = subprocess.Popen([sys.executable,
722 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
723 stdout=subprocess.PIPE, env=newenv)
Benjamin Petersonad6139a2010-04-11 21:16:33 +0000724 self.assertEqual(p.communicate()[0],
Philip Jenvey0805ca32010-04-07 04:04:10 +0000725 b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
Benjamin Petersonad6139a2010-04-11 21:16:33 +0000726 self.assertEqual(p.wait(), 0)
Philip Jenvey0805ca32010-04-07 04:04:10 +0000727
728 def test_envvar_and_command_line(self):
729 newenv = os.environ.copy()
730 newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
731 p = subprocess.Popen([sys.executable, "-W" "ignore::UnicodeWarning",
732 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
733 stdout=subprocess.PIPE, env=newenv)
Benjamin Petersonad6139a2010-04-11 21:16:33 +0000734 self.assertEqual(p.communicate()[0],
Philip Jenvey0805ca32010-04-07 04:04:10 +0000735 b"['ignore::UnicodeWarning', 'ignore::DeprecationWarning']")
Benjamin Petersonad6139a2010-04-11 21:16:33 +0000736 self.assertEqual(p.wait(), 0)
Philip Jenvey0805ca32010-04-07 04:04:10 +0000737
Philip Jenveye53de3d2010-04-14 03:01:39 +0000738 @unittest.skipUnless(sys.getfilesystemencoding() != 'ascii',
739 'requires non-ascii filesystemencoding')
740 def test_nonascii(self):
741 newenv = os.environ.copy()
742 newenv["PYTHONWARNINGS"] = "ignore:DeprecaciónWarning"
743 newenv["PYTHONIOENCODING"] = "utf-8"
744 p = subprocess.Popen([sys.executable,
745 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
746 stdout=subprocess.PIPE, env=newenv)
747 self.assertEqual(p.communicate()[0],
748 "['ignore:DeprecaciónWarning']".encode('utf-8'))
749 self.assertEqual(p.wait(), 0)
750
Philip Jenvey0805ca32010-04-07 04:04:10 +0000751class CEnvironmentVariableTests(EnvironmentVariableTests):
752 module = c_warnings
753
754class PyEnvironmentVariableTests(EnvironmentVariableTests):
755 module = py_warnings
756
757
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000758class BootstrapTest(unittest.TestCase):
759 def test_issue_8766(self):
760 # "import encodings" emits a warning whereas the warnings is not loaded
761 # or not completly loaded (warnings imports indirectly encodings by
762 # importing linecache) yet
763 with support.temp_cwd() as cwd, support.temp_cwd('encodings'):
764 env = os.environ.copy()
765 env['PYTHONPATH'] = cwd
766
767 # encodings loaded by initfsencoding()
768 retcode = subprocess.call([sys.executable, '-c', 'pass'], env=env)
769 self.assertEqual(retcode, 0)
770
771 # Use -W to load warnings module at startup
772 retcode = subprocess.call(
773 [sys.executable, '-c', 'pass', '-W', 'always'],
774 env=env)
775 self.assertEqual(retcode, 0)
776
Christian Heimes33fe8092008-04-13 13:53:33 +0000777def test_main():
Christian Heimesdae2a892008-04-19 00:55:37 +0000778 py_warnings.onceregistry.clear()
779 c_warnings.onceregistry.clear()
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000780 support.run_unittest(
781 CFilterTests, PyFilterTests,
782 CWarnTests, PyWarnTests,
783 CWCmdLineTests, PyWCmdLineTests,
784 _WarningsTests,
785 CWarningsDisplayTests, PyWarningsDisplayTests,
786 CCatchWarningTests, PyCatchWarningTests,
787 CEnvironmentVariableTests, PyEnvironmentVariableTests,
788 BootstrapTest,
789 )
Christian Heimes33fe8092008-04-13 13:53:33 +0000790
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000791
792if __name__ == "__main__":
Christian Heimes33fe8092008-04-13 13:53:33 +0000793 test_main()