blob: 71944cd15324ab4181350bb29171b7f60ffaccfb [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
Brett Cannone9746892008-04-12 23:44:07 +000013sys.modules['_warnings'] = 0
Brett Cannon667bb4f2008-04-13 02:42:36 +000014del sys.modules['warnings']
Jeremy Hylton85014662003-07-11 15:37:59 +000015
Brett Cannone9746892008-04-12 23:44:07 +000016import warnings as py_warnings
17
18del sys.modules['_warnings']
19del sys.modules['warnings']
20
21import warnings as c_warnings
22
Brett Cannon667bb4f2008-04-13 02:42:36 +000023sys.modules['warnings'] = original_warnings
24
25
Brett Cannone9746892008-04-12 23:44:07 +000026@contextmanager
27def warnings_state(module):
28 """Use a specific warnings implementation in warning_tests."""
29 global __warningregistry__
30 for to_clear in (sys, warning_tests):
31 try:
32 to_clear.__warningregistry__.clear()
33 except AttributeError:
34 pass
35 try:
36 __warningregistry__.clear()
37 except NameError:
38 pass
39 original_warnings = warning_tests.warnings
40 try:
41 warning_tests.warnings = module
42 yield
43 finally:
44 warning_tests.warnings = original_warnings
45
46
Brett Cannon667bb4f2008-04-13 02:42:36 +000047class BaseTest(unittest.TestCase):
Brett Cannone9746892008-04-12 23:44:07 +000048
Brett Cannon667bb4f2008-04-13 02:42:36 +000049 """Basic bookkeeping required for testing."""
Brett Cannone9746892008-04-12 23:44:07 +000050
51 def setUp(self):
Brett Cannon667bb4f2008-04-13 02:42:36 +000052 # The __warningregistry__ needs to be in a pristine state for tests
53 # to work properly.
54 if '__warningregistry__' in globals():
55 del globals()['__warningregistry__']
56 if hasattr(warning_tests, '__warningregistry__'):
57 del warning_tests.__warningregistry__
58 if hasattr(sys, '__warningregistry__'):
59 del sys.__warningregistry__
60 # The 'warnings' module must be explicitly set so that the proper
61 # interaction between _warnings and 'warnings' can be controlled.
62 sys.modules['warnings'] = self.module
63 super(BaseTest, self).setUp()
64
65 def tearDown(self):
66 sys.modules['warnings'] = original_warnings
67 super(BaseTest, self).tearDown()
68
69
70class FilterTests(object):
71
72 """Testing the filtering functionality."""
Brett Cannone9746892008-04-12 23:44:07 +000073
74 def test_error(self):
Brett Cannon672237d2008-09-09 00:49:16 +000075 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +000076 self.module.resetwarnings()
77 self.module.filterwarnings("error", category=UserWarning)
78 self.assertRaises(UserWarning, self.module.warn,
79 "FilterTests.test_error")
80
81 def test_ignore(self):
Brett Cannon672237d2008-09-09 00:49:16 +000082 with original_warnings.catch_warnings(record=True,
83 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +000084 self.module.resetwarnings()
85 self.module.filterwarnings("ignore", category=UserWarning)
86 self.module.warn("FilterTests.test_ignore", UserWarning)
Brett Cannon1eaf0742008-09-02 01:25:16 +000087 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +000088
89 def test_always(self):
Brett Cannon672237d2008-09-09 00:49:16 +000090 with original_warnings.catch_warnings(record=True,
91 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +000092 self.module.resetwarnings()
93 self.module.filterwarnings("always", category=UserWarning)
94 message = "FilterTests.test_always"
95 self.module.warn(message, UserWarning)
Brett Cannon672237d2008-09-09 00:49:16 +000096 self.assert_(message, w[-1].message)
Brett Cannone9746892008-04-12 23:44:07 +000097 self.module.warn(message, UserWarning)
Brett Cannon672237d2008-09-09 00:49:16 +000098 self.assert_(w[-1].message, message)
Brett Cannone9746892008-04-12 23:44:07 +000099
100 def test_default(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000101 with original_warnings.catch_warnings(record=True,
102 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000103 self.module.resetwarnings()
104 self.module.filterwarnings("default", category=UserWarning)
105 message = UserWarning("FilterTests.test_default")
106 for x in xrange(2):
107 self.module.warn(message, UserWarning)
108 if x == 0:
Brett Cannon672237d2008-09-09 00:49:16 +0000109 self.assertEquals(w[-1].message, message)
110 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000111 elif x == 1:
Brett Cannon672237d2008-09-09 00:49:16 +0000112 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000113 else:
114 raise ValueError("loop variant unhandled")
115
116 def test_module(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000117 with original_warnings.catch_warnings(record=True,
118 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000119 self.module.resetwarnings()
120 self.module.filterwarnings("module", category=UserWarning)
121 message = UserWarning("FilterTests.test_module")
122 self.module.warn(message, UserWarning)
Brett Cannon672237d2008-09-09 00:49:16 +0000123 self.assertEquals(w[-1].message, message)
124 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000125 self.module.warn(message, UserWarning)
Brett Cannon672237d2008-09-09 00:49:16 +0000126 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000127
128 def test_once(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000129 with original_warnings.catch_warnings(record=True,
130 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000131 self.module.resetwarnings()
132 self.module.filterwarnings("once", category=UserWarning)
133 message = UserWarning("FilterTests.test_once")
134 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
135 42)
Brett Cannon672237d2008-09-09 00:49:16 +0000136 self.assertEquals(w[-1].message, message)
137 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000138 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
139 13)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000140 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000141 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
142 42)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000143 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000144
145 def test_inheritance(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000146 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000147 self.module.resetwarnings()
148 self.module.filterwarnings("error", category=Warning)
149 self.assertRaises(UserWarning, self.module.warn,
150 "FilterTests.test_inheritance", UserWarning)
151
152 def test_ordering(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000153 with original_warnings.catch_warnings(record=True,
154 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000155 self.module.resetwarnings()
156 self.module.filterwarnings("ignore", category=UserWarning)
157 self.module.filterwarnings("error", category=UserWarning,
158 append=True)
Brett Cannon672237d2008-09-09 00:49:16 +0000159 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000160 try:
161 self.module.warn("FilterTests.test_ordering", UserWarning)
162 except UserWarning:
163 self.fail("order handling for actions failed")
Brett Cannon1eaf0742008-09-02 01:25:16 +0000164 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000165
166 def test_filterwarnings(self):
167 # Test filterwarnings().
168 # Implicitly also tests resetwarnings().
Brett Cannon672237d2008-09-09 00:49:16 +0000169 with original_warnings.catch_warnings(record=True,
170 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000171 self.module.filterwarnings("error", "", Warning, "", 0)
172 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
173
174 self.module.resetwarnings()
175 text = 'handle normally'
176 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000177 self.assertEqual(str(w[-1].message), text)
178 self.assert_(w[-1].category is UserWarning)
Brett Cannone9746892008-04-12 23:44:07 +0000179
180 self.module.filterwarnings("ignore", "", Warning, "", 0)
181 text = 'filtered out'
182 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000183 self.assertNotEqual(str(w[-1].message), text)
Brett Cannone9746892008-04-12 23:44:07 +0000184
185 self.module.resetwarnings()
186 self.module.filterwarnings("error", "hex*", Warning, "", 0)
187 self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
188 text = 'nonmatching text'
189 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000190 self.assertEqual(str(w[-1].message), text)
191 self.assert_(w[-1].category is UserWarning)
Brett Cannone9746892008-04-12 23:44:07 +0000192
Brett Cannon667bb4f2008-04-13 02:42:36 +0000193class CFilterTests(BaseTest, FilterTests):
Brett Cannone9746892008-04-12 23:44:07 +0000194 module = c_warnings
195
Brett Cannon667bb4f2008-04-13 02:42:36 +0000196class PyFilterTests(BaseTest, FilterTests):
Brett Cannone9746892008-04-12 23:44:07 +0000197 module = py_warnings
198
199
200class WarnTests(unittest.TestCase):
201
202 """Test warnings.warn() and warnings.warn_explicit()."""
203
204 def test_message(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000205 with original_warnings.catch_warnings(record=True,
206 module=self.module) as w:
Walter Dörwalde6dae6c2007-04-03 18:33:29 +0000207 for i in range(4):
Brett Cannone9746892008-04-12 23:44:07 +0000208 text = 'multi %d' %i # Different text on each call.
209 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000210 self.assertEqual(str(w[-1].message), text)
211 self.assert_(w[-1].category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000212
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000213 def test_filename(self):
Brett Cannone9746892008-04-12 23:44:07 +0000214 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000215 with original_warnings.catch_warnings(record=True,
216 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000217 warning_tests.inner("spam1")
Brett Cannon672237d2008-09-09 00:49:16 +0000218 self.assertEqual(os.path.basename(w[-1].filename),
219 "warning_tests.py")
Brett Cannone9746892008-04-12 23:44:07 +0000220 warning_tests.outer("spam2")
Brett Cannon672237d2008-09-09 00:49:16 +0000221 self.assertEqual(os.path.basename(w[-1].filename),
222 "warning_tests.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000223
224 def test_stacklevel(self):
225 # Test stacklevel argument
226 # make sure all messages are different, so the warning won't be skipped
Brett Cannone9746892008-04-12 23:44:07 +0000227 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000228 with original_warnings.catch_warnings(record=True,
229 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000230 warning_tests.inner("spam3", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000231 self.assertEqual(os.path.basename(w[-1].filename),
232 "warning_tests.py")
Brett Cannone9746892008-04-12 23:44:07 +0000233 warning_tests.outer("spam4", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000234 self.assertEqual(os.path.basename(w[-1].filename),
235 "warning_tests.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000236
Brett Cannone9746892008-04-12 23:44:07 +0000237 warning_tests.inner("spam5", stacklevel=2)
Brett Cannon672237d2008-09-09 00:49:16 +0000238 self.assertEqual(os.path.basename(w[-1].filename),
239 "test_warnings.py")
Brett Cannone9746892008-04-12 23:44:07 +0000240 warning_tests.outer("spam6", stacklevel=2)
Brett Cannon672237d2008-09-09 00:49:16 +0000241 self.assertEqual(os.path.basename(w[-1].filename),
242 "warning_tests.py")
Brett Cannone3dcb012008-05-06 04:37:31 +0000243 warning_tests.outer("spam6.5", stacklevel=3)
Brett Cannon672237d2008-09-09 00:49:16 +0000244 self.assertEqual(os.path.basename(w[-1].filename),
245 "test_warnings.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000246
Brett Cannone9746892008-04-12 23:44:07 +0000247 warning_tests.inner("spam7", stacklevel=9999)
Brett Cannon672237d2008-09-09 00:49:16 +0000248 self.assertEqual(os.path.basename(w[-1].filename),
249 "sys")
Brett Cannone9746892008-04-12 23:44:07 +0000250
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000251 def test_missing_filename_not_main(self):
252 # If __file__ is not specified and __main__ is not the module name,
253 # then __file__ should be set to the module name.
254 filename = warning_tests.__file__
255 try:
256 del warning_tests.__file__
257 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000258 with original_warnings.catch_warnings(record=True,
259 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000260 warning_tests.inner("spam8", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000261 self.assertEqual(w[-1].filename, warning_tests.__name__)
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000262 finally:
263 warning_tests.__file__ = filename
264
265 def test_missing_filename_main_with_argv(self):
266 # If __file__ is not specified and the caller is __main__ and sys.argv
267 # exists, then use sys.argv[0] as the file.
268 if not hasattr(sys, 'argv'):
269 return
270 filename = warning_tests.__file__
271 module_name = warning_tests.__name__
272 try:
273 del warning_tests.__file__
274 warning_tests.__name__ = '__main__'
275 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000276 with original_warnings.catch_warnings(record=True,
277 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000278 warning_tests.inner('spam9', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000279 self.assertEqual(w[-1].filename, sys.argv[0])
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000280 finally:
281 warning_tests.__file__ = filename
282 warning_tests.__name__ = module_name
283
284 def test_missing_filename_main_without_argv(self):
285 # If __file__ is not specified, the caller is __main__, and sys.argv
286 # is not set, then '__main__' is the file name.
287 filename = warning_tests.__file__
288 module_name = warning_tests.__name__
289 argv = sys.argv
290 try:
291 del warning_tests.__file__
292 warning_tests.__name__ = '__main__'
293 del sys.argv
294 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000295 with original_warnings.catch_warnings(record=True,
296 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000297 warning_tests.inner('spam10', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000298 self.assertEqual(w[-1].filename, '__main__')
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000299 finally:
300 warning_tests.__file__ = filename
301 warning_tests.__name__ = module_name
302 sys.argv = argv
303
304 def test_missing_filename_main_with_argv_empty_string(self):
305 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
306 # is the empty string, then '__main__ is the file name.
307 # Tests issue 2743.
308 file_name = warning_tests.__file__
309 module_name = warning_tests.__name__
310 argv = sys.argv
311 try:
312 del warning_tests.__file__
313 warning_tests.__name__ = '__main__'
314 sys.argv = ['']
315 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000316 with original_warnings.catch_warnings(record=True,
317 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000318 warning_tests.inner('spam11', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000319 self.assertEqual(w[-1].filename, '__main__')
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000320 finally:
321 warning_tests.__file__ = file_name
322 warning_tests.__name__ = module_name
323 sys.argv = argv
324
Brett Cannondea1b562008-06-27 00:31:13 +0000325 def test_warn_explicit_type_errors(self):
326 # warn_explicit() shoud error out gracefully if it is given objects
327 # of the wrong types.
328 # lineno is expected to be an integer.
329 self.assertRaises(TypeError, self.module.warn_explicit,
330 None, UserWarning, None, None)
331 # Either 'message' needs to be an instance of Warning or 'category'
332 # needs to be a subclass.
333 self.assertRaises(TypeError, self.module.warn_explicit,
334 None, None, None, 1)
335 # 'registry' must be a dict or None.
336 self.assertRaises((TypeError, AttributeError),
337 self.module.warn_explicit,
338 None, Warning, None, 1, registry=42)
339
Hirokazu Yamamotofcaa2102009-07-17 06:33:03 +0000340 def test_bad_str(self):
341 # issue 6415
342 # Warnings instance with a bad format string for __str__ should not
343 # trigger a bus error.
344 class BadStrWarning(Warning):
345 """Warning with a bad format string for __str__."""
346 def __str__(self):
347 return ("A bad formatted string %(err)" %
348 {"err" : "there is no %(err)s"})
349
Hirokazu Yamamoto8bb2d5d2009-07-19 03:39:54 +0000350 self.assertRaises(ValueError, self.module.warn, BadStrWarning())
Hirokazu Yamamotofcaa2102009-07-17 06:33:03 +0000351
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000352
Brett Cannon667bb4f2008-04-13 02:42:36 +0000353class CWarnTests(BaseTest, WarnTests):
Brett Cannone9746892008-04-12 23:44:07 +0000354 module = c_warnings
355
Brett Cannon667bb4f2008-04-13 02:42:36 +0000356class PyWarnTests(BaseTest, WarnTests):
Brett Cannone9746892008-04-12 23:44:07 +0000357 module = py_warnings
358
359
360class WCmdLineTests(unittest.TestCase):
361
362 def test_improper_input(self):
363 # Uses the private _setoption() function to test the parsing
364 # of command-line warning arguments
Brett Cannon672237d2008-09-09 00:49:16 +0000365 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000366 self.assertRaises(self.module._OptionError,
367 self.module._setoption, '1:2:3:4:5:6')
368 self.assertRaises(self.module._OptionError,
369 self.module._setoption, 'bogus::Warning')
370 self.assertRaises(self.module._OptionError,
371 self.module._setoption, 'ignore:2::4:-5')
372 self.module._setoption('error::Warning::0')
373 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
374
Brett Cannon667bb4f2008-04-13 02:42:36 +0000375class CWCmdLineTests(BaseTest, WCmdLineTests):
Brett Cannone9746892008-04-12 23:44:07 +0000376 module = c_warnings
377
Brett Cannon667bb4f2008-04-13 02:42:36 +0000378class PyWCmdLineTests(BaseTest, WCmdLineTests):
Brett Cannone9746892008-04-12 23:44:07 +0000379 module = py_warnings
380
381
Brett Cannon667bb4f2008-04-13 02:42:36 +0000382class _WarningsTests(BaseTest):
Brett Cannone9746892008-04-12 23:44:07 +0000383
384 """Tests specific to the _warnings module."""
385
386 module = c_warnings
387
388 def test_filter(self):
389 # Everything should function even if 'filters' is not in warnings.
Brett Cannon672237d2008-09-09 00:49:16 +0000390 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000391 self.module.filterwarnings("error", "", Warning, "", 0)
392 self.assertRaises(UserWarning, self.module.warn,
393 'convert to error')
394 del self.module.filters
395 self.assertRaises(UserWarning, self.module.warn,
396 'convert to error')
397
398 def test_onceregistry(self):
399 # Replacing or removing the onceregistry should be okay.
400 global __warningregistry__
401 message = UserWarning('onceregistry test')
402 try:
403 original_registry = self.module.onceregistry
404 __warningregistry__ = {}
Brett Cannon672237d2008-09-09 00:49:16 +0000405 with original_warnings.catch_warnings(record=True,
406 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000407 self.module.resetwarnings()
408 self.module.filterwarnings("once", category=UserWarning)
409 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannon672237d2008-09-09 00:49:16 +0000410 self.failUnlessEqual(w[-1].message, message)
411 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000412 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000413 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000414 # Test the resetting of onceregistry.
415 self.module.onceregistry = {}
416 __warningregistry__ = {}
417 self.module.warn('onceregistry test')
Brett Cannon672237d2008-09-09 00:49:16 +0000418 self.failUnlessEqual(w[-1].message.args, message.args)
Brett Cannone9746892008-04-12 23:44:07 +0000419 # Removal of onceregistry is okay.
Brett Cannon672237d2008-09-09 00:49:16 +0000420 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000421 del self.module.onceregistry
422 __warningregistry__ = {}
423 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000424 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000425 finally:
426 self.module.onceregistry = original_registry
427
428 def test_showwarning_missing(self):
429 # Test that showwarning() missing is okay.
430 text = 'del showwarning test'
Brett Cannon672237d2008-09-09 00:49:16 +0000431 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000432 self.module.filterwarnings("always", category=UserWarning)
433 del self.module.showwarning
434 with test_support.captured_output('stderr') as stream:
435 self.module.warn(text)
436 result = stream.getvalue()
437 self.failUnless(text in result)
438
Benjamin Petersond2950322008-05-06 22:18:11 +0000439 def test_showwarning_not_callable(self):
440 self.module.filterwarnings("always", category=UserWarning)
441 old_showwarning = self.module.showwarning
442 self.module.showwarning = 23
443 try:
444 self.assertRaises(TypeError, self.module.warn, "Warning!")
445 finally:
446 self.module.showwarning = old_showwarning
Georg Brandl88598222008-05-14 07:18:22 +0000447 self.module.resetwarnings()
Benjamin Petersond2950322008-05-06 22:18:11 +0000448
Brett Cannone9746892008-04-12 23:44:07 +0000449 def test_show_warning_output(self):
450 # With showarning() missing, make sure that output is okay.
451 text = 'test show_warning'
Brett Cannon672237d2008-09-09 00:49:16 +0000452 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000453 self.module.filterwarnings("always", category=UserWarning)
454 del self.module.showwarning
455 with test_support.captured_output('stderr') as stream:
456 warning_tests.inner(text)
457 result = stream.getvalue()
458 self.failUnlessEqual(result.count('\n'), 2,
459 "Too many newlines in %r" % result)
460 first_line, second_line = result.split('\n', 1)
461 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Brett Cannonc4774272008-04-13 17:41:31 +0000462 first_line_parts = first_line.rsplit(':', 3)
Brett Cannon25bb8182008-04-13 17:09:43 +0000463 path, line, warning_class, message = first_line_parts
Brett Cannone9746892008-04-12 23:44:07 +0000464 line = int(line)
465 self.failUnlessEqual(expected_file, path)
466 self.failUnlessEqual(warning_class, ' ' + UserWarning.__name__)
467 self.failUnlessEqual(message, ' ' + text)
468 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
469 assert expected_line
470 self.failUnlessEqual(second_line, expected_line)
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000471
Brett Cannon53ab5b72006-06-22 16:49:14 +0000472
Brett Cannon905c31c2007-12-20 10:09:52 +0000473class WarningsDisplayTests(unittest.TestCase):
474
Brett Cannone9746892008-04-12 23:44:07 +0000475 """Test the displaying of warnings and the ability to overload functions
476 related to displaying warnings."""
477
Brett Cannon905c31c2007-12-20 10:09:52 +0000478 def test_formatwarning(self):
479 message = "msg"
480 category = Warning
481 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
482 line_num = 3
483 file_line = linecache.getline(file_name, line_num).strip()
Brett Cannone9746892008-04-12 23:44:07 +0000484 format = "%s:%s: %s: %s\n %s\n"
485 expect = format % (file_name, line_num, category.__name__, message,
486 file_line)
487 self.failUnlessEqual(expect, self.module.formatwarning(message,
488 category, file_name, line_num))
489 # Test the 'line' argument.
490 file_line += " for the win!"
491 expect = format % (file_name, line_num, category.__name__, message,
492 file_line)
493 self.failUnlessEqual(expect, self.module.formatwarning(message,
494 category, file_name, line_num, file_line))
Brett Cannon905c31c2007-12-20 10:09:52 +0000495
496 def test_showwarning(self):
497 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
498 line_num = 3
499 expected_file_line = linecache.getline(file_name, line_num).strip()
500 message = 'msg'
501 category = Warning
502 file_object = StringIO.StringIO()
Brett Cannone9746892008-04-12 23:44:07 +0000503 expect = self.module.formatwarning(message, category, file_name,
504 line_num)
505 self.module.showwarning(message, category, file_name, line_num,
Brett Cannon905c31c2007-12-20 10:09:52 +0000506 file_object)
507 self.failUnlessEqual(file_object.getvalue(), expect)
Brett Cannone9746892008-04-12 23:44:07 +0000508 # Test 'line' argument.
509 expected_file_line += "for the win!"
510 expect = self.module.formatwarning(message, category, file_name,
511 line_num, expected_file_line)
512 file_object = StringIO.StringIO()
513 self.module.showwarning(message, category, file_name, line_num,
514 file_object, expected_file_line)
515 self.failUnlessEqual(expect, file_object.getvalue())
516
Brett Cannon667bb4f2008-04-13 02:42:36 +0000517class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
Brett Cannone9746892008-04-12 23:44:07 +0000518 module = c_warnings
519
Brett Cannon667bb4f2008-04-13 02:42:36 +0000520class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
Brett Cannone9746892008-04-12 23:44:07 +0000521 module = py_warnings
Brett Cannon905c31c2007-12-20 10:09:52 +0000522
523
Brett Cannon1eaf0742008-09-02 01:25:16 +0000524class CatchWarningTests(BaseTest):
Nick Coghlan38469e22008-07-13 12:23:47 +0000525
Brett Cannon1eaf0742008-09-02 01:25:16 +0000526 """Test catch_warnings()."""
527
528 def test_catch_warnings_restore(self):
Nick Coghlan38469e22008-07-13 12:23:47 +0000529 wmod = self.module
530 orig_filters = wmod.filters
531 orig_showwarning = wmod.showwarning
Nick Coghland2e09382008-09-11 12:11:06 +0000532 # Ensure both showwarning and filters are restored when recording
533 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlan38469e22008-07-13 12:23:47 +0000534 wmod.filters = wmod.showwarning = object()
535 self.assert_(wmod.filters is orig_filters)
536 self.assert_(wmod.showwarning is orig_showwarning)
Nick Coghland2e09382008-09-11 12:11:06 +0000537 # Same test, but with recording disabled
Brett Cannon1eaf0742008-09-02 01:25:16 +0000538 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlan38469e22008-07-13 12:23:47 +0000539 wmod.filters = wmod.showwarning = object()
540 self.assert_(wmod.filters is orig_filters)
541 self.assert_(wmod.showwarning is orig_showwarning)
542
Brett Cannon1eaf0742008-09-02 01:25:16 +0000543 def test_catch_warnings_recording(self):
Nick Coghlan38469e22008-07-13 12:23:47 +0000544 wmod = self.module
Nick Coghland2e09382008-09-11 12:11:06 +0000545 # Ensure warnings are recorded when requested
Brett Cannon1eaf0742008-09-02 01:25:16 +0000546 with wmod.catch_warnings(module=wmod, record=True) as w:
547 self.assertEqual(w, [])
Nick Coghland2e09382008-09-11 12:11:06 +0000548 self.assert_(type(w) is list)
Nick Coghlan38469e22008-07-13 12:23:47 +0000549 wmod.simplefilter("always")
550 wmod.warn("foo")
Brett Cannon672237d2008-09-09 00:49:16 +0000551 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlan38469e22008-07-13 12:23:47 +0000552 wmod.warn("bar")
Brett Cannon672237d2008-09-09 00:49:16 +0000553 self.assertEqual(str(w[-1].message), "bar")
Brett Cannon1eaf0742008-09-02 01:25:16 +0000554 self.assertEqual(str(w[0].message), "foo")
555 self.assertEqual(str(w[1].message), "bar")
Brett Cannon672237d2008-09-09 00:49:16 +0000556 del w[:]
Brett Cannon1eaf0742008-09-02 01:25:16 +0000557 self.assertEqual(w, [])
Nick Coghland2e09382008-09-11 12:11:06 +0000558 # Ensure warnings are not recorded when not requested
Nick Coghlan38469e22008-07-13 12:23:47 +0000559 orig_showwarning = wmod.showwarning
Brett Cannon1eaf0742008-09-02 01:25:16 +0000560 with wmod.catch_warnings(module=wmod, record=False) as w:
Nick Coghlan38469e22008-07-13 12:23:47 +0000561 self.assert_(w is None)
562 self.assert_(wmod.showwarning is orig_showwarning)
563
Nick Coghland2e09382008-09-11 12:11:06 +0000564 def test_catch_warnings_reentry_guard(self):
565 wmod = self.module
566 # Ensure catch_warnings is protected against incorrect usage
567 x = wmod.catch_warnings(module=wmod, record=True)
568 self.assertRaises(RuntimeError, x.__exit__)
569 with x:
570 self.assertRaises(RuntimeError, x.__enter__)
571 # Same test, but with recording disabled
572 x = wmod.catch_warnings(module=wmod, record=False)
573 self.assertRaises(RuntimeError, x.__exit__)
574 with x:
575 self.assertRaises(RuntimeError, x.__enter__)
576
577 def test_catch_warnings_defaults(self):
578 wmod = self.module
579 orig_filters = wmod.filters
580 orig_showwarning = wmod.showwarning
581 # Ensure default behaviour is not to record warnings
582 with wmod.catch_warnings(module=wmod) as w:
583 self.assert_(w is None)
584 self.assert_(wmod.showwarning is orig_showwarning)
585 self.assert_(wmod.filters is not orig_filters)
586 self.assert_(wmod.filters is orig_filters)
587 if wmod is sys.modules['warnings']:
588 # Ensure the default module is this one
589 with wmod.catch_warnings() as w:
590 self.assert_(w is None)
591 self.assert_(wmod.showwarning is orig_showwarning)
592 self.assert_(wmod.filters is not orig_filters)
593 self.assert_(wmod.filters is orig_filters)
594
595 def test_check_warnings(self):
596 # Explicit tests for the test_support convenience wrapper
597 wmod = self.module
598 if wmod is sys.modules['warnings']:
599 with test_support.check_warnings() as w:
600 self.assertEqual(w.warnings, [])
601 wmod.simplefilter("always")
602 wmod.warn("foo")
603 self.assertEqual(str(w.message), "foo")
604 wmod.warn("bar")
605 self.assertEqual(str(w.message), "bar")
606 self.assertEqual(str(w.warnings[0].message), "foo")
607 self.assertEqual(str(w.warnings[1].message), "bar")
608 w.reset()
609 self.assertEqual(w.warnings, [])
610
611
612
Brett Cannon1eaf0742008-09-02 01:25:16 +0000613class CCatchWarningTests(CatchWarningTests):
Nick Coghlan38469e22008-07-13 12:23:47 +0000614 module = c_warnings
615
Brett Cannon1eaf0742008-09-02 01:25:16 +0000616class PyCatchWarningTests(CatchWarningTests):
Nick Coghlan38469e22008-07-13 12:23:47 +0000617 module = py_warnings
618
619
Brett Cannon8a232cc2008-05-05 05:32:07 +0000620class ShowwarningDeprecationTests(BaseTest):
621
622 """Test the deprecation of the old warnings.showwarning() API works."""
623
624 @staticmethod
625 def bad_showwarning(message, category, filename, lineno, file=None):
626 pass
627
Brett Cannon1eaf0742008-09-02 01:25:16 +0000628 @staticmethod
629 def ok_showwarning(*args):
630 pass
631
Brett Cannon8a232cc2008-05-05 05:32:07 +0000632 def test_deprecation(self):
633 # message, category, filename, lineno[, file[, line]]
634 args = ("message", UserWarning, "file name", 42)
Brett Cannon672237d2008-09-09 00:49:16 +0000635 with original_warnings.catch_warnings(module=self.module):
Brett Cannon8a232cc2008-05-05 05:32:07 +0000636 self.module.filterwarnings("error", category=DeprecationWarning)
637 self.module.showwarning = self.bad_showwarning
638 self.assertRaises(DeprecationWarning, self.module.warn_explicit,
639 *args)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000640 self.module.showwarning = self.ok_showwarning
641 try:
642 self.module.warn_explicit(*args)
643 except DeprecationWarning as exc:
644 self.fail('showwarning(*args) should not trigger a '
645 'DeprecationWarning')
Brett Cannon8a232cc2008-05-05 05:32:07 +0000646
647class CShowwarningDeprecationTests(ShowwarningDeprecationTests):
648 module = c_warnings
649
650
651class PyShowwarningDeprecationTests(ShowwarningDeprecationTests):
652 module = py_warnings
653
654
Brett Cannone9746892008-04-12 23:44:07 +0000655def test_main():
Amaury Forgeot d'Arc607bff12008-04-18 23:31:33 +0000656 py_warnings.onceregistry.clear()
657 c_warnings.onceregistry.clear()
Brett Cannon1eaf0742008-09-02 01:25:16 +0000658 test_support.run_unittest(CFilterTests, PyFilterTests,
659 CWarnTests, PyWarnTests,
Brett Cannone9746892008-04-12 23:44:07 +0000660 CWCmdLineTests, PyWCmdLineTests,
661 _WarningsTests,
662 CWarningsDisplayTests, PyWarningsDisplayTests,
Brett Cannon1eaf0742008-09-02 01:25:16 +0000663 CCatchWarningTests, PyCatchWarningTests,
Brett Cannon8a232cc2008-05-05 05:32:07 +0000664 CShowwarningDeprecationTests,
Brett Cannon1eaf0742008-09-02 01:25:16 +0000665 PyShowwarningDeprecationTests,
Brett Cannone9746892008-04-12 23:44:07 +0000666 )
667
668
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000669if __name__ == "__main__":
Brett Cannone9746892008-04-12 23:44:07 +0000670 test_main()