blob: 79922b21521a3eeb2cf4e9164e022555a705b281 [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
30 try:
31 warning_tests.warnings = module
32 yield
33 finally:
34 warning_tests.warnings = original_warnings
35
36
Brett Cannon667bb4f2008-04-13 02:42:36 +000037class BaseTest(unittest.TestCase):
Brett Cannone9746892008-04-12 23:44:07 +000038
Brett Cannon667bb4f2008-04-13 02:42:36 +000039 """Basic bookkeeping required for testing."""
Brett Cannone9746892008-04-12 23:44:07 +000040
41 def setUp(self):
Brett Cannon667bb4f2008-04-13 02:42:36 +000042 # The __warningregistry__ needs to be in a pristine state for tests
43 # to work properly.
44 if '__warningregistry__' in globals():
45 del globals()['__warningregistry__']
46 if hasattr(warning_tests, '__warningregistry__'):
47 del warning_tests.__warningregistry__
48 if hasattr(sys, '__warningregistry__'):
49 del sys.__warningregistry__
50 # The 'warnings' module must be explicitly set so that the proper
51 # interaction between _warnings and 'warnings' can be controlled.
52 sys.modules['warnings'] = self.module
53 super(BaseTest, self).setUp()
54
55 def tearDown(self):
56 sys.modules['warnings'] = original_warnings
57 super(BaseTest, self).tearDown()
58
59
60class FilterTests(object):
61
62 """Testing the filtering functionality."""
Brett Cannone9746892008-04-12 23:44:07 +000063
64 def test_error(self):
Brett Cannon672237d2008-09-09 00:49:16 +000065 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +000066 self.module.resetwarnings()
67 self.module.filterwarnings("error", category=UserWarning)
68 self.assertRaises(UserWarning, self.module.warn,
69 "FilterTests.test_error")
70
71 def test_ignore(self):
Brett Cannon672237d2008-09-09 00:49:16 +000072 with original_warnings.catch_warnings(record=True,
73 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +000074 self.module.resetwarnings()
75 self.module.filterwarnings("ignore", category=UserWarning)
76 self.module.warn("FilterTests.test_ignore", UserWarning)
Brett Cannon1eaf0742008-09-02 01:25:16 +000077 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +000078
79 def test_always(self):
Brett Cannon672237d2008-09-09 00:49:16 +000080 with original_warnings.catch_warnings(record=True,
81 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +000082 self.module.resetwarnings()
83 self.module.filterwarnings("always", category=UserWarning)
84 message = "FilterTests.test_always"
85 self.module.warn(message, UserWarning)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000086 self.assertTrue(message, w[-1].message)
Brett Cannone9746892008-04-12 23:44:07 +000087 self.module.warn(message, UserWarning)
Benjamin Peterson5c8da862009-06-30 22:57:08 +000088 self.assertTrue(w[-1].message, message)
Brett Cannone9746892008-04-12 23:44:07 +000089
90 def test_default(self):
Brett Cannon672237d2008-09-09 00:49:16 +000091 with original_warnings.catch_warnings(record=True,
92 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +000093 self.module.resetwarnings()
94 self.module.filterwarnings("default", category=UserWarning)
95 message = UserWarning("FilterTests.test_default")
96 for x in xrange(2):
97 self.module.warn(message, UserWarning)
98 if x == 0:
Brett Cannon672237d2008-09-09 00:49:16 +000099 self.assertEquals(w[-1].message, message)
100 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000101 elif x == 1:
Brett Cannon672237d2008-09-09 00:49:16 +0000102 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000103 else:
104 raise ValueError("loop variant unhandled")
105
106 def test_module(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000107 with original_warnings.catch_warnings(record=True,
108 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000109 self.module.resetwarnings()
110 self.module.filterwarnings("module", category=UserWarning)
111 message = UserWarning("FilterTests.test_module")
112 self.module.warn(message, UserWarning)
Brett Cannon672237d2008-09-09 00:49:16 +0000113 self.assertEquals(w[-1].message, message)
114 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000115 self.module.warn(message, UserWarning)
Brett Cannon672237d2008-09-09 00:49:16 +0000116 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000117
118 def test_once(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000119 with original_warnings.catch_warnings(record=True,
120 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000121 self.module.resetwarnings()
122 self.module.filterwarnings("once", category=UserWarning)
123 message = UserWarning("FilterTests.test_once")
124 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
125 42)
Brett Cannon672237d2008-09-09 00:49:16 +0000126 self.assertEquals(w[-1].message, message)
127 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000128 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
129 13)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000130 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000131 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
132 42)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000133 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000134
135 def test_inheritance(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000136 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000137 self.module.resetwarnings()
138 self.module.filterwarnings("error", category=Warning)
139 self.assertRaises(UserWarning, self.module.warn,
140 "FilterTests.test_inheritance", UserWarning)
141
142 def test_ordering(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000143 with original_warnings.catch_warnings(record=True,
144 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000145 self.module.resetwarnings()
146 self.module.filterwarnings("ignore", category=UserWarning)
147 self.module.filterwarnings("error", category=UserWarning,
148 append=True)
Brett Cannon672237d2008-09-09 00:49:16 +0000149 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000150 try:
151 self.module.warn("FilterTests.test_ordering", UserWarning)
152 except UserWarning:
153 self.fail("order handling for actions failed")
Brett Cannon1eaf0742008-09-02 01:25:16 +0000154 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000155
156 def test_filterwarnings(self):
157 # Test filterwarnings().
158 # Implicitly also tests resetwarnings().
Brett Cannon672237d2008-09-09 00:49:16 +0000159 with original_warnings.catch_warnings(record=True,
160 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000161 self.module.filterwarnings("error", "", Warning, "", 0)
162 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
163
164 self.module.resetwarnings()
165 text = 'handle normally'
166 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000167 self.assertEqual(str(w[-1].message), text)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000168 self.assertTrue(w[-1].category is UserWarning)
Brett Cannone9746892008-04-12 23:44:07 +0000169
170 self.module.filterwarnings("ignore", "", Warning, "", 0)
171 text = 'filtered out'
172 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000173 self.assertNotEqual(str(w[-1].message), text)
Brett Cannone9746892008-04-12 23:44:07 +0000174
175 self.module.resetwarnings()
176 self.module.filterwarnings("error", "hex*", Warning, "", 0)
177 self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
178 text = 'nonmatching text'
179 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000180 self.assertEqual(str(w[-1].message), text)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000181 self.assertTrue(w[-1].category is UserWarning)
Brett Cannone9746892008-04-12 23:44:07 +0000182
Brett Cannon667bb4f2008-04-13 02:42:36 +0000183class CFilterTests(BaseTest, FilterTests):
Brett Cannone9746892008-04-12 23:44:07 +0000184 module = c_warnings
185
Brett Cannon667bb4f2008-04-13 02:42:36 +0000186class PyFilterTests(BaseTest, FilterTests):
Brett Cannone9746892008-04-12 23:44:07 +0000187 module = py_warnings
188
189
190class WarnTests(unittest.TestCase):
191
192 """Test warnings.warn() and warnings.warn_explicit()."""
193
194 def test_message(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000195 with original_warnings.catch_warnings(record=True,
196 module=self.module) as w:
Walter Dörwalde6dae6c2007-04-03 18:33:29 +0000197 for i in range(4):
Brett Cannone9746892008-04-12 23:44:07 +0000198 text = 'multi %d' %i # Different text on each call.
199 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000200 self.assertEqual(str(w[-1].message), text)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000201 self.assertTrue(w[-1].category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000202
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000203 def test_filename(self):
Brett Cannone9746892008-04-12 23:44:07 +0000204 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000205 with original_warnings.catch_warnings(record=True,
206 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000207 warning_tests.inner("spam1")
Brett Cannon672237d2008-09-09 00:49:16 +0000208 self.assertEqual(os.path.basename(w[-1].filename),
209 "warning_tests.py")
Brett Cannone9746892008-04-12 23:44:07 +0000210 warning_tests.outer("spam2")
Brett Cannon672237d2008-09-09 00:49:16 +0000211 self.assertEqual(os.path.basename(w[-1].filename),
212 "warning_tests.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000213
214 def test_stacklevel(self):
215 # Test stacklevel argument
216 # make sure all messages are different, so the warning won't be skipped
Brett Cannone9746892008-04-12 23:44:07 +0000217 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000218 with original_warnings.catch_warnings(record=True,
219 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000220 warning_tests.inner("spam3", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000221 self.assertEqual(os.path.basename(w[-1].filename),
222 "warning_tests.py")
Brett Cannone9746892008-04-12 23:44:07 +0000223 warning_tests.outer("spam4", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000224 self.assertEqual(os.path.basename(w[-1].filename),
225 "warning_tests.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000226
Brett Cannone9746892008-04-12 23:44:07 +0000227 warning_tests.inner("spam5", stacklevel=2)
Brett Cannon672237d2008-09-09 00:49:16 +0000228 self.assertEqual(os.path.basename(w[-1].filename),
229 "test_warnings.py")
Brett Cannone9746892008-04-12 23:44:07 +0000230 warning_tests.outer("spam6", stacklevel=2)
Brett Cannon672237d2008-09-09 00:49:16 +0000231 self.assertEqual(os.path.basename(w[-1].filename),
232 "warning_tests.py")
Brett Cannone3dcb012008-05-06 04:37:31 +0000233 warning_tests.outer("spam6.5", stacklevel=3)
Brett Cannon672237d2008-09-09 00:49:16 +0000234 self.assertEqual(os.path.basename(w[-1].filename),
235 "test_warnings.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000236
Brett Cannone9746892008-04-12 23:44:07 +0000237 warning_tests.inner("spam7", stacklevel=9999)
Brett Cannon672237d2008-09-09 00:49:16 +0000238 self.assertEqual(os.path.basename(w[-1].filename),
239 "sys")
Brett Cannone9746892008-04-12 23:44:07 +0000240
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000241 def test_missing_filename_not_main(self):
242 # If __file__ is not specified and __main__ is not the module name,
243 # then __file__ should be set to the module name.
244 filename = warning_tests.__file__
245 try:
246 del warning_tests.__file__
247 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000248 with original_warnings.catch_warnings(record=True,
249 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000250 warning_tests.inner("spam8", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000251 self.assertEqual(w[-1].filename, warning_tests.__name__)
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000252 finally:
253 warning_tests.__file__ = filename
254
255 def test_missing_filename_main_with_argv(self):
256 # If __file__ is not specified and the caller is __main__ and sys.argv
257 # exists, then use sys.argv[0] as the file.
258 if not hasattr(sys, 'argv'):
259 return
260 filename = warning_tests.__file__
261 module_name = warning_tests.__name__
262 try:
263 del warning_tests.__file__
264 warning_tests.__name__ = '__main__'
265 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000266 with original_warnings.catch_warnings(record=True,
267 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000268 warning_tests.inner('spam9', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000269 self.assertEqual(w[-1].filename, sys.argv[0])
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000270 finally:
271 warning_tests.__file__ = filename
272 warning_tests.__name__ = module_name
273
274 def test_missing_filename_main_without_argv(self):
275 # If __file__ is not specified, the caller is __main__, and sys.argv
276 # is not set, then '__main__' is the file name.
277 filename = warning_tests.__file__
278 module_name = warning_tests.__name__
279 argv = sys.argv
280 try:
281 del warning_tests.__file__
282 warning_tests.__name__ = '__main__'
283 del sys.argv
284 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000285 with original_warnings.catch_warnings(record=True,
286 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000287 warning_tests.inner('spam10', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000288 self.assertEqual(w[-1].filename, '__main__')
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000289 finally:
290 warning_tests.__file__ = filename
291 warning_tests.__name__ = module_name
292 sys.argv = argv
293
294 def test_missing_filename_main_with_argv_empty_string(self):
295 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
296 # is the empty string, then '__main__ is the file name.
297 # Tests issue 2743.
298 file_name = warning_tests.__file__
299 module_name = warning_tests.__name__
300 argv = sys.argv
301 try:
302 del warning_tests.__file__
303 warning_tests.__name__ = '__main__'
304 sys.argv = ['']
305 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000306 with original_warnings.catch_warnings(record=True,
307 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000308 warning_tests.inner('spam11', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000309 self.assertEqual(w[-1].filename, '__main__')
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000310 finally:
311 warning_tests.__file__ = file_name
312 warning_tests.__name__ = module_name
313 sys.argv = argv
314
Brett Cannondea1b562008-06-27 00:31:13 +0000315 def test_warn_explicit_type_errors(self):
316 # warn_explicit() shoud error out gracefully if it is given objects
317 # of the wrong types.
318 # lineno is expected to be an integer.
319 self.assertRaises(TypeError, self.module.warn_explicit,
320 None, UserWarning, None, None)
321 # Either 'message' needs to be an instance of Warning or 'category'
322 # needs to be a subclass.
323 self.assertRaises(TypeError, self.module.warn_explicit,
324 None, None, None, 1)
325 # 'registry' must be a dict or None.
326 self.assertRaises((TypeError, AttributeError),
327 self.module.warn_explicit,
328 None, Warning, None, 1, registry=42)
329
Hirokazu Yamamotoe78e5d22009-07-17 06:20:46 +0000330 def test_bad_str(self):
331 # issue 6415
332 # Warnings instance with a bad format string for __str__ should not
333 # trigger a bus error.
334 class BadStrWarning(Warning):
335 """Warning with a bad format string for __str__."""
336 def __str__(self):
337 return ("A bad formatted string %(err)" %
338 {"err" : "there is no %(err)s"})
339
340 with self.assertRaises(ValueError):
341 self.module.warn(BadStrWarning())
342
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000343
Brett Cannon667bb4f2008-04-13 02:42:36 +0000344class CWarnTests(BaseTest, WarnTests):
Brett Cannone9746892008-04-12 23:44:07 +0000345 module = c_warnings
346
Nick Coghlancd2e7042009-04-11 13:31:31 +0000347 # As an early adopter, we sanity check the
348 # test_support.import_fresh_module utility function
349 def test_accelerated(self):
350 self.assertFalse(original_warnings is self.module)
351 self.assertFalse(hasattr(self.module.warn, 'func_code'))
352
Brett Cannon667bb4f2008-04-13 02:42:36 +0000353class PyWarnTests(BaseTest, WarnTests):
Brett Cannone9746892008-04-12 23:44:07 +0000354 module = py_warnings
355
Nick Coghlancd2e7042009-04-11 13:31:31 +0000356 # As an early adopter, we sanity check the
357 # test_support.import_fresh_module utility function
358 def test_pure_python(self):
359 self.assertFalse(original_warnings is self.module)
360 self.assertTrue(hasattr(self.module.warn, 'func_code'))
361
Brett Cannone9746892008-04-12 23:44:07 +0000362
363class WCmdLineTests(unittest.TestCase):
364
365 def test_improper_input(self):
366 # Uses the private _setoption() function to test the parsing
367 # of command-line warning arguments
Brett Cannon672237d2008-09-09 00:49:16 +0000368 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000369 self.assertRaises(self.module._OptionError,
370 self.module._setoption, '1:2:3:4:5:6')
371 self.assertRaises(self.module._OptionError,
372 self.module._setoption, 'bogus::Warning')
373 self.assertRaises(self.module._OptionError,
374 self.module._setoption, 'ignore:2::4:-5')
375 self.module._setoption('error::Warning::0')
376 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
377
Brett Cannon667bb4f2008-04-13 02:42:36 +0000378class CWCmdLineTests(BaseTest, WCmdLineTests):
Brett Cannone9746892008-04-12 23:44:07 +0000379 module = c_warnings
380
Brett Cannon667bb4f2008-04-13 02:42:36 +0000381class PyWCmdLineTests(BaseTest, WCmdLineTests):
Brett Cannone9746892008-04-12 23:44:07 +0000382 module = py_warnings
383
384
Brett Cannon667bb4f2008-04-13 02:42:36 +0000385class _WarningsTests(BaseTest):
Brett Cannone9746892008-04-12 23:44:07 +0000386
387 """Tests specific to the _warnings module."""
388
389 module = c_warnings
390
391 def test_filter(self):
392 # Everything should function even if 'filters' is not in warnings.
Brett Cannon672237d2008-09-09 00:49:16 +0000393 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000394 self.module.filterwarnings("error", "", Warning, "", 0)
395 self.assertRaises(UserWarning, self.module.warn,
396 'convert to error')
397 del self.module.filters
398 self.assertRaises(UserWarning, self.module.warn,
399 'convert to error')
400
401 def test_onceregistry(self):
402 # Replacing or removing the onceregistry should be okay.
403 global __warningregistry__
404 message = UserWarning('onceregistry test')
405 try:
406 original_registry = self.module.onceregistry
407 __warningregistry__ = {}
Brett Cannon672237d2008-09-09 00:49:16 +0000408 with original_warnings.catch_warnings(record=True,
409 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000410 self.module.resetwarnings()
411 self.module.filterwarnings("once", category=UserWarning)
412 self.module.warn_explicit(message, UserWarning, "file", 42)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000413 self.assertEqual(w[-1].message, message)
Brett Cannon672237d2008-09-09 00:49:16 +0000414 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000415 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000416 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000417 # Test the resetting of onceregistry.
418 self.module.onceregistry = {}
419 __warningregistry__ = {}
420 self.module.warn('onceregistry test')
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000421 self.assertEqual(w[-1].message.args, message.args)
Brett Cannone9746892008-04-12 23:44:07 +0000422 # Removal of onceregistry is okay.
Brett Cannon672237d2008-09-09 00:49:16 +0000423 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000424 del self.module.onceregistry
425 __warningregistry__ = {}
426 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000427 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000428 finally:
429 self.module.onceregistry = original_registry
430
Brett Cannon15ba4da2009-04-01 18:03:59 +0000431 def test_default_action(self):
432 # Replacing or removing defaultaction should be okay.
433 message = UserWarning("defaultaction test")
434 original = self.module.defaultaction
435 try:
436 with original_warnings.catch_warnings(record=True,
437 module=self.module) as w:
438 self.module.resetwarnings()
439 registry = {}
440 self.module.warn_explicit(message, UserWarning, "<test>", 42,
441 registry=registry)
442 self.assertEqual(w[-1].message, message)
443 self.assertEqual(len(w), 1)
444 self.assertEqual(len(registry), 1)
445 del w[:]
446 # Test removal.
447 del self.module.defaultaction
448 __warningregistry__ = {}
449 registry = {}
450 self.module.warn_explicit(message, UserWarning, "<test>", 43,
451 registry=registry)
452 self.assertEqual(w[-1].message, message)
453 self.assertEqual(len(w), 1)
454 self.assertEqual(len(registry), 1)
455 del w[:]
456 # Test setting.
457 self.module.defaultaction = "ignore"
458 __warningregistry__ = {}
459 registry = {}
460 self.module.warn_explicit(message, UserWarning, "<test>", 44,
461 registry=registry)
462 self.assertEqual(len(w), 0)
463 finally:
464 self.module.defaultaction = original
465
Brett Cannone9746892008-04-12 23:44:07 +0000466 def test_showwarning_missing(self):
467 # Test that showwarning() missing is okay.
468 text = 'del showwarning test'
Brett Cannon672237d2008-09-09 00:49:16 +0000469 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000470 self.module.filterwarnings("always", category=UserWarning)
471 del self.module.showwarning
472 with test_support.captured_output('stderr') as stream:
473 self.module.warn(text)
474 result = stream.getvalue()
Ezio Melottiaa980582010-01-23 23:04:36 +0000475 self.assertIn(text, result)
Brett Cannone9746892008-04-12 23:44:07 +0000476
Benjamin Petersond2950322008-05-06 22:18:11 +0000477 def test_showwarning_not_callable(self):
Brett Cannonce3d2212009-04-01 20:25:48 +0000478 with original_warnings.catch_warnings(module=self.module):
479 self.module.filterwarnings("always", category=UserWarning)
480 old_showwarning = self.module.showwarning
481 self.module.showwarning = 23
482 try:
483 self.assertRaises(TypeError, self.module.warn, "Warning!")
484 finally:
485 self.module.showwarning = old_showwarning
Benjamin Petersond2950322008-05-06 22:18:11 +0000486
Brett Cannone9746892008-04-12 23:44:07 +0000487 def test_show_warning_output(self):
488 # With showarning() missing, make sure that output is okay.
489 text = 'test show_warning'
Brett Cannon672237d2008-09-09 00:49:16 +0000490 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000491 self.module.filterwarnings("always", category=UserWarning)
492 del self.module.showwarning
493 with test_support.captured_output('stderr') as stream:
494 warning_tests.inner(text)
495 result = stream.getvalue()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000496 self.assertEqual(result.count('\n'), 2,
Brett Cannone9746892008-04-12 23:44:07 +0000497 "Too many newlines in %r" % result)
498 first_line, second_line = result.split('\n', 1)
499 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Brett Cannonc4774272008-04-13 17:41:31 +0000500 first_line_parts = first_line.rsplit(':', 3)
Brett Cannon25bb8182008-04-13 17:09:43 +0000501 path, line, warning_class, message = first_line_parts
Brett Cannone9746892008-04-12 23:44:07 +0000502 line = int(line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000503 self.assertEqual(expected_file, path)
504 self.assertEqual(warning_class, ' ' + UserWarning.__name__)
505 self.assertEqual(message, ' ' + text)
Brett Cannone9746892008-04-12 23:44:07 +0000506 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
507 assert expected_line
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000508 self.assertEqual(second_line, expected_line)
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000509
Brett Cannon53ab5b72006-06-22 16:49:14 +0000510
Brett Cannon905c31c2007-12-20 10:09:52 +0000511class WarningsDisplayTests(unittest.TestCase):
512
Brett Cannone9746892008-04-12 23:44:07 +0000513 """Test the displaying of warnings and the ability to overload functions
514 related to displaying warnings."""
515
Brett Cannon905c31c2007-12-20 10:09:52 +0000516 def test_formatwarning(self):
517 message = "msg"
518 category = Warning
519 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
520 line_num = 3
521 file_line = linecache.getline(file_name, line_num).strip()
Brett Cannone9746892008-04-12 23:44:07 +0000522 format = "%s:%s: %s: %s\n %s\n"
523 expect = format % (file_name, line_num, category.__name__, message,
524 file_line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000525 self.assertEqual(expect, self.module.formatwarning(message,
Brett Cannone9746892008-04-12 23:44:07 +0000526 category, file_name, line_num))
527 # Test the 'line' argument.
528 file_line += " for the win!"
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, file_line))
Brett Cannon905c31c2007-12-20 10:09:52 +0000533
534 def test_showwarning(self):
535 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
536 line_num = 3
537 expected_file_line = linecache.getline(file_name, line_num).strip()
538 message = 'msg'
539 category = Warning
540 file_object = StringIO.StringIO()
Brett Cannone9746892008-04-12 23:44:07 +0000541 expect = self.module.formatwarning(message, category, file_name,
542 line_num)
543 self.module.showwarning(message, category, file_name, line_num,
Brett Cannon905c31c2007-12-20 10:09:52 +0000544 file_object)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000545 self.assertEqual(file_object.getvalue(), expect)
Brett Cannone9746892008-04-12 23:44:07 +0000546 # Test 'line' argument.
547 expected_file_line += "for the win!"
548 expect = self.module.formatwarning(message, category, file_name,
549 line_num, expected_file_line)
550 file_object = StringIO.StringIO()
551 self.module.showwarning(message, category, file_name, line_num,
552 file_object, expected_file_line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000553 self.assertEqual(expect, file_object.getvalue())
Brett Cannone9746892008-04-12 23:44:07 +0000554
Brett Cannon667bb4f2008-04-13 02:42:36 +0000555class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
Brett Cannone9746892008-04-12 23:44:07 +0000556 module = c_warnings
557
Brett Cannon667bb4f2008-04-13 02:42:36 +0000558class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
Brett Cannone9746892008-04-12 23:44:07 +0000559 module = py_warnings
Brett Cannon905c31c2007-12-20 10:09:52 +0000560
561
Brett Cannon1eaf0742008-09-02 01:25:16 +0000562class CatchWarningTests(BaseTest):
Nick Coghlan38469e22008-07-13 12:23:47 +0000563
Brett Cannon1eaf0742008-09-02 01:25:16 +0000564 """Test catch_warnings()."""
565
566 def test_catch_warnings_restore(self):
Nick Coghlan38469e22008-07-13 12:23:47 +0000567 wmod = self.module
568 orig_filters = wmod.filters
569 orig_showwarning = wmod.showwarning
Nick Coghland2e09382008-09-11 12:11:06 +0000570 # Ensure both showwarning and filters are restored when recording
571 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlan38469e22008-07-13 12:23:47 +0000572 wmod.filters = wmod.showwarning = object()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000573 self.assertTrue(wmod.filters is orig_filters)
574 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghland2e09382008-09-11 12:11:06 +0000575 # Same test, but with recording disabled
Brett Cannon1eaf0742008-09-02 01:25:16 +0000576 with wmod.catch_warnings(module=wmod, record=False):
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 Coghlan38469e22008-07-13 12:23:47 +0000580
Brett Cannon1eaf0742008-09-02 01:25:16 +0000581 def test_catch_warnings_recording(self):
Nick Coghlan38469e22008-07-13 12:23:47 +0000582 wmod = self.module
Nick Coghland2e09382008-09-11 12:11:06 +0000583 # Ensure warnings are recorded when requested
Brett Cannon1eaf0742008-09-02 01:25:16 +0000584 with wmod.catch_warnings(module=wmod, record=True) as w:
585 self.assertEqual(w, [])
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000586 self.assertTrue(type(w) is list)
Nick Coghlan38469e22008-07-13 12:23:47 +0000587 wmod.simplefilter("always")
588 wmod.warn("foo")
Brett Cannon672237d2008-09-09 00:49:16 +0000589 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlan38469e22008-07-13 12:23:47 +0000590 wmod.warn("bar")
Brett Cannon672237d2008-09-09 00:49:16 +0000591 self.assertEqual(str(w[-1].message), "bar")
Brett Cannon1eaf0742008-09-02 01:25:16 +0000592 self.assertEqual(str(w[0].message), "foo")
593 self.assertEqual(str(w[1].message), "bar")
Brett Cannon672237d2008-09-09 00:49:16 +0000594 del w[:]
Brett Cannon1eaf0742008-09-02 01:25:16 +0000595 self.assertEqual(w, [])
Nick Coghland2e09382008-09-11 12:11:06 +0000596 # Ensure warnings are not recorded when not requested
Nick Coghlan38469e22008-07-13 12:23:47 +0000597 orig_showwarning = wmod.showwarning
Brett Cannon1eaf0742008-09-02 01:25:16 +0000598 with wmod.catch_warnings(module=wmod, record=False) as w:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000599 self.assertTrue(w is None)
600 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlan38469e22008-07-13 12:23:47 +0000601
Nick Coghland2e09382008-09-11 12:11:06 +0000602 def test_catch_warnings_reentry_guard(self):
603 wmod = self.module
604 # Ensure catch_warnings is protected against incorrect usage
605 x = wmod.catch_warnings(module=wmod, record=True)
606 self.assertRaises(RuntimeError, x.__exit__)
607 with x:
608 self.assertRaises(RuntimeError, x.__enter__)
609 # Same test, but with recording disabled
610 x = wmod.catch_warnings(module=wmod, record=False)
611 self.assertRaises(RuntimeError, x.__exit__)
612 with x:
613 self.assertRaises(RuntimeError, x.__enter__)
614
615 def test_catch_warnings_defaults(self):
616 wmod = self.module
617 orig_filters = wmod.filters
618 orig_showwarning = wmod.showwarning
619 # Ensure default behaviour is not to record warnings
620 with wmod.catch_warnings(module=wmod) as w:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000621 self.assertTrue(w is None)
622 self.assertTrue(wmod.showwarning is orig_showwarning)
623 self.assertTrue(wmod.filters is not orig_filters)
624 self.assertTrue(wmod.filters is orig_filters)
Nick Coghland2e09382008-09-11 12:11:06 +0000625 if wmod is sys.modules['warnings']:
626 # Ensure the default module is this one
627 with wmod.catch_warnings() as w:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000628 self.assertTrue(w is None)
629 self.assertTrue(wmod.showwarning is orig_showwarning)
630 self.assertTrue(wmod.filters is not orig_filters)
631 self.assertTrue(wmod.filters is orig_filters)
Nick Coghland2e09382008-09-11 12:11:06 +0000632
633 def test_check_warnings(self):
634 # Explicit tests for the test_support convenience wrapper
635 wmod = self.module
Florent Xicluna73588542010-03-18 19:51:47 +0000636 if wmod is not sys.modules['warnings']:
637 return
638 with test_support.check_warnings(quiet=False) as w:
639 self.assertEqual(w.warnings, [])
640 wmod.simplefilter("always")
641 wmod.warn("foo")
642 self.assertEqual(str(w.message), "foo")
643 wmod.warn("bar")
644 self.assertEqual(str(w.message), "bar")
645 self.assertEqual(str(w.warnings[0].message), "foo")
646 self.assertEqual(str(w.warnings[1].message), "bar")
647 w.reset()
648 self.assertEqual(w.warnings, [])
Nick Coghland2e09382008-09-11 12:11:06 +0000649
Florent Xicluna73588542010-03-18 19:51:47 +0000650 with test_support.check_warnings():
651 # defaults to quiet=True without argument
652 pass
653 with test_support.check_warnings(('foo', UserWarning)):
654 wmod.warn("foo")
655
656 with self.assertRaises(AssertionError):
657 with test_support.check_warnings(('', RuntimeWarning)):
658 # defaults to quiet=False with argument
659 pass
660 with self.assertRaises(AssertionError):
661 with test_support.check_warnings(('foo', RuntimeWarning)):
662 wmod.warn("foo")
Nick Coghland2e09382008-09-11 12:11:06 +0000663
664
Brett Cannon1eaf0742008-09-02 01:25:16 +0000665class CCatchWarningTests(CatchWarningTests):
Nick Coghlan38469e22008-07-13 12:23:47 +0000666 module = c_warnings
667
Brett Cannon1eaf0742008-09-02 01:25:16 +0000668class PyCatchWarningTests(CatchWarningTests):
Nick Coghlan38469e22008-07-13 12:23:47 +0000669 module = py_warnings
670
671
Brett Cannone9746892008-04-12 23:44:07 +0000672def test_main():
Amaury Forgeot d'Arc607bff12008-04-18 23:31:33 +0000673 py_warnings.onceregistry.clear()
674 c_warnings.onceregistry.clear()
Brett Cannon1eaf0742008-09-02 01:25:16 +0000675 test_support.run_unittest(CFilterTests, PyFilterTests,
676 CWarnTests, PyWarnTests,
Brett Cannone9746892008-04-12 23:44:07 +0000677 CWCmdLineTests, PyWCmdLineTests,
678 _WarningsTests,
679 CWarningsDisplayTests, PyWarningsDisplayTests,
Brett Cannon1eaf0742008-09-02 01:25:16 +0000680 CCatchWarningTests, PyCatchWarningTests,
Brett Cannone9746892008-04-12 23:44:07 +0000681 )
682
683
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000684if __name__ == "__main__":
Brett Cannone9746892008-04-12 23:44:07 +0000685 test_main()