blob: 5cf1034a5da524f7e1f97ed6771ae89b272510cb [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 shutil
8import tempfile
9import subprocess
Benjamin Petersonee8712c2008-05-20 21:35:26 +000010from test import support
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)
Brett Cannonec92e182008-09-02 02:46:59 +000084 self.assertEquals(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:
Brett Cannon1cd02472008-09-09 01:52:27 +0000106 self.assertEquals(w[-1].message, message)
107 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000108 elif x == 1:
Brett Cannon1cd02472008-09-09 01:52:27 +0000109 self.assertEquals(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)
Brett Cannon1cd02472008-09-09 01:52:27 +0000120 self.assertEquals(w[-1].message, message)
121 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000122 self.module.warn(message, UserWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +0000123 self.assertEquals(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)
Brett Cannon1cd02472008-09-09 01:52:27 +0000133 self.assertEquals(w[-1].message, message)
134 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000135 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
136 13)
Brett Cannonec92e182008-09-02 02:46:59 +0000137 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000138 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
139 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000140 self.assertEquals(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")
Brett Cannonec92e182008-09-02 02:46:59 +0000161 self.assertEquals(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()``.
Brett Cannon1cd02472008-09-09 01:52:27 +0000221 self.assertEquals(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
398class CWCmdLineTests(BaseTest, WCmdLineTests):
399 module = c_warnings
400
401class PyWCmdLineTests(BaseTest, WCmdLineTests):
402 module = py_warnings
403
404
405class _WarningsTests(BaseTest):
406
407 """Tests specific to the _warnings module."""
408
409 module = c_warnings
410
411 def test_filter(self):
412 # Everything should function even if 'filters' is not in warnings.
Brett Cannon1cd02472008-09-09 01:52:27 +0000413 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000414 self.module.filterwarnings("error", "", Warning, "", 0)
415 self.assertRaises(UserWarning, self.module.warn,
416 'convert to error')
417 del self.module.filters
418 self.assertRaises(UserWarning, self.module.warn,
419 'convert to error')
420
421 def test_onceregistry(self):
422 # Replacing or removing the onceregistry should be okay.
423 global __warningregistry__
424 message = UserWarning('onceregistry test')
425 try:
426 original_registry = self.module.onceregistry
427 __warningregistry__ = {}
Brett Cannon1cd02472008-09-09 01:52:27 +0000428 with original_warnings.catch_warnings(record=True,
429 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000430 self.module.resetwarnings()
431 self.module.filterwarnings("once", category=UserWarning)
432 self.module.warn_explicit(message, UserWarning, "file", 42)
Georg Brandlab91fde2009-08-13 08:51:18 +0000433 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000434 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000435 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000436 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000437 # Test the resetting of onceregistry.
438 self.module.onceregistry = {}
439 __warningregistry__ = {}
440 self.module.warn('onceregistry test')
Georg Brandlab91fde2009-08-13 08:51:18 +0000441 self.assertEqual(w[-1].message.args, message.args)
Christian Heimes33fe8092008-04-13 13:53:33 +0000442 # Removal of onceregistry is okay.
Brett Cannon1cd02472008-09-09 01:52:27 +0000443 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000444 del self.module.onceregistry
445 __warningregistry__ = {}
446 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000447 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000448 finally:
449 self.module.onceregistry = original_registry
450
Brett Cannon0759dd62009-04-01 18:13:07 +0000451 def test_default_action(self):
452 # Replacing or removing defaultaction should be okay.
453 message = UserWarning("defaultaction test")
454 original = self.module.defaultaction
455 try:
456 with original_warnings.catch_warnings(record=True,
457 module=self.module) as w:
458 self.module.resetwarnings()
459 registry = {}
460 self.module.warn_explicit(message, UserWarning, "<test>", 42,
461 registry=registry)
462 self.assertEqual(w[-1].message, message)
463 self.assertEqual(len(w), 1)
464 self.assertEqual(len(registry), 1)
465 del w[:]
466 # Test removal.
467 del self.module.defaultaction
468 __warningregistry__ = {}
469 registry = {}
470 self.module.warn_explicit(message, UserWarning, "<test>", 43,
471 registry=registry)
472 self.assertEqual(w[-1].message, message)
473 self.assertEqual(len(w), 1)
474 self.assertEqual(len(registry), 1)
475 del w[:]
476 # Test setting.
477 self.module.defaultaction = "ignore"
478 __warningregistry__ = {}
479 registry = {}
480 self.module.warn_explicit(message, UserWarning, "<test>", 44,
481 registry=registry)
482 self.assertEqual(len(w), 0)
483 finally:
484 self.module.defaultaction = original
485
Christian Heimes33fe8092008-04-13 13:53:33 +0000486 def test_showwarning_missing(self):
487 # Test that showwarning() missing is okay.
488 text = 'del showwarning test'
Brett Cannon1cd02472008-09-09 01:52:27 +0000489 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000490 self.module.filterwarnings("always", category=UserWarning)
491 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000492 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000493 self.module.warn(text)
494 result = stream.getvalue()
Georg Brandlab91fde2009-08-13 08:51:18 +0000495 self.assertTrue(text in result)
Christian Heimes33fe8092008-04-13 13:53:33 +0000496
Christian Heimes8dc226f2008-05-06 23:45:46 +0000497 def test_showwarning_not_callable(self):
Brett Cannonfcc05272009-04-01 20:27:29 +0000498 with original_warnings.catch_warnings(module=self.module):
499 self.module.filterwarnings("always", category=UserWarning)
500 old_showwarning = self.module.showwarning
501 self.module.showwarning = 23
502 try:
503 self.assertRaises(TypeError, self.module.warn, "Warning!")
504 finally:
505 self.module.showwarning = old_showwarning
Christian Heimes8dc226f2008-05-06 23:45:46 +0000506
Christian Heimes33fe8092008-04-13 13:53:33 +0000507 def test_show_warning_output(self):
508 # With showarning() missing, make sure that output is okay.
509 text = 'test show_warning'
Brett Cannon1cd02472008-09-09 01:52:27 +0000510 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000511 self.module.filterwarnings("always", category=UserWarning)
512 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000513 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000514 warning_tests.inner(text)
515 result = stream.getvalue()
Georg Brandlab91fde2009-08-13 08:51:18 +0000516 self.assertEqual(result.count('\n'), 2,
Christian Heimes33fe8092008-04-13 13:53:33 +0000517 "Too many newlines in %r" % result)
518 first_line, second_line = result.split('\n', 1)
519 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Neal Norwitz32dde222008-04-15 06:43:13 +0000520 first_line_parts = first_line.rsplit(':', 3)
521 path, line, warning_class, message = first_line_parts
Christian Heimes33fe8092008-04-13 13:53:33 +0000522 line = int(line)
Georg Brandlab91fde2009-08-13 08:51:18 +0000523 self.assertEqual(expected_file, path)
524 self.assertEqual(warning_class, ' ' + UserWarning.__name__)
525 self.assertEqual(message, ' ' + text)
Christian Heimes33fe8092008-04-13 13:53:33 +0000526 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
527 assert expected_line
Georg Brandlab91fde2009-08-13 08:51:18 +0000528 self.assertEqual(second_line, expected_line)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000529
530
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000531class WarningsDisplayTests(unittest.TestCase):
532
Christian Heimes33fe8092008-04-13 13:53:33 +0000533 """Test the displaying of warnings and the ability to overload functions
534 related to displaying warnings."""
535
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000536 def test_formatwarning(self):
537 message = "msg"
538 category = Warning
539 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
540 line_num = 3
541 file_line = linecache.getline(file_name, line_num).strip()
Christian Heimes33fe8092008-04-13 13:53:33 +0000542 format = "%s:%s: %s: %s\n %s\n"
543 expect = format % (file_name, line_num, category.__name__, message,
544 file_line)
Georg Brandlab91fde2009-08-13 08:51:18 +0000545 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000546 category, file_name, line_num))
547 # Test the 'line' argument.
548 file_line += " for the win!"
549 expect = format % (file_name, line_num, category.__name__, message,
550 file_line)
Georg Brandlab91fde2009-08-13 08:51:18 +0000551 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000552 category, file_name, line_num, file_line))
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000553
554 def test_showwarning(self):
555 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
556 line_num = 3
557 expected_file_line = linecache.getline(file_name, line_num).strip()
558 message = 'msg'
559 category = Warning
560 file_object = StringIO()
Christian Heimes33fe8092008-04-13 13:53:33 +0000561 expect = self.module.formatwarning(message, category, file_name,
562 line_num)
563 self.module.showwarning(message, category, file_name, line_num,
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000564 file_object)
Georg Brandlab91fde2009-08-13 08:51:18 +0000565 self.assertEqual(file_object.getvalue(), expect)
Christian Heimes33fe8092008-04-13 13:53:33 +0000566 # Test 'line' argument.
567 expected_file_line += "for the win!"
568 expect = self.module.formatwarning(message, category, file_name,
569 line_num, expected_file_line)
570 file_object = StringIO()
571 self.module.showwarning(message, category, file_name, line_num,
572 file_object, expected_file_line)
Georg Brandlab91fde2009-08-13 08:51:18 +0000573 self.assertEqual(expect, file_object.getvalue())
Christian Heimes33fe8092008-04-13 13:53:33 +0000574
575class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
576 module = c_warnings
577
578class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
579 module = py_warnings
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000580
Brett Cannon1cd02472008-09-09 01:52:27 +0000581
Brett Cannonec92e182008-09-02 02:46:59 +0000582class CatchWarningTests(BaseTest):
Nick Coghlanb1304932008-07-13 12:25:08 +0000583
Brett Cannonec92e182008-09-02 02:46:59 +0000584 """Test catch_warnings()."""
585
586 def test_catch_warnings_restore(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000587 wmod = self.module
588 orig_filters = wmod.filters
589 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000590 # Ensure both showwarning and filters are restored when recording
591 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlanb1304932008-07-13 12:25:08 +0000592 wmod.filters = wmod.showwarning = object()
Georg Brandlab91fde2009-08-13 08:51:18 +0000593 self.assertTrue(wmod.filters is orig_filters)
594 self.assertTrue(wmod.showwarning is orig_showwarning)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000595 # Same test, but with recording disabled
596 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlanb1304932008-07-13 12:25:08 +0000597 wmod.filters = wmod.showwarning = object()
Georg Brandlab91fde2009-08-13 08:51:18 +0000598 self.assertTrue(wmod.filters is orig_filters)
599 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000600
Brett Cannonec92e182008-09-02 02:46:59 +0000601 def test_catch_warnings_recording(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000602 wmod = self.module
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000603 # Ensure warnings are recorded when requested
604 with wmod.catch_warnings(module=wmod, record=True) as w:
Brett Cannonec92e182008-09-02 02:46:59 +0000605 self.assertEqual(w, [])
Georg Brandlab91fde2009-08-13 08:51:18 +0000606 self.assertTrue(type(w) is list)
Nick Coghlanb1304932008-07-13 12:25:08 +0000607 wmod.simplefilter("always")
608 wmod.warn("foo")
Brett Cannon1cd02472008-09-09 01:52:27 +0000609 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlanb1304932008-07-13 12:25:08 +0000610 wmod.warn("bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000611 self.assertEqual(str(w[-1].message), "bar")
Brett Cannonec92e182008-09-02 02:46:59 +0000612 self.assertEqual(str(w[0].message), "foo")
613 self.assertEqual(str(w[1].message), "bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000614 del w[:]
Brett Cannonec92e182008-09-02 02:46:59 +0000615 self.assertEqual(w, [])
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000616 # Ensure warnings are not recorded when not requested
Nick Coghlanb1304932008-07-13 12:25:08 +0000617 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000618 with wmod.catch_warnings(module=wmod, record=False) as w:
Georg Brandlab91fde2009-08-13 08:51:18 +0000619 self.assertTrue(w is None)
620 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000621
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000622 def test_catch_warnings_reentry_guard(self):
623 wmod = self.module
624 # Ensure catch_warnings is protected against incorrect usage
625 x = wmod.catch_warnings(module=wmod, record=True)
626 self.assertRaises(RuntimeError, x.__exit__)
627 with x:
628 self.assertRaises(RuntimeError, x.__enter__)
629 # Same test, but with recording disabled
630 x = wmod.catch_warnings(module=wmod, record=False)
631 self.assertRaises(RuntimeError, x.__exit__)
632 with x:
633 self.assertRaises(RuntimeError, x.__enter__)
634
635 def test_catch_warnings_defaults(self):
636 wmod = self.module
637 orig_filters = wmod.filters
638 orig_showwarning = wmod.showwarning
639 # Ensure default behaviour is not to record warnings
640 with wmod.catch_warnings(module=wmod) as w:
Georg Brandlab91fde2009-08-13 08:51:18 +0000641 self.assertTrue(w is None)
642 self.assertTrue(wmod.showwarning is orig_showwarning)
643 self.assertTrue(wmod.filters is not orig_filters)
644 self.assertTrue(wmod.filters is orig_filters)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000645 if wmod is sys.modules['warnings']:
646 # Ensure the default module is this one
647 with wmod.catch_warnings() as w:
Georg Brandlab91fde2009-08-13 08:51:18 +0000648 self.assertTrue(w is None)
649 self.assertTrue(wmod.showwarning is orig_showwarning)
650 self.assertTrue(wmod.filters is not orig_filters)
651 self.assertTrue(wmod.filters is orig_filters)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000652
653 def test_check_warnings(self):
654 # Explicit tests for the test.support convenience wrapper
655 wmod = self.module
656 if wmod is sys.modules['warnings']:
657 with support.check_warnings() as w:
658 self.assertEqual(w.warnings, [])
659 wmod.simplefilter("always")
660 wmod.warn("foo")
661 self.assertEqual(str(w.message), "foo")
662 wmod.warn("bar")
663 self.assertEqual(str(w.message), "bar")
664 self.assertEqual(str(w.warnings[0].message), "foo")
665 self.assertEqual(str(w.warnings[1].message), "bar")
666 w.reset()
667 self.assertEqual(w.warnings, [])
668
Brett Cannonec92e182008-09-02 02:46:59 +0000669class CCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000670 module = c_warnings
671
Brett Cannonec92e182008-09-02 02:46:59 +0000672class PyCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000673 module = py_warnings
674
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000675
Victor Stinner148051a2010-05-20 21:00:34 +0000676class BootstrapTest(unittest.TestCase):
677 def test_issue_8766(self):
678 # "import encodings" emits a warning whereas the warnings is not loaded
679 # or not completly loaded (warnings imports indirectly encodings by
680 # importing linecache) yet
681 old_cwd = os.getcwd()
682 try:
683 cwd = tempfile.mkdtemp()
684 try:
685 os.chdir(cwd)
686 os.mkdir('encodings')
687 env = os.environ.copy()
688 env['PYTHONPATH'] = cwd
689
690 # encodings loaded by initfsencoding()
691 retcode = subprocess.call([sys.executable, '-c', 'pass'], env=env)
692 self.assertEqual(retcode, 0)
693
694 # Use -W to load warnings module at startup
695 retcode = subprocess.call(
696 [sys.executable, '-c', 'pass', '-W', 'always'],
697 env=env)
698 self.assertEqual(retcode, 0)
699 finally:
700 shutil.rmtree(cwd)
701 finally:
702 os.chdir(old_cwd)
703
Christian Heimes33fe8092008-04-13 13:53:33 +0000704def test_main():
Christian Heimesdae2a892008-04-19 00:55:37 +0000705 py_warnings.onceregistry.clear()
706 c_warnings.onceregistry.clear()
Victor Stinner148051a2010-05-20 21:00:34 +0000707 support.run_unittest(
708 CFilterTests, PyFilterTests,
709 CWarnTests, PyWarnTests,
710 CWCmdLineTests, PyWCmdLineTests,
711 _WarningsTests,
712 CWarningsDisplayTests, PyWarningsDisplayTests,
713 CCatchWarningTests, PyCatchWarningTests,
714 BootstrapTest,
715 )
Christian Heimes33fe8092008-04-13 13:53:33 +0000716
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000717
718if __name__ == "__main__":
Christian Heimes33fe8092008-04-13 13:53:33 +0000719 test_main()