blob: 52b9dbedd77061ba3edb82174cd3c28c4fd942b4 [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
Jeremy Hylton85014662003-07-11 15:37:59 +00009
Guido van Rossum805365e2007-05-07 22:24:25 +000010from test import warning_tests
Jeremy Hylton85014662003-07-11 15:37:59 +000011
Christian Heimes33fe8092008-04-13 13:53:33 +000012import warnings as original_warnings
Jeremy Hylton85014662003-07-11 15:37:59 +000013
Nick Coghlan47384702009-04-22 16:13:36 +000014py_warnings = support.import_fresh_module('warnings', blocked=['_warnings'])
15c_warnings = support.import_fresh_module('warnings', fresh=['_warnings'])
Christian Heimes33fe8092008-04-13 13:53:33 +000016
17@contextmanager
18def warnings_state(module):
19 """Use a specific warnings implementation in warning_tests."""
20 global __warningregistry__
21 for to_clear in (sys, warning_tests):
22 try:
23 to_clear.__warningregistry__.clear()
24 except AttributeError:
25 pass
26 try:
27 __warningregistry__.clear()
28 except NameError:
29 pass
30 original_warnings = warning_tests.warnings
Florent Xiclunafd1b0932010-03-28 00:25:02 +000031 original_filters = module.filters
Christian Heimes33fe8092008-04-13 13:53:33 +000032 try:
Florent Xiclunafd1b0932010-03-28 00:25:02 +000033 module.filters = original_filters[:]
34 module.simplefilter("once")
Christian Heimes33fe8092008-04-13 13:53:33 +000035 warning_tests.warnings = module
36 yield
37 finally:
38 warning_tests.warnings = original_warnings
Florent Xiclunafd1b0932010-03-28 00:25:02 +000039 module.filters = original_filters
Christian Heimes33fe8092008-04-13 13:53:33 +000040
41
42class BaseTest(unittest.TestCase):
43
44 """Basic bookkeeping required for testing."""
45
46 def setUp(self):
47 # The __warningregistry__ needs to be in a pristine state for tests
48 # to work properly.
49 if '__warningregistry__' in globals():
50 del globals()['__warningregistry__']
51 if hasattr(warning_tests, '__warningregistry__'):
52 del warning_tests.__warningregistry__
53 if hasattr(sys, '__warningregistry__'):
54 del sys.__warningregistry__
55 # The 'warnings' module must be explicitly set so that the proper
56 # interaction between _warnings and 'warnings' can be controlled.
57 sys.modules['warnings'] = self.module
58 super(BaseTest, self).setUp()
59
60 def tearDown(self):
61 sys.modules['warnings'] = original_warnings
62 super(BaseTest, self).tearDown()
63
64
65class FilterTests(object):
66
67 """Testing the filtering functionality."""
68
69 def test_error(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000070 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000071 self.module.resetwarnings()
72 self.module.filterwarnings("error", category=UserWarning)
73 self.assertRaises(UserWarning, self.module.warn,
74 "FilterTests.test_error")
75
76 def test_ignore(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000077 with original_warnings.catch_warnings(record=True,
78 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000079 self.module.resetwarnings()
80 self.module.filterwarnings("ignore", category=UserWarning)
81 self.module.warn("FilterTests.test_ignore", UserWarning)
Brett Cannonec92e182008-09-02 02:46:59 +000082 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +000083
84 def test_always(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000085 with original_warnings.catch_warnings(record=True,
86 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000087 self.module.resetwarnings()
88 self.module.filterwarnings("always", category=UserWarning)
89 message = "FilterTests.test_always"
90 self.module.warn(message, UserWarning)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000091 self.assertTrue(message, w[-1].message)
Christian Heimes33fe8092008-04-13 13:53:33 +000092 self.module.warn(message, UserWarning)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000093 self.assertTrue(w[-1].message, message)
Christian Heimes33fe8092008-04-13 13:53:33 +000094
95 def test_default(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000096 with original_warnings.catch_warnings(record=True,
97 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000098 self.module.resetwarnings()
99 self.module.filterwarnings("default", category=UserWarning)
100 message = UserWarning("FilterTests.test_default")
101 for x in range(2):
102 self.module.warn(message, UserWarning)
103 if x == 0:
Brett Cannon1cd02472008-09-09 01:52:27 +0000104 self.assertEquals(w[-1].message, message)
105 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000106 elif x == 1:
Brett Cannon1cd02472008-09-09 01:52:27 +0000107 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000108 else:
109 raise ValueError("loop variant unhandled")
110
111 def test_module(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000112 with original_warnings.catch_warnings(record=True,
113 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000114 self.module.resetwarnings()
115 self.module.filterwarnings("module", category=UserWarning)
116 message = UserWarning("FilterTests.test_module")
117 self.module.warn(message, UserWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +0000118 self.assertEquals(w[-1].message, message)
119 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000120 self.module.warn(message, UserWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +0000121 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000122
123 def test_once(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000124 with original_warnings.catch_warnings(record=True,
125 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000126 self.module.resetwarnings()
127 self.module.filterwarnings("once", category=UserWarning)
128 message = UserWarning("FilterTests.test_once")
129 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
130 42)
Brett Cannon1cd02472008-09-09 01:52:27 +0000131 self.assertEquals(w[-1].message, message)
132 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000133 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
134 13)
Brett Cannonec92e182008-09-02 02:46:59 +0000135 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000136 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
137 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000138 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000139
140 def test_inheritance(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000141 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000142 self.module.resetwarnings()
143 self.module.filterwarnings("error", category=Warning)
144 self.assertRaises(UserWarning, self.module.warn,
145 "FilterTests.test_inheritance", UserWarning)
146
147 def test_ordering(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000148 with original_warnings.catch_warnings(record=True,
149 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000150 self.module.resetwarnings()
151 self.module.filterwarnings("ignore", category=UserWarning)
152 self.module.filterwarnings("error", category=UserWarning,
153 append=True)
Brett Cannon1cd02472008-09-09 01:52:27 +0000154 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000155 try:
156 self.module.warn("FilterTests.test_ordering", UserWarning)
157 except UserWarning:
158 self.fail("order handling for actions failed")
Brett Cannonec92e182008-09-02 02:46:59 +0000159 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000160
161 def test_filterwarnings(self):
162 # Test filterwarnings().
163 # Implicitly also tests resetwarnings().
Brett Cannon1cd02472008-09-09 01:52:27 +0000164 with original_warnings.catch_warnings(record=True,
165 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000166 self.module.filterwarnings("error", "", Warning, "", 0)
167 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
168
169 self.module.resetwarnings()
170 text = 'handle normally'
171 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000172 self.assertEqual(str(w[-1].message), text)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000173 self.assertTrue(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000174
175 self.module.filterwarnings("ignore", "", Warning, "", 0)
176 text = 'filtered out'
177 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000178 self.assertNotEqual(str(w[-1].message), text)
Christian Heimes33fe8092008-04-13 13:53:33 +0000179
180 self.module.resetwarnings()
181 self.module.filterwarnings("error", "hex*", Warning, "", 0)
182 self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
183 text = 'nonmatching text'
184 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000185 self.assertEqual(str(w[-1].message), text)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000186 self.assertTrue(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000187
188class CFilterTests(BaseTest, FilterTests):
189 module = c_warnings
190
191class PyFilterTests(BaseTest, FilterTests):
192 module = py_warnings
193
194
195class WarnTests(unittest.TestCase):
196
197 """Test warnings.warn() and warnings.warn_explicit()."""
198
199 def test_message(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000200 with original_warnings.catch_warnings(record=True,
201 module=self.module) as w:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000202 self.module.simplefilter("once")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000203 for i in range(4):
Christian Heimes33fe8092008-04-13 13:53:33 +0000204 text = 'multi %d' %i # Different text on each call.
205 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000206 self.assertEqual(str(w[-1].message), text)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000207 self.assertTrue(w[-1].category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000208
Brett Cannon54bd41d2008-09-02 04:01:42 +0000209 # Issue 3639
210 def test_warn_nonstandard_types(self):
211 # warn() should handle non-standard types without issue.
212 for ob in (Warning, None, 42):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000213 with original_warnings.catch_warnings(record=True,
214 module=self.module) as w:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000215 self.module.simplefilter("once")
Brett Cannon54bd41d2008-09-02 04:01:42 +0000216 self.module.warn(ob)
217 # Don't directly compare objects since
218 # ``Warning() != Warning()``.
Brett Cannon1cd02472008-09-09 01:52:27 +0000219 self.assertEquals(str(w[-1].message), str(UserWarning(ob)))
Brett Cannon54bd41d2008-09-02 04:01:42 +0000220
Guido van Rossumd8faa362007-04-27 19:54:29 +0000221 def test_filename(self):
Christian Heimes33fe8092008-04-13 13:53:33 +0000222 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000223 with original_warnings.catch_warnings(record=True,
224 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000225 warning_tests.inner("spam1")
Brett Cannon1cd02472008-09-09 01:52:27 +0000226 self.assertEqual(os.path.basename(w[-1].filename),
227 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000228 warning_tests.outer("spam2")
Brett Cannon1cd02472008-09-09 01:52:27 +0000229 self.assertEqual(os.path.basename(w[-1].filename),
230 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000231
232 def test_stacklevel(self):
233 # Test stacklevel argument
234 # make sure all messages are different, so the warning won't be skipped
Christian Heimes33fe8092008-04-13 13:53:33 +0000235 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000236 with original_warnings.catch_warnings(record=True,
237 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000238 warning_tests.inner("spam3", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000239 self.assertEqual(os.path.basename(w[-1].filename),
240 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000241 warning_tests.outer("spam4", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000242 self.assertEqual(os.path.basename(w[-1].filename),
243 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000244
Christian Heimes33fe8092008-04-13 13:53:33 +0000245 warning_tests.inner("spam5", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000246 self.assertEqual(os.path.basename(w[-1].filename),
247 "test_warnings.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000248 warning_tests.outer("spam6", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000249 self.assertEqual(os.path.basename(w[-1].filename),
250 "warning_tests.py")
Christian Heimes5d8da202008-05-06 13:58:24 +0000251 warning_tests.outer("spam6.5", stacklevel=3)
Brett Cannon1cd02472008-09-09 01:52:27 +0000252 self.assertEqual(os.path.basename(w[-1].filename),
253 "test_warnings.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000254
Christian Heimes33fe8092008-04-13 13:53:33 +0000255 warning_tests.inner("spam7", stacklevel=9999)
Brett Cannon1cd02472008-09-09 01:52:27 +0000256 self.assertEqual(os.path.basename(w[-1].filename),
257 "sys")
Christian Heimes33fe8092008-04-13 13:53:33 +0000258
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000259 def test_missing_filename_not_main(self):
260 # If __file__ is not specified and __main__ is not the module name,
261 # then __file__ should be set to the module name.
262 filename = warning_tests.__file__
263 try:
264 del warning_tests.__file__
265 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000266 with original_warnings.catch_warnings(record=True,
267 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000268 warning_tests.inner("spam8", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000269 self.assertEqual(w[-1].filename, warning_tests.__name__)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000270 finally:
271 warning_tests.__file__ = filename
272
273 def test_missing_filename_main_with_argv(self):
274 # If __file__ is not specified and the caller is __main__ and sys.argv
275 # exists, then use sys.argv[0] as the file.
276 if not hasattr(sys, 'argv'):
277 return
278 filename = warning_tests.__file__
279 module_name = warning_tests.__name__
280 try:
281 del warning_tests.__file__
282 warning_tests.__name__ = '__main__'
283 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000284 with original_warnings.catch_warnings(record=True,
285 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000286 warning_tests.inner('spam9', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000287 self.assertEqual(w[-1].filename, sys.argv[0])
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000288 finally:
289 warning_tests.__file__ = filename
290 warning_tests.__name__ = module_name
291
292 def test_missing_filename_main_without_argv(self):
293 # If __file__ is not specified, the caller is __main__, and sys.argv
294 # is not set, then '__main__' is the file name.
295 filename = warning_tests.__file__
296 module_name = warning_tests.__name__
297 argv = sys.argv
298 try:
299 del warning_tests.__file__
300 warning_tests.__name__ = '__main__'
301 del sys.argv
302 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000303 with original_warnings.catch_warnings(record=True,
304 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000305 warning_tests.inner('spam10', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000306 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000307 finally:
308 warning_tests.__file__ = filename
309 warning_tests.__name__ = module_name
310 sys.argv = argv
311
Christian Heimesdaaf8ee2008-05-04 23:58:41 +0000312 def test_missing_filename_main_with_argv_empty_string(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000313 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
314 # is the empty string, then '__main__ is the file name.
315 # Tests issue 2743.
316 file_name = warning_tests.__file__
317 module_name = warning_tests.__name__
318 argv = sys.argv
319 try:
320 del warning_tests.__file__
321 warning_tests.__name__ = '__main__'
322 sys.argv = ['']
323 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000324 with original_warnings.catch_warnings(record=True,
325 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000326 warning_tests.inner('spam11', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000327 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000328 finally:
329 warning_tests.__file__ = file_name
330 warning_tests.__name__ = module_name
331 sys.argv = argv
332
Brett Cannondb734912008-06-27 00:52:15 +0000333 def test_warn_explicit_type_errors(self):
334 # warn_explicit() shoud error out gracefully if it is given objects
335 # of the wrong types.
336 # lineno is expected to be an integer.
337 self.assertRaises(TypeError, self.module.warn_explicit,
338 None, UserWarning, None, None)
339 # Either 'message' needs to be an instance of Warning or 'category'
340 # needs to be a subclass.
341 self.assertRaises(TypeError, self.module.warn_explicit,
342 None, None, None, 1)
343 # 'registry' must be a dict or None.
344 self.assertRaises((TypeError, AttributeError),
345 self.module.warn_explicit,
346 None, Warning, None, 1, registry=42)
347
Hirokazu Yamamoto1c0c0032009-07-17 06:55:42 +0000348 def test_bad_str(self):
349 # issue 6415
350 # Warnings instance with a bad format string for __str__ should not
351 # trigger a bus error.
352 class BadStrWarning(Warning):
353 """Warning with a bad format string for __str__."""
354 def __str__(self):
355 return ("A bad formatted string %(err)" %
356 {"err" : "there is no %(err)s"})
357
358 with self.assertRaises(ValueError):
359 self.module.warn(BadStrWarning())
360
361
Christian Heimes33fe8092008-04-13 13:53:33 +0000362class CWarnTests(BaseTest, WarnTests):
363 module = c_warnings
364
Nick Coghlanfce769e2009-04-11 14:30:59 +0000365 # As an early adopter, we sanity check the
366 # test.support.import_fresh_module utility function
367 def test_accelerated(self):
368 self.assertFalse(original_warnings is self.module)
369 self.assertFalse(hasattr(self.module.warn, '__code__'))
370
Christian Heimes33fe8092008-04-13 13:53:33 +0000371class PyWarnTests(BaseTest, WarnTests):
372 module = py_warnings
373
Nick Coghlanfce769e2009-04-11 14:30:59 +0000374 # As an early adopter, we sanity check the
375 # test.support.import_fresh_module utility function
376 def test_pure_python(self):
377 self.assertFalse(original_warnings is self.module)
378 self.assertTrue(hasattr(self.module.warn, '__code__'))
379
Christian Heimes33fe8092008-04-13 13:53:33 +0000380
381class WCmdLineTests(unittest.TestCase):
382
383 def test_improper_input(self):
384 # Uses the private _setoption() function to test the parsing
385 # of command-line warning arguments
Brett Cannon1cd02472008-09-09 01:52:27 +0000386 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000387 self.assertRaises(self.module._OptionError,
388 self.module._setoption, '1:2:3:4:5:6')
389 self.assertRaises(self.module._OptionError,
390 self.module._setoption, 'bogus::Warning')
391 self.assertRaises(self.module._OptionError,
392 self.module._setoption, 'ignore:2::4:-5')
393 self.module._setoption('error::Warning::0')
394 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
395
396class CWCmdLineTests(BaseTest, WCmdLineTests):
397 module = c_warnings
398
399class PyWCmdLineTests(BaseTest, WCmdLineTests):
400 module = py_warnings
401
402
403class _WarningsTests(BaseTest):
404
405 """Tests specific to the _warnings module."""
406
407 module = c_warnings
408
409 def test_filter(self):
410 # Everything should function even if 'filters' is not in warnings.
Brett Cannon1cd02472008-09-09 01:52:27 +0000411 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000412 self.module.filterwarnings("error", "", Warning, "", 0)
413 self.assertRaises(UserWarning, self.module.warn,
414 'convert to error')
415 del self.module.filters
416 self.assertRaises(UserWarning, self.module.warn,
417 'convert to error')
418
419 def test_onceregistry(self):
420 # Replacing or removing the onceregistry should be okay.
421 global __warningregistry__
422 message = UserWarning('onceregistry test')
423 try:
424 original_registry = self.module.onceregistry
425 __warningregistry__ = {}
Brett Cannon1cd02472008-09-09 01:52:27 +0000426 with original_warnings.catch_warnings(record=True,
427 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000428 self.module.resetwarnings()
429 self.module.filterwarnings("once", category=UserWarning)
430 self.module.warn_explicit(message, UserWarning, "file", 42)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000431 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000432 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000433 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000434 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000435 # Test the resetting of onceregistry.
436 self.module.onceregistry = {}
437 __warningregistry__ = {}
438 self.module.warn('onceregistry test')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000439 self.assertEqual(w[-1].message.args, message.args)
Christian Heimes33fe8092008-04-13 13:53:33 +0000440 # Removal of onceregistry is okay.
Brett Cannon1cd02472008-09-09 01:52:27 +0000441 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000442 del self.module.onceregistry
443 __warningregistry__ = {}
444 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000445 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000446 finally:
447 self.module.onceregistry = original_registry
448
Brett Cannon0759dd62009-04-01 18:13:07 +0000449 def test_default_action(self):
450 # Replacing or removing defaultaction should be okay.
451 message = UserWarning("defaultaction test")
452 original = self.module.defaultaction
453 try:
454 with original_warnings.catch_warnings(record=True,
455 module=self.module) as w:
456 self.module.resetwarnings()
457 registry = {}
458 self.module.warn_explicit(message, UserWarning, "<test>", 42,
459 registry=registry)
460 self.assertEqual(w[-1].message, message)
461 self.assertEqual(len(w), 1)
462 self.assertEqual(len(registry), 1)
463 del w[:]
464 # Test removal.
465 del self.module.defaultaction
466 __warningregistry__ = {}
467 registry = {}
468 self.module.warn_explicit(message, UserWarning, "<test>", 43,
469 registry=registry)
470 self.assertEqual(w[-1].message, message)
471 self.assertEqual(len(w), 1)
472 self.assertEqual(len(registry), 1)
473 del w[:]
474 # Test setting.
475 self.module.defaultaction = "ignore"
476 __warningregistry__ = {}
477 registry = {}
478 self.module.warn_explicit(message, UserWarning, "<test>", 44,
479 registry=registry)
480 self.assertEqual(len(w), 0)
481 finally:
482 self.module.defaultaction = original
483
Christian Heimes33fe8092008-04-13 13:53:33 +0000484 def test_showwarning_missing(self):
485 # Test that showwarning() missing is okay.
486 text = 'del showwarning test'
Brett Cannon1cd02472008-09-09 01:52:27 +0000487 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000488 self.module.filterwarnings("always", category=UserWarning)
489 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000490 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000491 self.module.warn(text)
492 result = stream.getvalue()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000493 self.assertIn(text, result)
Christian Heimes33fe8092008-04-13 13:53:33 +0000494
Christian Heimes8dc226f2008-05-06 23:45:46 +0000495 def test_showwarning_not_callable(self):
Brett Cannonfcc05272009-04-01 20:27:29 +0000496 with original_warnings.catch_warnings(module=self.module):
497 self.module.filterwarnings("always", category=UserWarning)
498 old_showwarning = self.module.showwarning
499 self.module.showwarning = 23
500 try:
501 self.assertRaises(TypeError, self.module.warn, "Warning!")
502 finally:
503 self.module.showwarning = old_showwarning
Christian Heimes8dc226f2008-05-06 23:45:46 +0000504
Christian Heimes33fe8092008-04-13 13:53:33 +0000505 def test_show_warning_output(self):
506 # With showarning() missing, make sure that output is okay.
507 text = 'test show_warning'
Brett Cannon1cd02472008-09-09 01:52:27 +0000508 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000509 self.module.filterwarnings("always", category=UserWarning)
510 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000511 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000512 warning_tests.inner(text)
513 result = stream.getvalue()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000514 self.assertEqual(result.count('\n'), 2,
Christian Heimes33fe8092008-04-13 13:53:33 +0000515 "Too many newlines in %r" % result)
516 first_line, second_line = result.split('\n', 1)
517 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Neal Norwitz32dde222008-04-15 06:43:13 +0000518 first_line_parts = first_line.rsplit(':', 3)
519 path, line, warning_class, message = first_line_parts
Christian Heimes33fe8092008-04-13 13:53:33 +0000520 line = int(line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000521 self.assertEqual(expected_file, path)
522 self.assertEqual(warning_class, ' ' + UserWarning.__name__)
523 self.assertEqual(message, ' ' + text)
Christian Heimes33fe8092008-04-13 13:53:33 +0000524 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
525 assert expected_line
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000526 self.assertEqual(second_line, expected_line)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000527
528
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000529class WarningsDisplayTests(unittest.TestCase):
530
Christian Heimes33fe8092008-04-13 13:53:33 +0000531 """Test the displaying of warnings and the ability to overload functions
532 related to displaying warnings."""
533
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000534 def test_formatwarning(self):
535 message = "msg"
536 category = Warning
537 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
538 line_num = 3
539 file_line = linecache.getline(file_name, line_num).strip()
Christian Heimes33fe8092008-04-13 13:53:33 +0000540 format = "%s:%s: %s: %s\n %s\n"
541 expect = format % (file_name, line_num, category.__name__, message,
542 file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000543 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000544 category, file_name, line_num))
545 # Test the 'line' argument.
546 file_line += " for the win!"
547 expect = format % (file_name, line_num, category.__name__, message,
548 file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000549 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000550 category, file_name, line_num, file_line))
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000551
552 def test_showwarning(self):
553 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
554 line_num = 3
555 expected_file_line = linecache.getline(file_name, line_num).strip()
556 message = 'msg'
557 category = Warning
558 file_object = StringIO()
Christian Heimes33fe8092008-04-13 13:53:33 +0000559 expect = self.module.formatwarning(message, category, file_name,
560 line_num)
561 self.module.showwarning(message, category, file_name, line_num,
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000562 file_object)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000563 self.assertEqual(file_object.getvalue(), expect)
Christian Heimes33fe8092008-04-13 13:53:33 +0000564 # Test 'line' argument.
565 expected_file_line += "for the win!"
566 expect = self.module.formatwarning(message, category, file_name,
567 line_num, expected_file_line)
568 file_object = StringIO()
569 self.module.showwarning(message, category, file_name, line_num,
570 file_object, expected_file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000571 self.assertEqual(expect, file_object.getvalue())
Christian Heimes33fe8092008-04-13 13:53:33 +0000572
573class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
574 module = c_warnings
575
576class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
577 module = py_warnings
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000578
Brett Cannon1cd02472008-09-09 01:52:27 +0000579
Brett Cannonec92e182008-09-02 02:46:59 +0000580class CatchWarningTests(BaseTest):
Nick Coghlanb1304932008-07-13 12:25:08 +0000581
Brett Cannonec92e182008-09-02 02:46:59 +0000582 """Test catch_warnings()."""
583
584 def test_catch_warnings_restore(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000585 wmod = self.module
586 orig_filters = wmod.filters
587 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000588 # Ensure both showwarning and filters are restored when recording
589 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlanb1304932008-07-13 12:25:08 +0000590 wmod.filters = wmod.showwarning = object()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000591 self.assertTrue(wmod.filters is orig_filters)
592 self.assertTrue(wmod.showwarning is orig_showwarning)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000593 # Same test, but with recording disabled
594 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlanb1304932008-07-13 12:25:08 +0000595 wmod.filters = wmod.showwarning = object()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000596 self.assertTrue(wmod.filters is orig_filters)
597 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000598
Brett Cannonec92e182008-09-02 02:46:59 +0000599 def test_catch_warnings_recording(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000600 wmod = self.module
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000601 # Ensure warnings are recorded when requested
602 with wmod.catch_warnings(module=wmod, record=True) as w:
Brett Cannonec92e182008-09-02 02:46:59 +0000603 self.assertEqual(w, [])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000604 self.assertTrue(type(w) is list)
Nick Coghlanb1304932008-07-13 12:25:08 +0000605 wmod.simplefilter("always")
606 wmod.warn("foo")
Brett Cannon1cd02472008-09-09 01:52:27 +0000607 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlanb1304932008-07-13 12:25:08 +0000608 wmod.warn("bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000609 self.assertEqual(str(w[-1].message), "bar")
Brett Cannonec92e182008-09-02 02:46:59 +0000610 self.assertEqual(str(w[0].message), "foo")
611 self.assertEqual(str(w[1].message), "bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000612 del w[:]
Brett Cannonec92e182008-09-02 02:46:59 +0000613 self.assertEqual(w, [])
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000614 # Ensure warnings are not recorded when not requested
Nick Coghlanb1304932008-07-13 12:25:08 +0000615 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000616 with wmod.catch_warnings(module=wmod, record=False) as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000617 self.assertTrue(w is None)
618 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000619
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000620 def test_catch_warnings_reentry_guard(self):
621 wmod = self.module
622 # Ensure catch_warnings is protected against incorrect usage
623 x = wmod.catch_warnings(module=wmod, record=True)
624 self.assertRaises(RuntimeError, x.__exit__)
625 with x:
626 self.assertRaises(RuntimeError, x.__enter__)
627 # Same test, but with recording disabled
628 x = wmod.catch_warnings(module=wmod, record=False)
629 self.assertRaises(RuntimeError, x.__exit__)
630 with x:
631 self.assertRaises(RuntimeError, x.__enter__)
632
633 def test_catch_warnings_defaults(self):
634 wmod = self.module
635 orig_filters = wmod.filters
636 orig_showwarning = wmod.showwarning
637 # Ensure default behaviour is not to record warnings
638 with wmod.catch_warnings(module=wmod) as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000639 self.assertTrue(w is None)
640 self.assertTrue(wmod.showwarning is orig_showwarning)
641 self.assertTrue(wmod.filters is not orig_filters)
642 self.assertTrue(wmod.filters is orig_filters)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000643 if wmod is sys.modules['warnings']:
644 # Ensure the default module is this one
645 with wmod.catch_warnings() as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000646 self.assertTrue(w is None)
647 self.assertTrue(wmod.showwarning is orig_showwarning)
648 self.assertTrue(wmod.filters is not orig_filters)
649 self.assertTrue(wmod.filters is orig_filters)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000650
651 def test_check_warnings(self):
652 # Explicit tests for the test.support convenience wrapper
653 wmod = self.module
Florent Xicluna53b506be2010-03-18 20:00:57 +0000654 if wmod is not sys.modules['warnings']:
655 return
656 with support.check_warnings(quiet=False) as w:
657 self.assertEqual(w.warnings, [])
658 wmod.simplefilter("always")
659 wmod.warn("foo")
660 self.assertEqual(str(w.message), "foo")
661 wmod.warn("bar")
662 self.assertEqual(str(w.message), "bar")
663 self.assertEqual(str(w.warnings[0].message), "foo")
664 self.assertEqual(str(w.warnings[1].message), "bar")
665 w.reset()
666 self.assertEqual(w.warnings, [])
667
668 with support.check_warnings():
669 # defaults to quiet=True without argument
670 pass
671 with support.check_warnings(('foo', UserWarning)):
672 wmod.warn("foo")
673
674 with self.assertRaises(AssertionError):
675 with support.check_warnings(('', RuntimeWarning)):
676 # defaults to quiet=False with argument
677 pass
678 with self.assertRaises(AssertionError):
679 with support.check_warnings(('foo', RuntimeWarning)):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000680 wmod.warn("foo")
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000681
Brett Cannonec92e182008-09-02 02:46:59 +0000682class CCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000683 module = c_warnings
684
Brett Cannonec92e182008-09-02 02:46:59 +0000685class PyCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000686 module = py_warnings
687
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000688
Philip Jenvey0805ca32010-04-07 04:04:10 +0000689class EnvironmentVariableTests(BaseTest):
690
691 def test_single_warning(self):
692 newenv = os.environ.copy()
693 newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
694 p = subprocess.Popen([sys.executable,
695 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
696 stdout=subprocess.PIPE, env=newenv)
Benjamin Petersonad6139a2010-04-11 21:16:33 +0000697 self.assertEqual(p.communicate()[0], b"['ignore::DeprecationWarning']")
698 self.assertEqual(p.wait(), 0)
Philip Jenvey0805ca32010-04-07 04:04:10 +0000699
700 def test_comma_separated_warnings(self):
701 newenv = os.environ.copy()
702 newenv["PYTHONWARNINGS"] = ("ignore::DeprecationWarning,"
703 "ignore::UnicodeWarning")
704 p = subprocess.Popen([sys.executable,
705 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
706 stdout=subprocess.PIPE, env=newenv)
Benjamin Petersonad6139a2010-04-11 21:16:33 +0000707 self.assertEqual(p.communicate()[0],
Philip Jenvey0805ca32010-04-07 04:04:10 +0000708 b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
Benjamin Petersonad6139a2010-04-11 21:16:33 +0000709 self.assertEqual(p.wait(), 0)
Philip Jenvey0805ca32010-04-07 04:04:10 +0000710
711 def test_envvar_and_command_line(self):
712 newenv = os.environ.copy()
713 newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
714 p = subprocess.Popen([sys.executable, "-W" "ignore::UnicodeWarning",
715 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
716 stdout=subprocess.PIPE, env=newenv)
Benjamin Petersonad6139a2010-04-11 21:16:33 +0000717 self.assertEqual(p.communicate()[0],
Philip Jenvey0805ca32010-04-07 04:04:10 +0000718 b"['ignore::UnicodeWarning', 'ignore::DeprecationWarning']")
Benjamin Petersonad6139a2010-04-11 21:16:33 +0000719 self.assertEqual(p.wait(), 0)
Philip Jenvey0805ca32010-04-07 04:04:10 +0000720
Philip Jenveye53de3d2010-04-14 03:01:39 +0000721 @unittest.skipUnless(sys.getfilesystemencoding() != 'ascii',
722 'requires non-ascii filesystemencoding')
723 def test_nonascii(self):
724 newenv = os.environ.copy()
725 newenv["PYTHONWARNINGS"] = "ignore:DeprecaciónWarning"
726 newenv["PYTHONIOENCODING"] = "utf-8"
727 p = subprocess.Popen([sys.executable,
728 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
729 stdout=subprocess.PIPE, env=newenv)
730 self.assertEqual(p.communicate()[0],
731 "['ignore:DeprecaciónWarning']".encode('utf-8'))
732 self.assertEqual(p.wait(), 0)
733
Philip Jenvey0805ca32010-04-07 04:04:10 +0000734class CEnvironmentVariableTests(EnvironmentVariableTests):
735 module = c_warnings
736
737class PyEnvironmentVariableTests(EnvironmentVariableTests):
738 module = py_warnings
739
740
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000741class BootstrapTest(unittest.TestCase):
742 def test_issue_8766(self):
743 # "import encodings" emits a warning whereas the warnings is not loaded
744 # or not completly loaded (warnings imports indirectly encodings by
745 # importing linecache) yet
746 with support.temp_cwd() as cwd, support.temp_cwd('encodings'):
747 env = os.environ.copy()
748 env['PYTHONPATH'] = cwd
749
750 # encodings loaded by initfsencoding()
751 retcode = subprocess.call([sys.executable, '-c', 'pass'], env=env)
752 self.assertEqual(retcode, 0)
753
754 # Use -W to load warnings module at startup
755 retcode = subprocess.call(
756 [sys.executable, '-c', 'pass', '-W', 'always'],
757 env=env)
758 self.assertEqual(retcode, 0)
759
Christian Heimes33fe8092008-04-13 13:53:33 +0000760def test_main():
Christian Heimesdae2a892008-04-19 00:55:37 +0000761 py_warnings.onceregistry.clear()
762 c_warnings.onceregistry.clear()
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000763 support.run_unittest(
764 CFilterTests, PyFilterTests,
765 CWarnTests, PyWarnTests,
766 CWCmdLineTests, PyWCmdLineTests,
767 _WarningsTests,
768 CWarningsDisplayTests, PyWarningsDisplayTests,
769 CCatchWarningTests, PyCatchWarningTests,
770 CEnvironmentVariableTests, PyEnvironmentVariableTests,
771 BootstrapTest,
772 )
Christian Heimes33fe8092008-04-13 13:53:33 +0000773
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000774
775if __name__ == "__main__":
Christian Heimes33fe8092008-04-13 13:53:33 +0000776 test_main()