blob: 4e0afcc659a6dd6282a627dd7b5fa0e63ee78054 [file] [log] [blame]
Brett Cannone9746892008-04-12 23:44:07 +00001from contextlib import contextmanager
Brett Cannon905c31c2007-12-20 10:09:52 +00002import linecache
Raymond Hettingerdc9dcf12003-07-13 06:15:11 +00003import os
Brett Cannon905c31c2007-12-20 10:09:52 +00004import StringIO
Brett Cannon855da6c2007-08-17 20:16:15 +00005import sys
Raymond Hettingerd6f6e502003-07-13 08:37:40 +00006import unittest
Philip Jenveyaebbaeb2010-04-06 23:24:45 +00007import subprocess
Raymond Hettingerd6f6e502003-07-13 08:37:40 +00008from test import test_support
Jeremy Hylton85014662003-07-11 15:37:59 +00009
Walter Dörwalde1a9b422007-04-03 16:53:43 +000010import warning_tests
11
Brett Cannon667bb4f2008-04-13 02:42:36 +000012import warnings as original_warnings
13
Nick Coghlan5533ff62009-04-22 15:26:04 +000014py_warnings = test_support.import_fresh_module('warnings', blocked=['_warnings'])
15c_warnings = test_support.import_fresh_module('warnings', fresh=['_warnings'])
Brett Cannon667bb4f2008-04-13 02:42:36 +000016
Brett Cannone9746892008-04-12 23:44:07 +000017@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 Xiclunafd37dd42010-03-25 20:39:10 +000031 original_filters = module.filters
Brett Cannone9746892008-04-12 23:44:07 +000032 try:
Florent Xiclunafd37dd42010-03-25 20:39:10 +000033 module.filters = original_filters[:]
34 module.simplefilter("once")
Brett Cannone9746892008-04-12 23:44:07 +000035 warning_tests.warnings = module
36 yield
37 finally:
38 warning_tests.warnings = original_warnings
Florent Xiclunafd37dd42010-03-25 20:39:10 +000039 module.filters = original_filters
Brett Cannone9746892008-04-12 23:44:07 +000040
41
Brett Cannon667bb4f2008-04-13 02:42:36 +000042class BaseTest(unittest.TestCase):
Brett Cannone9746892008-04-12 23:44:07 +000043
Brett Cannon667bb4f2008-04-13 02:42:36 +000044 """Basic bookkeeping required for testing."""
Brett Cannone9746892008-04-12 23:44:07 +000045
46 def setUp(self):
Brett Cannon667bb4f2008-04-13 02:42:36 +000047 # 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."""
Brett Cannone9746892008-04-12 23:44:07 +000068
69 def test_error(self):
Brett Cannon672237d2008-09-09 00:49:16 +000070 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +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 Cannon672237d2008-09-09 00:49:16 +000077 with original_warnings.catch_warnings(record=True,
78 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +000079 self.module.resetwarnings()
80 self.module.filterwarnings("ignore", category=UserWarning)
81 self.module.warn("FilterTests.test_ignore", UserWarning)
Brett Cannon1eaf0742008-09-02 01:25:16 +000082 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +000083
84 def test_always(self):
Brett Cannon672237d2008-09-09 00:49:16 +000085 with original_warnings.catch_warnings(record=True,
86 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +000087 self.module.resetwarnings()
88 self.module.filterwarnings("always", category=UserWarning)
89 message = "FilterTests.test_always"
90 self.module.warn(message, UserWarning)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000091 self.assertTrue(message, w[-1].message)
Brett Cannone9746892008-04-12 23:44:07 +000092 self.module.warn(message, UserWarning)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000093 self.assertTrue(w[-1].message, message)
Brett Cannone9746892008-04-12 23:44:07 +000094
95 def test_default(self):
Brett Cannon672237d2008-09-09 00:49:16 +000096 with original_warnings.catch_warnings(record=True,
97 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +000098 self.module.resetwarnings()
99 self.module.filterwarnings("default", category=UserWarning)
100 message = UserWarning("FilterTests.test_default")
101 for x in xrange(2):
102 self.module.warn(message, UserWarning)
103 if x == 0:
Brett Cannon672237d2008-09-09 00:49:16 +0000104 self.assertEquals(w[-1].message, message)
105 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000106 elif x == 1:
Brett Cannon672237d2008-09-09 00:49:16 +0000107 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000108 else:
109 raise ValueError("loop variant unhandled")
110
111 def test_module(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000112 with original_warnings.catch_warnings(record=True,
113 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000114 self.module.resetwarnings()
115 self.module.filterwarnings("module", category=UserWarning)
116 message = UserWarning("FilterTests.test_module")
117 self.module.warn(message, UserWarning)
Brett Cannon672237d2008-09-09 00:49:16 +0000118 self.assertEquals(w[-1].message, message)
119 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000120 self.module.warn(message, UserWarning)
Brett Cannon672237d2008-09-09 00:49:16 +0000121 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000122
123 def test_once(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000124 with original_warnings.catch_warnings(record=True,
125 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +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 Cannon672237d2008-09-09 00:49:16 +0000131 self.assertEquals(w[-1].message, message)
132 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000133 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
134 13)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000135 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000136 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
137 42)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000138 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000139
140 def test_inheritance(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000141 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +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 Cannon672237d2008-09-09 00:49:16 +0000148 with original_warnings.catch_warnings(record=True,
149 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000150 self.module.resetwarnings()
151 self.module.filterwarnings("ignore", category=UserWarning)
152 self.module.filterwarnings("error", category=UserWarning,
153 append=True)
Brett Cannon672237d2008-09-09 00:49:16 +0000154 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000155 try:
156 self.module.warn("FilterTests.test_ordering", UserWarning)
157 except UserWarning:
158 self.fail("order handling for actions failed")
Brett Cannon1eaf0742008-09-02 01:25:16 +0000159 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000160
161 def test_filterwarnings(self):
162 # Test filterwarnings().
163 # Implicitly also tests resetwarnings().
Brett Cannon672237d2008-09-09 00:49:16 +0000164 with original_warnings.catch_warnings(record=True,
165 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +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 Cannon672237d2008-09-09 00:49:16 +0000172 self.assertEqual(str(w[-1].message), text)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000173 self.assertTrue(w[-1].category is UserWarning)
Brett Cannone9746892008-04-12 23:44:07 +0000174
175 self.module.filterwarnings("ignore", "", Warning, "", 0)
176 text = 'filtered out'
177 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000178 self.assertNotEqual(str(w[-1].message), text)
Brett Cannone9746892008-04-12 23:44:07 +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 Cannon672237d2008-09-09 00:49:16 +0000185 self.assertEqual(str(w[-1].message), text)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000186 self.assertTrue(w[-1].category is UserWarning)
Brett Cannone9746892008-04-12 23:44:07 +0000187
Brett Cannon667bb4f2008-04-13 02:42:36 +0000188class CFilterTests(BaseTest, FilterTests):
Brett Cannone9746892008-04-12 23:44:07 +0000189 module = c_warnings
190
Brett Cannon667bb4f2008-04-13 02:42:36 +0000191class PyFilterTests(BaseTest, FilterTests):
Brett Cannone9746892008-04-12 23:44:07 +0000192 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 Cannon672237d2008-09-09 00:49:16 +0000200 with original_warnings.catch_warnings(record=True,
201 module=self.module) as w:
Florent Xiclunafd37dd42010-03-25 20:39:10 +0000202 self.module.simplefilter("once")
Walter Dörwalde6dae6c2007-04-03 18:33:29 +0000203 for i in range(4):
Brett Cannone9746892008-04-12 23:44:07 +0000204 text = 'multi %d' %i # Different text on each call.
205 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000206 self.assertEqual(str(w[-1].message), text)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000207 self.assertTrue(w[-1].category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000208
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000209 def test_filename(self):
Brett Cannone9746892008-04-12 23:44:07 +0000210 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000211 with original_warnings.catch_warnings(record=True,
212 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000213 warning_tests.inner("spam1")
Brett Cannon672237d2008-09-09 00:49:16 +0000214 self.assertEqual(os.path.basename(w[-1].filename),
215 "warning_tests.py")
Brett Cannone9746892008-04-12 23:44:07 +0000216 warning_tests.outer("spam2")
Brett Cannon672237d2008-09-09 00:49:16 +0000217 self.assertEqual(os.path.basename(w[-1].filename),
218 "warning_tests.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000219
220 def test_stacklevel(self):
221 # Test stacklevel argument
222 # make sure all messages are different, so the warning won't be skipped
Brett Cannone9746892008-04-12 23:44:07 +0000223 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000224 with original_warnings.catch_warnings(record=True,
225 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000226 warning_tests.inner("spam3", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000227 self.assertEqual(os.path.basename(w[-1].filename),
228 "warning_tests.py")
Brett Cannone9746892008-04-12 23:44:07 +0000229 warning_tests.outer("spam4", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000230 self.assertEqual(os.path.basename(w[-1].filename),
231 "warning_tests.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000232
Brett Cannone9746892008-04-12 23:44:07 +0000233 warning_tests.inner("spam5", stacklevel=2)
Brett Cannon672237d2008-09-09 00:49:16 +0000234 self.assertEqual(os.path.basename(w[-1].filename),
235 "test_warnings.py")
Brett Cannone9746892008-04-12 23:44:07 +0000236 warning_tests.outer("spam6", stacklevel=2)
Brett Cannon672237d2008-09-09 00:49:16 +0000237 self.assertEqual(os.path.basename(w[-1].filename),
238 "warning_tests.py")
Brett Cannone3dcb012008-05-06 04:37:31 +0000239 warning_tests.outer("spam6.5", stacklevel=3)
Brett Cannon672237d2008-09-09 00:49:16 +0000240 self.assertEqual(os.path.basename(w[-1].filename),
241 "test_warnings.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000242
Brett Cannone9746892008-04-12 23:44:07 +0000243 warning_tests.inner("spam7", stacklevel=9999)
Brett Cannon672237d2008-09-09 00:49:16 +0000244 self.assertEqual(os.path.basename(w[-1].filename),
245 "sys")
Brett Cannone9746892008-04-12 23:44:07 +0000246
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000247 def test_missing_filename_not_main(self):
248 # If __file__ is not specified and __main__ is not the module name,
249 # then __file__ should be set to the module name.
250 filename = warning_tests.__file__
251 try:
252 del warning_tests.__file__
253 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000254 with original_warnings.catch_warnings(record=True,
255 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000256 warning_tests.inner("spam8", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000257 self.assertEqual(w[-1].filename, warning_tests.__name__)
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000258 finally:
259 warning_tests.__file__ = filename
260
261 def test_missing_filename_main_with_argv(self):
262 # If __file__ is not specified and the caller is __main__ and sys.argv
263 # exists, then use sys.argv[0] as the file.
264 if not hasattr(sys, 'argv'):
265 return
266 filename = warning_tests.__file__
267 module_name = warning_tests.__name__
268 try:
269 del warning_tests.__file__
270 warning_tests.__name__ = '__main__'
271 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000272 with original_warnings.catch_warnings(record=True,
273 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000274 warning_tests.inner('spam9', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000275 self.assertEqual(w[-1].filename, sys.argv[0])
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000276 finally:
277 warning_tests.__file__ = filename
278 warning_tests.__name__ = module_name
279
280 def test_missing_filename_main_without_argv(self):
281 # If __file__ is not specified, the caller is __main__, and sys.argv
282 # is not set, then '__main__' is the file name.
283 filename = warning_tests.__file__
284 module_name = warning_tests.__name__
285 argv = sys.argv
286 try:
287 del warning_tests.__file__
288 warning_tests.__name__ = '__main__'
289 del sys.argv
290 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000291 with original_warnings.catch_warnings(record=True,
292 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000293 warning_tests.inner('spam10', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000294 self.assertEqual(w[-1].filename, '__main__')
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000295 finally:
296 warning_tests.__file__ = filename
297 warning_tests.__name__ = module_name
298 sys.argv = argv
299
300 def test_missing_filename_main_with_argv_empty_string(self):
301 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
302 # is the empty string, then '__main__ is the file name.
303 # Tests issue 2743.
304 file_name = warning_tests.__file__
305 module_name = warning_tests.__name__
306 argv = sys.argv
307 try:
308 del warning_tests.__file__
309 warning_tests.__name__ = '__main__'
310 sys.argv = ['']
311 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000312 with original_warnings.catch_warnings(record=True,
313 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000314 warning_tests.inner('spam11', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000315 self.assertEqual(w[-1].filename, '__main__')
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000316 finally:
317 warning_tests.__file__ = file_name
318 warning_tests.__name__ = module_name
319 sys.argv = argv
320
Brett Cannondea1b562008-06-27 00:31:13 +0000321 def test_warn_explicit_type_errors(self):
322 # warn_explicit() shoud error out gracefully if it is given objects
323 # of the wrong types.
324 # lineno is expected to be an integer.
325 self.assertRaises(TypeError, self.module.warn_explicit,
326 None, UserWarning, None, None)
327 # Either 'message' needs to be an instance of Warning or 'category'
328 # needs to be a subclass.
329 self.assertRaises(TypeError, self.module.warn_explicit,
330 None, None, None, 1)
331 # 'registry' must be a dict or None.
332 self.assertRaises((TypeError, AttributeError),
333 self.module.warn_explicit,
334 None, Warning, None, 1, registry=42)
335
Hirokazu Yamamotoe78e5d22009-07-17 06:20:46 +0000336 def test_bad_str(self):
337 # issue 6415
338 # Warnings instance with a bad format string for __str__ should not
339 # trigger a bus error.
340 class BadStrWarning(Warning):
341 """Warning with a bad format string for __str__."""
342 def __str__(self):
343 return ("A bad formatted string %(err)" %
344 {"err" : "there is no %(err)s"})
345
346 with self.assertRaises(ValueError):
347 self.module.warn(BadStrWarning())
348
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000349
Brett Cannon667bb4f2008-04-13 02:42:36 +0000350class CWarnTests(BaseTest, WarnTests):
Brett Cannone9746892008-04-12 23:44:07 +0000351 module = c_warnings
352
Nick Coghlancd2e7042009-04-11 13:31:31 +0000353 # As an early adopter, we sanity check the
354 # test_support.import_fresh_module utility function
355 def test_accelerated(self):
356 self.assertFalse(original_warnings is self.module)
357 self.assertFalse(hasattr(self.module.warn, 'func_code'))
358
Brett Cannon667bb4f2008-04-13 02:42:36 +0000359class PyWarnTests(BaseTest, WarnTests):
Brett Cannone9746892008-04-12 23:44:07 +0000360 module = py_warnings
361
Nick Coghlancd2e7042009-04-11 13:31:31 +0000362 # As an early adopter, we sanity check the
363 # test_support.import_fresh_module utility function
364 def test_pure_python(self):
365 self.assertFalse(original_warnings is self.module)
366 self.assertTrue(hasattr(self.module.warn, 'func_code'))
367
Brett Cannone9746892008-04-12 23:44:07 +0000368
369class WCmdLineTests(unittest.TestCase):
370
371 def test_improper_input(self):
372 # Uses the private _setoption() function to test the parsing
373 # of command-line warning arguments
Brett Cannon672237d2008-09-09 00:49:16 +0000374 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000375 self.assertRaises(self.module._OptionError,
376 self.module._setoption, '1:2:3:4:5:6')
377 self.assertRaises(self.module._OptionError,
378 self.module._setoption, 'bogus::Warning')
379 self.assertRaises(self.module._OptionError,
380 self.module._setoption, 'ignore:2::4:-5')
381 self.module._setoption('error::Warning::0')
382 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
383
Brett Cannon667bb4f2008-04-13 02:42:36 +0000384class CWCmdLineTests(BaseTest, WCmdLineTests):
Brett Cannone9746892008-04-12 23:44:07 +0000385 module = c_warnings
386
Brett Cannon667bb4f2008-04-13 02:42:36 +0000387class PyWCmdLineTests(BaseTest, WCmdLineTests):
Brett Cannone9746892008-04-12 23:44:07 +0000388 module = py_warnings
389
390
Brett Cannon667bb4f2008-04-13 02:42:36 +0000391class _WarningsTests(BaseTest):
Brett Cannone9746892008-04-12 23:44:07 +0000392
393 """Tests specific to the _warnings module."""
394
395 module = c_warnings
396
397 def test_filter(self):
398 # Everything should function even if 'filters' is not in warnings.
Brett Cannon672237d2008-09-09 00:49:16 +0000399 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000400 self.module.filterwarnings("error", "", Warning, "", 0)
401 self.assertRaises(UserWarning, self.module.warn,
402 'convert to error')
403 del self.module.filters
404 self.assertRaises(UserWarning, self.module.warn,
405 'convert to error')
406
407 def test_onceregistry(self):
408 # Replacing or removing the onceregistry should be okay.
409 global __warningregistry__
410 message = UserWarning('onceregistry test')
411 try:
412 original_registry = self.module.onceregistry
413 __warningregistry__ = {}
Brett Cannon672237d2008-09-09 00:49:16 +0000414 with original_warnings.catch_warnings(record=True,
415 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000416 self.module.resetwarnings()
417 self.module.filterwarnings("once", category=UserWarning)
418 self.module.warn_explicit(message, UserWarning, "file", 42)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000419 self.assertEqual(w[-1].message, message)
Brett Cannon672237d2008-09-09 00:49:16 +0000420 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000421 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000422 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000423 # Test the resetting of onceregistry.
424 self.module.onceregistry = {}
425 __warningregistry__ = {}
426 self.module.warn('onceregistry test')
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000427 self.assertEqual(w[-1].message.args, message.args)
Brett Cannone9746892008-04-12 23:44:07 +0000428 # Removal of onceregistry is okay.
Brett Cannon672237d2008-09-09 00:49:16 +0000429 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000430 del self.module.onceregistry
431 __warningregistry__ = {}
432 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000433 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000434 finally:
435 self.module.onceregistry = original_registry
436
Brett Cannon15ba4da2009-04-01 18:03:59 +0000437 def test_default_action(self):
438 # Replacing or removing defaultaction should be okay.
439 message = UserWarning("defaultaction test")
440 original = self.module.defaultaction
441 try:
442 with original_warnings.catch_warnings(record=True,
443 module=self.module) as w:
444 self.module.resetwarnings()
445 registry = {}
446 self.module.warn_explicit(message, UserWarning, "<test>", 42,
447 registry=registry)
448 self.assertEqual(w[-1].message, message)
449 self.assertEqual(len(w), 1)
450 self.assertEqual(len(registry), 1)
451 del w[:]
452 # Test removal.
453 del self.module.defaultaction
454 __warningregistry__ = {}
455 registry = {}
456 self.module.warn_explicit(message, UserWarning, "<test>", 43,
457 registry=registry)
458 self.assertEqual(w[-1].message, message)
459 self.assertEqual(len(w), 1)
460 self.assertEqual(len(registry), 1)
461 del w[:]
462 # Test setting.
463 self.module.defaultaction = "ignore"
464 __warningregistry__ = {}
465 registry = {}
466 self.module.warn_explicit(message, UserWarning, "<test>", 44,
467 registry=registry)
468 self.assertEqual(len(w), 0)
469 finally:
470 self.module.defaultaction = original
471
Brett Cannone9746892008-04-12 23:44:07 +0000472 def test_showwarning_missing(self):
473 # Test that showwarning() missing is okay.
474 text = 'del showwarning test'
Brett Cannon672237d2008-09-09 00:49:16 +0000475 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000476 self.module.filterwarnings("always", category=UserWarning)
477 del self.module.showwarning
478 with test_support.captured_output('stderr') as stream:
479 self.module.warn(text)
480 result = stream.getvalue()
Ezio Melottiaa980582010-01-23 23:04:36 +0000481 self.assertIn(text, result)
Brett Cannone9746892008-04-12 23:44:07 +0000482
Benjamin Petersond2950322008-05-06 22:18:11 +0000483 def test_showwarning_not_callable(self):
Brett Cannonce3d2212009-04-01 20:25:48 +0000484 with original_warnings.catch_warnings(module=self.module):
485 self.module.filterwarnings("always", category=UserWarning)
486 old_showwarning = self.module.showwarning
487 self.module.showwarning = 23
488 try:
489 self.assertRaises(TypeError, self.module.warn, "Warning!")
490 finally:
491 self.module.showwarning = old_showwarning
Benjamin Petersond2950322008-05-06 22:18:11 +0000492
Brett Cannone9746892008-04-12 23:44:07 +0000493 def test_show_warning_output(self):
494 # With showarning() missing, make sure that output is okay.
495 text = 'test show_warning'
Brett Cannon672237d2008-09-09 00:49:16 +0000496 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000497 self.module.filterwarnings("always", category=UserWarning)
498 del self.module.showwarning
499 with test_support.captured_output('stderr') as stream:
500 warning_tests.inner(text)
501 result = stream.getvalue()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000502 self.assertEqual(result.count('\n'), 2,
Brett Cannone9746892008-04-12 23:44:07 +0000503 "Too many newlines in %r" % result)
504 first_line, second_line = result.split('\n', 1)
505 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Brett Cannonc4774272008-04-13 17:41:31 +0000506 first_line_parts = first_line.rsplit(':', 3)
Brett Cannon25bb8182008-04-13 17:09:43 +0000507 path, line, warning_class, message = first_line_parts
Brett Cannone9746892008-04-12 23:44:07 +0000508 line = int(line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000509 self.assertEqual(expected_file, path)
510 self.assertEqual(warning_class, ' ' + UserWarning.__name__)
511 self.assertEqual(message, ' ' + text)
Brett Cannone9746892008-04-12 23:44:07 +0000512 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
513 assert expected_line
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000514 self.assertEqual(second_line, expected_line)
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000515
Brett Cannon53ab5b72006-06-22 16:49:14 +0000516
Brett Cannon905c31c2007-12-20 10:09:52 +0000517class WarningsDisplayTests(unittest.TestCase):
518
Brett Cannone9746892008-04-12 23:44:07 +0000519 """Test the displaying of warnings and the ability to overload functions
520 related to displaying warnings."""
521
Brett Cannon905c31c2007-12-20 10:09:52 +0000522 def test_formatwarning(self):
523 message = "msg"
524 category = Warning
525 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
526 line_num = 3
527 file_line = linecache.getline(file_name, line_num).strip()
Brett Cannone9746892008-04-12 23:44:07 +0000528 format = "%s:%s: %s: %s\n %s\n"
529 expect = format % (file_name, line_num, category.__name__, message,
530 file_line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000531 self.assertEqual(expect, self.module.formatwarning(message,
Brett Cannone9746892008-04-12 23:44:07 +0000532 category, file_name, line_num))
533 # Test the 'line' argument.
534 file_line += " for the win!"
535 expect = format % (file_name, line_num, category.__name__, message,
536 file_line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000537 self.assertEqual(expect, self.module.formatwarning(message,
Brett Cannone9746892008-04-12 23:44:07 +0000538 category, file_name, line_num, file_line))
Brett Cannon905c31c2007-12-20 10:09:52 +0000539
540 def test_showwarning(self):
541 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
542 line_num = 3
543 expected_file_line = linecache.getline(file_name, line_num).strip()
544 message = 'msg'
545 category = Warning
546 file_object = StringIO.StringIO()
Brett Cannone9746892008-04-12 23:44:07 +0000547 expect = self.module.formatwarning(message, category, file_name,
548 line_num)
549 self.module.showwarning(message, category, file_name, line_num,
Brett Cannon905c31c2007-12-20 10:09:52 +0000550 file_object)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000551 self.assertEqual(file_object.getvalue(), expect)
Brett Cannone9746892008-04-12 23:44:07 +0000552 # Test 'line' argument.
553 expected_file_line += "for the win!"
554 expect = self.module.formatwarning(message, category, file_name,
555 line_num, expected_file_line)
556 file_object = StringIO.StringIO()
557 self.module.showwarning(message, category, file_name, line_num,
558 file_object, expected_file_line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000559 self.assertEqual(expect, file_object.getvalue())
Brett Cannone9746892008-04-12 23:44:07 +0000560
Brett Cannon667bb4f2008-04-13 02:42:36 +0000561class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
Brett Cannone9746892008-04-12 23:44:07 +0000562 module = c_warnings
563
Brett Cannon667bb4f2008-04-13 02:42:36 +0000564class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
Brett Cannone9746892008-04-12 23:44:07 +0000565 module = py_warnings
Brett Cannon905c31c2007-12-20 10:09:52 +0000566
567
Brett Cannon1eaf0742008-09-02 01:25:16 +0000568class CatchWarningTests(BaseTest):
Nick Coghlan38469e22008-07-13 12:23:47 +0000569
Brett Cannon1eaf0742008-09-02 01:25:16 +0000570 """Test catch_warnings()."""
571
572 def test_catch_warnings_restore(self):
Nick Coghlan38469e22008-07-13 12:23:47 +0000573 wmod = self.module
574 orig_filters = wmod.filters
575 orig_showwarning = wmod.showwarning
Nick Coghland2e09382008-09-11 12:11:06 +0000576 # Ensure both showwarning and filters are restored when recording
577 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlan38469e22008-07-13 12:23:47 +0000578 wmod.filters = wmod.showwarning = object()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000579 self.assertTrue(wmod.filters is orig_filters)
580 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghland2e09382008-09-11 12:11:06 +0000581 # Same test, but with recording disabled
Brett Cannon1eaf0742008-09-02 01:25:16 +0000582 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlan38469e22008-07-13 12:23:47 +0000583 wmod.filters = wmod.showwarning = object()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000584 self.assertTrue(wmod.filters is orig_filters)
585 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlan38469e22008-07-13 12:23:47 +0000586
Brett Cannon1eaf0742008-09-02 01:25:16 +0000587 def test_catch_warnings_recording(self):
Nick Coghlan38469e22008-07-13 12:23:47 +0000588 wmod = self.module
Nick Coghland2e09382008-09-11 12:11:06 +0000589 # Ensure warnings are recorded when requested
Brett Cannon1eaf0742008-09-02 01:25:16 +0000590 with wmod.catch_warnings(module=wmod, record=True) as w:
591 self.assertEqual(w, [])
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000592 self.assertTrue(type(w) is list)
Nick Coghlan38469e22008-07-13 12:23:47 +0000593 wmod.simplefilter("always")
594 wmod.warn("foo")
Brett Cannon672237d2008-09-09 00:49:16 +0000595 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlan38469e22008-07-13 12:23:47 +0000596 wmod.warn("bar")
Brett Cannon672237d2008-09-09 00:49:16 +0000597 self.assertEqual(str(w[-1].message), "bar")
Brett Cannon1eaf0742008-09-02 01:25:16 +0000598 self.assertEqual(str(w[0].message), "foo")
599 self.assertEqual(str(w[1].message), "bar")
Brett Cannon672237d2008-09-09 00:49:16 +0000600 del w[:]
Brett Cannon1eaf0742008-09-02 01:25:16 +0000601 self.assertEqual(w, [])
Nick Coghland2e09382008-09-11 12:11:06 +0000602 # Ensure warnings are not recorded when not requested
Nick Coghlan38469e22008-07-13 12:23:47 +0000603 orig_showwarning = wmod.showwarning
Brett Cannon1eaf0742008-09-02 01:25:16 +0000604 with wmod.catch_warnings(module=wmod, record=False) as w:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000605 self.assertTrue(w is None)
606 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlan38469e22008-07-13 12:23:47 +0000607
Nick Coghland2e09382008-09-11 12:11:06 +0000608 def test_catch_warnings_reentry_guard(self):
609 wmod = self.module
610 # Ensure catch_warnings is protected against incorrect usage
611 x = wmod.catch_warnings(module=wmod, record=True)
612 self.assertRaises(RuntimeError, x.__exit__)
613 with x:
614 self.assertRaises(RuntimeError, x.__enter__)
615 # Same test, but with recording disabled
616 x = wmod.catch_warnings(module=wmod, record=False)
617 self.assertRaises(RuntimeError, x.__exit__)
618 with x:
619 self.assertRaises(RuntimeError, x.__enter__)
620
621 def test_catch_warnings_defaults(self):
622 wmod = self.module
623 orig_filters = wmod.filters
624 orig_showwarning = wmod.showwarning
625 # Ensure default behaviour is not to record warnings
626 with wmod.catch_warnings(module=wmod) as w:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000627 self.assertTrue(w is None)
628 self.assertTrue(wmod.showwarning is orig_showwarning)
629 self.assertTrue(wmod.filters is not orig_filters)
630 self.assertTrue(wmod.filters is orig_filters)
Nick Coghland2e09382008-09-11 12:11:06 +0000631 if wmod is sys.modules['warnings']:
632 # Ensure the default module is this one
633 with wmod.catch_warnings() as w:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000634 self.assertTrue(w is None)
635 self.assertTrue(wmod.showwarning is orig_showwarning)
636 self.assertTrue(wmod.filters is not orig_filters)
637 self.assertTrue(wmod.filters is orig_filters)
Nick Coghland2e09382008-09-11 12:11:06 +0000638
639 def test_check_warnings(self):
640 # Explicit tests for the test_support convenience wrapper
641 wmod = self.module
Florent Xicluna73588542010-03-18 19:51:47 +0000642 if wmod is not sys.modules['warnings']:
643 return
644 with test_support.check_warnings(quiet=False) as w:
645 self.assertEqual(w.warnings, [])
646 wmod.simplefilter("always")
647 wmod.warn("foo")
648 self.assertEqual(str(w.message), "foo")
649 wmod.warn("bar")
650 self.assertEqual(str(w.message), "bar")
651 self.assertEqual(str(w.warnings[0].message), "foo")
652 self.assertEqual(str(w.warnings[1].message), "bar")
653 w.reset()
654 self.assertEqual(w.warnings, [])
Nick Coghland2e09382008-09-11 12:11:06 +0000655
Florent Xicluna73588542010-03-18 19:51:47 +0000656 with test_support.check_warnings():
657 # defaults to quiet=True without argument
658 pass
659 with test_support.check_warnings(('foo', UserWarning)):
660 wmod.warn("foo")
661
662 with self.assertRaises(AssertionError):
663 with test_support.check_warnings(('', RuntimeWarning)):
664 # defaults to quiet=False with argument
665 pass
666 with self.assertRaises(AssertionError):
667 with test_support.check_warnings(('foo', RuntimeWarning)):
668 wmod.warn("foo")
Nick Coghland2e09382008-09-11 12:11:06 +0000669
670
Brett Cannon1eaf0742008-09-02 01:25:16 +0000671class CCatchWarningTests(CatchWarningTests):
Nick Coghlan38469e22008-07-13 12:23:47 +0000672 module = c_warnings
673
Brett Cannon1eaf0742008-09-02 01:25:16 +0000674class PyCatchWarningTests(CatchWarningTests):
Nick Coghlan38469e22008-07-13 12:23:47 +0000675 module = py_warnings
676
677
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000678class EnvironmentVariableTests(BaseTest):
679
680 def test_single_warning(self):
681 newenv = os.environ.copy()
682 newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
683 p = subprocess.Popen([sys.executable,
684 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
685 stdout=subprocess.PIPE, env=newenv)
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000686 self.assertEqual(p.communicate()[0], "['ignore::DeprecationWarning']")
687 self.assertEqual(p.wait(), 0)
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000688
689 def test_comma_separated_warnings(self):
690 newenv = os.environ.copy()
691 newenv["PYTHONWARNINGS"] = ("ignore::DeprecationWarning,"
692 "ignore::UnicodeWarning")
693 p = subprocess.Popen([sys.executable,
694 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
695 stdout=subprocess.PIPE, env=newenv)
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000696 self.assertEqual(p.communicate()[0],
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000697 "['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000698 self.assertEqual(p.wait(), 0)
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000699
700 def test_envvar_and_command_line(self):
701 newenv = os.environ.copy()
702 newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
703 p = subprocess.Popen([sys.executable, "-W" "ignore::UnicodeWarning",
704 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
705 stdout=subprocess.PIPE, env=newenv)
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000706 self.assertEqual(p.communicate()[0],
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000707 "['ignore::UnicodeWarning', 'ignore::DeprecationWarning']")
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000708 self.assertEqual(p.wait(), 0)
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000709
710class CEnvironmentVariableTests(EnvironmentVariableTests):
711 module = c_warnings
712
713class PyEnvironmentVariableTests(EnvironmentVariableTests):
714 module = py_warnings
715
716
Brett Cannone9746892008-04-12 23:44:07 +0000717def test_main():
Amaury Forgeot d'Arc607bff12008-04-18 23:31:33 +0000718 py_warnings.onceregistry.clear()
719 c_warnings.onceregistry.clear()
Brett Cannon1eaf0742008-09-02 01:25:16 +0000720 test_support.run_unittest(CFilterTests, PyFilterTests,
721 CWarnTests, PyWarnTests,
Brett Cannone9746892008-04-12 23:44:07 +0000722 CWCmdLineTests, PyWCmdLineTests,
723 _WarningsTests,
724 CWarningsDisplayTests, PyWarningsDisplayTests,
Brett Cannon1eaf0742008-09-02 01:25:16 +0000725 CCatchWarningTests, PyCatchWarningTests,
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000726 CEnvironmentVariableTests,
727 PyEnvironmentVariableTests
Brett Cannone9746892008-04-12 23:44:07 +0000728 )
729
730
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000731if __name__ == "__main__":
Brett Cannone9746892008-04-12 23:44:07 +0000732 test_main()