blob: a0a65b41f1bd7f36851e240d549726335d3a28ce [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
7from test import test_support
Jeremy Hylton85014662003-07-11 15:37:59 +00008
Walter Dörwalde1a9b422007-04-03 16:53:43 +00009import warning_tests
10
Brett Cannon667bb4f2008-04-13 02:42:36 +000011import warnings as original_warnings
12
Nick Coghlan5533ff62009-04-22 15:26:04 +000013py_warnings = test_support.import_fresh_module('warnings', blocked=['_warnings'])
14c_warnings = test_support.import_fresh_module('warnings', fresh=['_warnings'])
Brett Cannon667bb4f2008-04-13 02:42:36 +000015
Brett Cannone9746892008-04-12 23:44:07 +000016@contextmanager
17def warnings_state(module):
18 """Use a specific warnings implementation in warning_tests."""
19 global __warningregistry__
20 for to_clear in (sys, warning_tests):
21 try:
22 to_clear.__warningregistry__.clear()
23 except AttributeError:
24 pass
25 try:
26 __warningregistry__.clear()
27 except NameError:
28 pass
29 original_warnings = warning_tests.warnings
Florent Xiclunafd37dd42010-03-25 20:39:10 +000030 original_filters = module.filters
Brett Cannone9746892008-04-12 23:44:07 +000031 try:
Florent Xiclunafd37dd42010-03-25 20:39:10 +000032 module.filters = original_filters[:]
33 module.simplefilter("once")
Brett Cannone9746892008-04-12 23:44:07 +000034 warning_tests.warnings = module
35 yield
36 finally:
37 warning_tests.warnings = original_warnings
Florent Xiclunafd37dd42010-03-25 20:39:10 +000038 module.filters = original_filters
Brett Cannone9746892008-04-12 23:44:07 +000039
40
Brett Cannon667bb4f2008-04-13 02:42:36 +000041class BaseTest(unittest.TestCase):
Brett Cannone9746892008-04-12 23:44:07 +000042
Brett Cannon667bb4f2008-04-13 02:42:36 +000043 """Basic bookkeeping required for testing."""
Brett Cannone9746892008-04-12 23:44:07 +000044
45 def setUp(self):
Brett Cannon667bb4f2008-04-13 02:42:36 +000046 # The __warningregistry__ needs to be in a pristine state for tests
47 # to work properly.
48 if '__warningregistry__' in globals():
49 del globals()['__warningregistry__']
50 if hasattr(warning_tests, '__warningregistry__'):
51 del warning_tests.__warningregistry__
52 if hasattr(sys, '__warningregistry__'):
53 del sys.__warningregistry__
54 # The 'warnings' module must be explicitly set so that the proper
55 # interaction between _warnings and 'warnings' can be controlled.
56 sys.modules['warnings'] = self.module
57 super(BaseTest, self).setUp()
58
59 def tearDown(self):
60 sys.modules['warnings'] = original_warnings
61 super(BaseTest, self).tearDown()
62
63
64class FilterTests(object):
65
66 """Testing the filtering functionality."""
Brett Cannone9746892008-04-12 23:44:07 +000067
68 def test_error(self):
Brett Cannon672237d2008-09-09 00:49:16 +000069 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +000070 self.module.resetwarnings()
71 self.module.filterwarnings("error", category=UserWarning)
72 self.assertRaises(UserWarning, self.module.warn,
73 "FilterTests.test_error")
74
75 def test_ignore(self):
Brett Cannon672237d2008-09-09 00:49:16 +000076 with original_warnings.catch_warnings(record=True,
77 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +000078 self.module.resetwarnings()
79 self.module.filterwarnings("ignore", category=UserWarning)
80 self.module.warn("FilterTests.test_ignore", UserWarning)
Brett Cannon1eaf0742008-09-02 01:25:16 +000081 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +000082
83 def test_always(self):
Brett Cannon672237d2008-09-09 00:49:16 +000084 with original_warnings.catch_warnings(record=True,
85 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +000086 self.module.resetwarnings()
87 self.module.filterwarnings("always", category=UserWarning)
88 message = "FilterTests.test_always"
89 self.module.warn(message, UserWarning)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000090 self.assertTrue(message, w[-1].message)
Brett Cannone9746892008-04-12 23:44:07 +000091 self.module.warn(message, UserWarning)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000092 self.assertTrue(w[-1].message, message)
Brett Cannone9746892008-04-12 23:44:07 +000093
94 def test_default(self):
Brett Cannon672237d2008-09-09 00:49:16 +000095 with original_warnings.catch_warnings(record=True,
96 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +000097 self.module.resetwarnings()
98 self.module.filterwarnings("default", category=UserWarning)
99 message = UserWarning("FilterTests.test_default")
100 for x in xrange(2):
101 self.module.warn(message, UserWarning)
102 if x == 0:
Brett Cannon672237d2008-09-09 00:49:16 +0000103 self.assertEquals(w[-1].message, message)
104 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000105 elif x == 1:
Brett Cannon672237d2008-09-09 00:49:16 +0000106 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000107 else:
108 raise ValueError("loop variant unhandled")
109
110 def test_module(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000111 with original_warnings.catch_warnings(record=True,
112 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000113 self.module.resetwarnings()
114 self.module.filterwarnings("module", category=UserWarning)
115 message = UserWarning("FilterTests.test_module")
116 self.module.warn(message, UserWarning)
Brett Cannon672237d2008-09-09 00:49:16 +0000117 self.assertEquals(w[-1].message, message)
118 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000119 self.module.warn(message, UserWarning)
Brett Cannon672237d2008-09-09 00:49:16 +0000120 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000121
122 def test_once(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000123 with original_warnings.catch_warnings(record=True,
124 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000125 self.module.resetwarnings()
126 self.module.filterwarnings("once", category=UserWarning)
127 message = UserWarning("FilterTests.test_once")
128 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
129 42)
Brett Cannon672237d2008-09-09 00:49:16 +0000130 self.assertEquals(w[-1].message, message)
131 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000132 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
133 13)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000134 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000135 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
136 42)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000137 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000138
139 def test_inheritance(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000140 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000141 self.module.resetwarnings()
142 self.module.filterwarnings("error", category=Warning)
143 self.assertRaises(UserWarning, self.module.warn,
144 "FilterTests.test_inheritance", UserWarning)
145
146 def test_ordering(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000147 with original_warnings.catch_warnings(record=True,
148 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000149 self.module.resetwarnings()
150 self.module.filterwarnings("ignore", category=UserWarning)
151 self.module.filterwarnings("error", category=UserWarning,
152 append=True)
Brett Cannon672237d2008-09-09 00:49:16 +0000153 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000154 try:
155 self.module.warn("FilterTests.test_ordering", UserWarning)
156 except UserWarning:
157 self.fail("order handling for actions failed")
Brett Cannon1eaf0742008-09-02 01:25:16 +0000158 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000159
160 def test_filterwarnings(self):
161 # Test filterwarnings().
162 # Implicitly also tests resetwarnings().
Brett Cannon672237d2008-09-09 00:49:16 +0000163 with original_warnings.catch_warnings(record=True,
164 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000165 self.module.filterwarnings("error", "", Warning, "", 0)
166 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
167
168 self.module.resetwarnings()
169 text = 'handle normally'
170 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000171 self.assertEqual(str(w[-1].message), text)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000172 self.assertTrue(w[-1].category is UserWarning)
Brett Cannone9746892008-04-12 23:44:07 +0000173
174 self.module.filterwarnings("ignore", "", Warning, "", 0)
175 text = 'filtered out'
176 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000177 self.assertNotEqual(str(w[-1].message), text)
Brett Cannone9746892008-04-12 23:44:07 +0000178
179 self.module.resetwarnings()
180 self.module.filterwarnings("error", "hex*", Warning, "", 0)
181 self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
182 text = 'nonmatching text'
183 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000184 self.assertEqual(str(w[-1].message), text)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000185 self.assertTrue(w[-1].category is UserWarning)
Brett Cannone9746892008-04-12 23:44:07 +0000186
Brett Cannon667bb4f2008-04-13 02:42:36 +0000187class CFilterTests(BaseTest, FilterTests):
Brett Cannone9746892008-04-12 23:44:07 +0000188 module = c_warnings
189
Brett Cannon667bb4f2008-04-13 02:42:36 +0000190class PyFilterTests(BaseTest, FilterTests):
Brett Cannone9746892008-04-12 23:44:07 +0000191 module = py_warnings
192
193
194class WarnTests(unittest.TestCase):
195
196 """Test warnings.warn() and warnings.warn_explicit()."""
197
198 def test_message(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000199 with original_warnings.catch_warnings(record=True,
200 module=self.module) as w:
Florent Xiclunafd37dd42010-03-25 20:39:10 +0000201 self.module.simplefilter("once")
Walter Dörwalde6dae6c2007-04-03 18:33:29 +0000202 for i in range(4):
Brett Cannone9746892008-04-12 23:44:07 +0000203 text = 'multi %d' %i # Different text on each call.
204 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000205 self.assertEqual(str(w[-1].message), text)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000206 self.assertTrue(w[-1].category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000207
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000208 def test_filename(self):
Brett Cannone9746892008-04-12 23:44:07 +0000209 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000210 with original_warnings.catch_warnings(record=True,
211 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000212 warning_tests.inner("spam1")
Brett Cannon672237d2008-09-09 00:49:16 +0000213 self.assertEqual(os.path.basename(w[-1].filename),
214 "warning_tests.py")
Brett Cannone9746892008-04-12 23:44:07 +0000215 warning_tests.outer("spam2")
Brett Cannon672237d2008-09-09 00:49:16 +0000216 self.assertEqual(os.path.basename(w[-1].filename),
217 "warning_tests.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000218
219 def test_stacklevel(self):
220 # Test stacklevel argument
221 # make sure all messages are different, so the warning won't be skipped
Brett Cannone9746892008-04-12 23:44:07 +0000222 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000223 with original_warnings.catch_warnings(record=True,
224 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000225 warning_tests.inner("spam3", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000226 self.assertEqual(os.path.basename(w[-1].filename),
227 "warning_tests.py")
Brett Cannone9746892008-04-12 23:44:07 +0000228 warning_tests.outer("spam4", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000229 self.assertEqual(os.path.basename(w[-1].filename),
230 "warning_tests.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000231
Brett Cannone9746892008-04-12 23:44:07 +0000232 warning_tests.inner("spam5", stacklevel=2)
Brett Cannon672237d2008-09-09 00:49:16 +0000233 self.assertEqual(os.path.basename(w[-1].filename),
234 "test_warnings.py")
Brett Cannone9746892008-04-12 23:44:07 +0000235 warning_tests.outer("spam6", stacklevel=2)
Brett Cannon672237d2008-09-09 00:49:16 +0000236 self.assertEqual(os.path.basename(w[-1].filename),
237 "warning_tests.py")
Brett Cannone3dcb012008-05-06 04:37:31 +0000238 warning_tests.outer("spam6.5", stacklevel=3)
Brett Cannon672237d2008-09-09 00:49:16 +0000239 self.assertEqual(os.path.basename(w[-1].filename),
240 "test_warnings.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000241
Brett Cannone9746892008-04-12 23:44:07 +0000242 warning_tests.inner("spam7", stacklevel=9999)
Brett Cannon672237d2008-09-09 00:49:16 +0000243 self.assertEqual(os.path.basename(w[-1].filename),
244 "sys")
Brett Cannone9746892008-04-12 23:44:07 +0000245
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000246 def test_missing_filename_not_main(self):
247 # If __file__ is not specified and __main__ is not the module name,
248 # then __file__ should be set to the module name.
249 filename = warning_tests.__file__
250 try:
251 del warning_tests.__file__
252 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000253 with original_warnings.catch_warnings(record=True,
254 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000255 warning_tests.inner("spam8", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000256 self.assertEqual(w[-1].filename, warning_tests.__name__)
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000257 finally:
258 warning_tests.__file__ = filename
259
260 def test_missing_filename_main_with_argv(self):
261 # If __file__ is not specified and the caller is __main__ and sys.argv
262 # exists, then use sys.argv[0] as the file.
263 if not hasattr(sys, 'argv'):
264 return
265 filename = warning_tests.__file__
266 module_name = warning_tests.__name__
267 try:
268 del warning_tests.__file__
269 warning_tests.__name__ = '__main__'
270 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000271 with original_warnings.catch_warnings(record=True,
272 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000273 warning_tests.inner('spam9', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000274 self.assertEqual(w[-1].filename, sys.argv[0])
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000275 finally:
276 warning_tests.__file__ = filename
277 warning_tests.__name__ = module_name
278
279 def test_missing_filename_main_without_argv(self):
280 # If __file__ is not specified, the caller is __main__, and sys.argv
281 # is not set, then '__main__' is the file name.
282 filename = warning_tests.__file__
283 module_name = warning_tests.__name__
284 argv = sys.argv
285 try:
286 del warning_tests.__file__
287 warning_tests.__name__ = '__main__'
288 del sys.argv
289 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000290 with original_warnings.catch_warnings(record=True,
291 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000292 warning_tests.inner('spam10', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000293 self.assertEqual(w[-1].filename, '__main__')
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000294 finally:
295 warning_tests.__file__ = filename
296 warning_tests.__name__ = module_name
297 sys.argv = argv
298
299 def test_missing_filename_main_with_argv_empty_string(self):
300 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
301 # is the empty string, then '__main__ is the file name.
302 # Tests issue 2743.
303 file_name = warning_tests.__file__
304 module_name = warning_tests.__name__
305 argv = sys.argv
306 try:
307 del warning_tests.__file__
308 warning_tests.__name__ = '__main__'
309 sys.argv = ['']
310 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000311 with original_warnings.catch_warnings(record=True,
312 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000313 warning_tests.inner('spam11', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000314 self.assertEqual(w[-1].filename, '__main__')
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000315 finally:
316 warning_tests.__file__ = file_name
317 warning_tests.__name__ = module_name
318 sys.argv = argv
319
Brett Cannondea1b562008-06-27 00:31:13 +0000320 def test_warn_explicit_type_errors(self):
321 # warn_explicit() shoud error out gracefully if it is given objects
322 # of the wrong types.
323 # lineno is expected to be an integer.
324 self.assertRaises(TypeError, self.module.warn_explicit,
325 None, UserWarning, None, None)
326 # Either 'message' needs to be an instance of Warning or 'category'
327 # needs to be a subclass.
328 self.assertRaises(TypeError, self.module.warn_explicit,
329 None, None, None, 1)
330 # 'registry' must be a dict or None.
331 self.assertRaises((TypeError, AttributeError),
332 self.module.warn_explicit,
333 None, Warning, None, 1, registry=42)
334
Hirokazu Yamamotoe78e5d22009-07-17 06:20:46 +0000335 def test_bad_str(self):
336 # issue 6415
337 # Warnings instance with a bad format string for __str__ should not
338 # trigger a bus error.
339 class BadStrWarning(Warning):
340 """Warning with a bad format string for __str__."""
341 def __str__(self):
342 return ("A bad formatted string %(err)" %
343 {"err" : "there is no %(err)s"})
344
345 with self.assertRaises(ValueError):
346 self.module.warn(BadStrWarning())
347
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000348
Brett Cannon667bb4f2008-04-13 02:42:36 +0000349class CWarnTests(BaseTest, WarnTests):
Brett Cannone9746892008-04-12 23:44:07 +0000350 module = c_warnings
351
Nick Coghlancd2e7042009-04-11 13:31:31 +0000352 # As an early adopter, we sanity check the
353 # test_support.import_fresh_module utility function
354 def test_accelerated(self):
355 self.assertFalse(original_warnings is self.module)
356 self.assertFalse(hasattr(self.module.warn, 'func_code'))
357
Brett Cannon667bb4f2008-04-13 02:42:36 +0000358class PyWarnTests(BaseTest, WarnTests):
Brett Cannone9746892008-04-12 23:44:07 +0000359 module = py_warnings
360
Nick Coghlancd2e7042009-04-11 13:31:31 +0000361 # As an early adopter, we sanity check the
362 # test_support.import_fresh_module utility function
363 def test_pure_python(self):
364 self.assertFalse(original_warnings is self.module)
365 self.assertTrue(hasattr(self.module.warn, 'func_code'))
366
Brett Cannone9746892008-04-12 23:44:07 +0000367
368class WCmdLineTests(unittest.TestCase):
369
370 def test_improper_input(self):
371 # Uses the private _setoption() function to test the parsing
372 # of command-line warning arguments
Brett Cannon672237d2008-09-09 00:49:16 +0000373 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000374 self.assertRaises(self.module._OptionError,
375 self.module._setoption, '1:2:3:4:5:6')
376 self.assertRaises(self.module._OptionError,
377 self.module._setoption, 'bogus::Warning')
378 self.assertRaises(self.module._OptionError,
379 self.module._setoption, 'ignore:2::4:-5')
380 self.module._setoption('error::Warning::0')
381 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
382
Brett Cannon667bb4f2008-04-13 02:42:36 +0000383class CWCmdLineTests(BaseTest, WCmdLineTests):
Brett Cannone9746892008-04-12 23:44:07 +0000384 module = c_warnings
385
Brett Cannon667bb4f2008-04-13 02:42:36 +0000386class PyWCmdLineTests(BaseTest, WCmdLineTests):
Brett Cannone9746892008-04-12 23:44:07 +0000387 module = py_warnings
388
389
Brett Cannon667bb4f2008-04-13 02:42:36 +0000390class _WarningsTests(BaseTest):
Brett Cannone9746892008-04-12 23:44:07 +0000391
392 """Tests specific to the _warnings module."""
393
394 module = c_warnings
395
396 def test_filter(self):
397 # Everything should function even if 'filters' is not in warnings.
Brett Cannon672237d2008-09-09 00:49:16 +0000398 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000399 self.module.filterwarnings("error", "", Warning, "", 0)
400 self.assertRaises(UserWarning, self.module.warn,
401 'convert to error')
402 del self.module.filters
403 self.assertRaises(UserWarning, self.module.warn,
404 'convert to error')
405
406 def test_onceregistry(self):
407 # Replacing or removing the onceregistry should be okay.
408 global __warningregistry__
409 message = UserWarning('onceregistry test')
410 try:
411 original_registry = self.module.onceregistry
412 __warningregistry__ = {}
Brett Cannon672237d2008-09-09 00:49:16 +0000413 with original_warnings.catch_warnings(record=True,
414 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000415 self.module.resetwarnings()
416 self.module.filterwarnings("once", category=UserWarning)
417 self.module.warn_explicit(message, UserWarning, "file", 42)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000418 self.assertEqual(w[-1].message, message)
Brett Cannon672237d2008-09-09 00:49:16 +0000419 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000420 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000421 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000422 # Test the resetting of onceregistry.
423 self.module.onceregistry = {}
424 __warningregistry__ = {}
425 self.module.warn('onceregistry test')
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000426 self.assertEqual(w[-1].message.args, message.args)
Brett Cannone9746892008-04-12 23:44:07 +0000427 # Removal of onceregistry is okay.
Brett Cannon672237d2008-09-09 00:49:16 +0000428 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000429 del self.module.onceregistry
430 __warningregistry__ = {}
431 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000432 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000433 finally:
434 self.module.onceregistry = original_registry
435
Brett Cannon15ba4da2009-04-01 18:03:59 +0000436 def test_default_action(self):
437 # Replacing or removing defaultaction should be okay.
438 message = UserWarning("defaultaction test")
439 original = self.module.defaultaction
440 try:
441 with original_warnings.catch_warnings(record=True,
442 module=self.module) as w:
443 self.module.resetwarnings()
444 registry = {}
445 self.module.warn_explicit(message, UserWarning, "<test>", 42,
446 registry=registry)
447 self.assertEqual(w[-1].message, message)
448 self.assertEqual(len(w), 1)
449 self.assertEqual(len(registry), 1)
450 del w[:]
451 # Test removal.
452 del self.module.defaultaction
453 __warningregistry__ = {}
454 registry = {}
455 self.module.warn_explicit(message, UserWarning, "<test>", 43,
456 registry=registry)
457 self.assertEqual(w[-1].message, message)
458 self.assertEqual(len(w), 1)
459 self.assertEqual(len(registry), 1)
460 del w[:]
461 # Test setting.
462 self.module.defaultaction = "ignore"
463 __warningregistry__ = {}
464 registry = {}
465 self.module.warn_explicit(message, UserWarning, "<test>", 44,
466 registry=registry)
467 self.assertEqual(len(w), 0)
468 finally:
469 self.module.defaultaction = original
470
Brett Cannone9746892008-04-12 23:44:07 +0000471 def test_showwarning_missing(self):
472 # Test that showwarning() missing is okay.
473 text = 'del showwarning test'
Brett Cannon672237d2008-09-09 00:49:16 +0000474 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000475 self.module.filterwarnings("always", category=UserWarning)
476 del self.module.showwarning
477 with test_support.captured_output('stderr') as stream:
478 self.module.warn(text)
479 result = stream.getvalue()
Ezio Melottiaa980582010-01-23 23:04:36 +0000480 self.assertIn(text, result)
Brett Cannone9746892008-04-12 23:44:07 +0000481
Benjamin Petersond2950322008-05-06 22:18:11 +0000482 def test_showwarning_not_callable(self):
Brett Cannonce3d2212009-04-01 20:25:48 +0000483 with original_warnings.catch_warnings(module=self.module):
484 self.module.filterwarnings("always", category=UserWarning)
485 old_showwarning = self.module.showwarning
486 self.module.showwarning = 23
487 try:
488 self.assertRaises(TypeError, self.module.warn, "Warning!")
489 finally:
490 self.module.showwarning = old_showwarning
Benjamin Petersond2950322008-05-06 22:18:11 +0000491
Brett Cannone9746892008-04-12 23:44:07 +0000492 def test_show_warning_output(self):
493 # With showarning() missing, make sure that output is okay.
494 text = 'test show_warning'
Brett Cannon672237d2008-09-09 00:49:16 +0000495 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000496 self.module.filterwarnings("always", category=UserWarning)
497 del self.module.showwarning
498 with test_support.captured_output('stderr') as stream:
499 warning_tests.inner(text)
500 result = stream.getvalue()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000501 self.assertEqual(result.count('\n'), 2,
Brett Cannone9746892008-04-12 23:44:07 +0000502 "Too many newlines in %r" % result)
503 first_line, second_line = result.split('\n', 1)
504 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Brett Cannonc4774272008-04-13 17:41:31 +0000505 first_line_parts = first_line.rsplit(':', 3)
Brett Cannon25bb8182008-04-13 17:09:43 +0000506 path, line, warning_class, message = first_line_parts
Brett Cannone9746892008-04-12 23:44:07 +0000507 line = int(line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000508 self.assertEqual(expected_file, path)
509 self.assertEqual(warning_class, ' ' + UserWarning.__name__)
510 self.assertEqual(message, ' ' + text)
Brett Cannone9746892008-04-12 23:44:07 +0000511 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
512 assert expected_line
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000513 self.assertEqual(second_line, expected_line)
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000514
Brett Cannon53ab5b72006-06-22 16:49:14 +0000515
Brett Cannon905c31c2007-12-20 10:09:52 +0000516class WarningsDisplayTests(unittest.TestCase):
517
Brett Cannone9746892008-04-12 23:44:07 +0000518 """Test the displaying of warnings and the ability to overload functions
519 related to displaying warnings."""
520
Brett Cannon905c31c2007-12-20 10:09:52 +0000521 def test_formatwarning(self):
522 message = "msg"
523 category = Warning
524 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
525 line_num = 3
526 file_line = linecache.getline(file_name, line_num).strip()
Brett Cannone9746892008-04-12 23:44:07 +0000527 format = "%s:%s: %s: %s\n %s\n"
528 expect = format % (file_name, line_num, category.__name__, message,
529 file_line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000530 self.assertEqual(expect, self.module.formatwarning(message,
Brett Cannone9746892008-04-12 23:44:07 +0000531 category, file_name, line_num))
532 # Test the 'line' argument.
533 file_line += " for the win!"
534 expect = format % (file_name, line_num, category.__name__, message,
535 file_line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000536 self.assertEqual(expect, self.module.formatwarning(message,
Brett Cannone9746892008-04-12 23:44:07 +0000537 category, file_name, line_num, file_line))
Brett Cannon905c31c2007-12-20 10:09:52 +0000538
539 def test_showwarning(self):
540 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
541 line_num = 3
542 expected_file_line = linecache.getline(file_name, line_num).strip()
543 message = 'msg'
544 category = Warning
545 file_object = StringIO.StringIO()
Brett Cannone9746892008-04-12 23:44:07 +0000546 expect = self.module.formatwarning(message, category, file_name,
547 line_num)
548 self.module.showwarning(message, category, file_name, line_num,
Brett Cannon905c31c2007-12-20 10:09:52 +0000549 file_object)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000550 self.assertEqual(file_object.getvalue(), expect)
Brett Cannone9746892008-04-12 23:44:07 +0000551 # Test 'line' argument.
552 expected_file_line += "for the win!"
553 expect = self.module.formatwarning(message, category, file_name,
554 line_num, expected_file_line)
555 file_object = StringIO.StringIO()
556 self.module.showwarning(message, category, file_name, line_num,
557 file_object, expected_file_line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000558 self.assertEqual(expect, file_object.getvalue())
Brett Cannone9746892008-04-12 23:44:07 +0000559
Brett Cannon667bb4f2008-04-13 02:42:36 +0000560class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
Brett Cannone9746892008-04-12 23:44:07 +0000561 module = c_warnings
562
Brett Cannon667bb4f2008-04-13 02:42:36 +0000563class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
Brett Cannone9746892008-04-12 23:44:07 +0000564 module = py_warnings
Brett Cannon905c31c2007-12-20 10:09:52 +0000565
566
Brett Cannon1eaf0742008-09-02 01:25:16 +0000567class CatchWarningTests(BaseTest):
Nick Coghlan38469e22008-07-13 12:23:47 +0000568
Brett Cannon1eaf0742008-09-02 01:25:16 +0000569 """Test catch_warnings()."""
570
571 def test_catch_warnings_restore(self):
Nick Coghlan38469e22008-07-13 12:23:47 +0000572 wmod = self.module
573 orig_filters = wmod.filters
574 orig_showwarning = wmod.showwarning
Nick Coghland2e09382008-09-11 12:11:06 +0000575 # Ensure both showwarning and filters are restored when recording
576 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlan38469e22008-07-13 12:23:47 +0000577 wmod.filters = wmod.showwarning = object()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000578 self.assertTrue(wmod.filters is orig_filters)
579 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghland2e09382008-09-11 12:11:06 +0000580 # Same test, but with recording disabled
Brett Cannon1eaf0742008-09-02 01:25:16 +0000581 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlan38469e22008-07-13 12:23:47 +0000582 wmod.filters = wmod.showwarning = object()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000583 self.assertTrue(wmod.filters is orig_filters)
584 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlan38469e22008-07-13 12:23:47 +0000585
Brett Cannon1eaf0742008-09-02 01:25:16 +0000586 def test_catch_warnings_recording(self):
Nick Coghlan38469e22008-07-13 12:23:47 +0000587 wmod = self.module
Nick Coghland2e09382008-09-11 12:11:06 +0000588 # Ensure warnings are recorded when requested
Brett Cannon1eaf0742008-09-02 01:25:16 +0000589 with wmod.catch_warnings(module=wmod, record=True) as w:
590 self.assertEqual(w, [])
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000591 self.assertTrue(type(w) is list)
Nick Coghlan38469e22008-07-13 12:23:47 +0000592 wmod.simplefilter("always")
593 wmod.warn("foo")
Brett Cannon672237d2008-09-09 00:49:16 +0000594 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlan38469e22008-07-13 12:23:47 +0000595 wmod.warn("bar")
Brett Cannon672237d2008-09-09 00:49:16 +0000596 self.assertEqual(str(w[-1].message), "bar")
Brett Cannon1eaf0742008-09-02 01:25:16 +0000597 self.assertEqual(str(w[0].message), "foo")
598 self.assertEqual(str(w[1].message), "bar")
Brett Cannon672237d2008-09-09 00:49:16 +0000599 del w[:]
Brett Cannon1eaf0742008-09-02 01:25:16 +0000600 self.assertEqual(w, [])
Nick Coghland2e09382008-09-11 12:11:06 +0000601 # Ensure warnings are not recorded when not requested
Nick Coghlan38469e22008-07-13 12:23:47 +0000602 orig_showwarning = wmod.showwarning
Brett Cannon1eaf0742008-09-02 01:25:16 +0000603 with wmod.catch_warnings(module=wmod, record=False) as w:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000604 self.assertTrue(w is None)
605 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlan38469e22008-07-13 12:23:47 +0000606
Nick Coghland2e09382008-09-11 12:11:06 +0000607 def test_catch_warnings_reentry_guard(self):
608 wmod = self.module
609 # Ensure catch_warnings is protected against incorrect usage
610 x = wmod.catch_warnings(module=wmod, record=True)
611 self.assertRaises(RuntimeError, x.__exit__)
612 with x:
613 self.assertRaises(RuntimeError, x.__enter__)
614 # Same test, but with recording disabled
615 x = wmod.catch_warnings(module=wmod, record=False)
616 self.assertRaises(RuntimeError, x.__exit__)
617 with x:
618 self.assertRaises(RuntimeError, x.__enter__)
619
620 def test_catch_warnings_defaults(self):
621 wmod = self.module
622 orig_filters = wmod.filters
623 orig_showwarning = wmod.showwarning
624 # Ensure default behaviour is not to record warnings
625 with wmod.catch_warnings(module=wmod) as w:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000626 self.assertTrue(w is None)
627 self.assertTrue(wmod.showwarning is orig_showwarning)
628 self.assertTrue(wmod.filters is not orig_filters)
629 self.assertTrue(wmod.filters is orig_filters)
Nick Coghland2e09382008-09-11 12:11:06 +0000630 if wmod is sys.modules['warnings']:
631 # Ensure the default module is this one
632 with wmod.catch_warnings() as w:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000633 self.assertTrue(w is None)
634 self.assertTrue(wmod.showwarning is orig_showwarning)
635 self.assertTrue(wmod.filters is not orig_filters)
636 self.assertTrue(wmod.filters is orig_filters)
Nick Coghland2e09382008-09-11 12:11:06 +0000637
638 def test_check_warnings(self):
639 # Explicit tests for the test_support convenience wrapper
640 wmod = self.module
Florent Xicluna73588542010-03-18 19:51:47 +0000641 if wmod is not sys.modules['warnings']:
642 return
643 with test_support.check_warnings(quiet=False) as w:
644 self.assertEqual(w.warnings, [])
645 wmod.simplefilter("always")
646 wmod.warn("foo")
647 self.assertEqual(str(w.message), "foo")
648 wmod.warn("bar")
649 self.assertEqual(str(w.message), "bar")
650 self.assertEqual(str(w.warnings[0].message), "foo")
651 self.assertEqual(str(w.warnings[1].message), "bar")
652 w.reset()
653 self.assertEqual(w.warnings, [])
Nick Coghland2e09382008-09-11 12:11:06 +0000654
Florent Xicluna73588542010-03-18 19:51:47 +0000655 with test_support.check_warnings():
656 # defaults to quiet=True without argument
657 pass
658 with test_support.check_warnings(('foo', UserWarning)):
659 wmod.warn("foo")
660
661 with self.assertRaises(AssertionError):
662 with test_support.check_warnings(('', RuntimeWarning)):
663 # defaults to quiet=False with argument
664 pass
665 with self.assertRaises(AssertionError):
666 with test_support.check_warnings(('foo', RuntimeWarning)):
667 wmod.warn("foo")
Nick Coghland2e09382008-09-11 12:11:06 +0000668
669
Brett Cannon1eaf0742008-09-02 01:25:16 +0000670class CCatchWarningTests(CatchWarningTests):
Nick Coghlan38469e22008-07-13 12:23:47 +0000671 module = c_warnings
672
Brett Cannon1eaf0742008-09-02 01:25:16 +0000673class PyCatchWarningTests(CatchWarningTests):
Nick Coghlan38469e22008-07-13 12:23:47 +0000674 module = py_warnings
675
676
Brett Cannone9746892008-04-12 23:44:07 +0000677def test_main():
Amaury Forgeot d'Arc607bff12008-04-18 23:31:33 +0000678 py_warnings.onceregistry.clear()
679 c_warnings.onceregistry.clear()
Brett Cannon1eaf0742008-09-02 01:25:16 +0000680 test_support.run_unittest(CFilterTests, PyFilterTests,
681 CWarnTests, PyWarnTests,
Brett Cannone9746892008-04-12 23:44:07 +0000682 CWCmdLineTests, PyWCmdLineTests,
683 _WarningsTests,
684 CWarningsDisplayTests, PyWarningsDisplayTests,
Brett Cannon1eaf0742008-09-02 01:25:16 +0000685 CCatchWarningTests, PyCatchWarningTests,
Brett Cannone9746892008-04-12 23:44:07 +0000686 )
687
688
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000689if __name__ == "__main__":
Brett Cannone9746892008-04-12 23:44:07 +0000690 test_main()