blob: 1f5d05fb8a110263d9028ae85efb6513cff183b6 [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
350 with self.assertRaises(ValueError):
351 self.module.warn(BadStrWarning())
352
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000353
Brett Cannon667bb4f2008-04-13 02:42:36 +0000354class CWarnTests(BaseTest, WarnTests):
Brett Cannone9746892008-04-12 23:44:07 +0000355 module = c_warnings
356
Brett Cannon667bb4f2008-04-13 02:42:36 +0000357class PyWarnTests(BaseTest, WarnTests):
Brett Cannone9746892008-04-12 23:44:07 +0000358 module = py_warnings
359
360
361class WCmdLineTests(unittest.TestCase):
362
363 def test_improper_input(self):
364 # Uses the private _setoption() function to test the parsing
365 # of command-line warning arguments
Brett Cannon672237d2008-09-09 00:49:16 +0000366 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000367 self.assertRaises(self.module._OptionError,
368 self.module._setoption, '1:2:3:4:5:6')
369 self.assertRaises(self.module._OptionError,
370 self.module._setoption, 'bogus::Warning')
371 self.assertRaises(self.module._OptionError,
372 self.module._setoption, 'ignore:2::4:-5')
373 self.module._setoption('error::Warning::0')
374 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
375
Brett Cannon667bb4f2008-04-13 02:42:36 +0000376class CWCmdLineTests(BaseTest, WCmdLineTests):
Brett Cannone9746892008-04-12 23:44:07 +0000377 module = c_warnings
378
Brett Cannon667bb4f2008-04-13 02:42:36 +0000379class PyWCmdLineTests(BaseTest, WCmdLineTests):
Brett Cannone9746892008-04-12 23:44:07 +0000380 module = py_warnings
381
382
Brett Cannon667bb4f2008-04-13 02:42:36 +0000383class _WarningsTests(BaseTest):
Brett Cannone9746892008-04-12 23:44:07 +0000384
385 """Tests specific to the _warnings module."""
386
387 module = c_warnings
388
389 def test_filter(self):
390 # Everything should function even if 'filters' is not in warnings.
Brett Cannon672237d2008-09-09 00:49:16 +0000391 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000392 self.module.filterwarnings("error", "", Warning, "", 0)
393 self.assertRaises(UserWarning, self.module.warn,
394 'convert to error')
395 del self.module.filters
396 self.assertRaises(UserWarning, self.module.warn,
397 'convert to error')
398
399 def test_onceregistry(self):
400 # Replacing or removing the onceregistry should be okay.
401 global __warningregistry__
402 message = UserWarning('onceregistry test')
403 try:
404 original_registry = self.module.onceregistry
405 __warningregistry__ = {}
Brett Cannon672237d2008-09-09 00:49:16 +0000406 with original_warnings.catch_warnings(record=True,
407 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000408 self.module.resetwarnings()
409 self.module.filterwarnings("once", category=UserWarning)
410 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannon672237d2008-09-09 00:49:16 +0000411 self.failUnlessEqual(w[-1].message, message)
412 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000413 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000414 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000415 # Test the resetting of onceregistry.
416 self.module.onceregistry = {}
417 __warningregistry__ = {}
418 self.module.warn('onceregistry test')
Brett Cannon672237d2008-09-09 00:49:16 +0000419 self.failUnlessEqual(w[-1].message.args, message.args)
Brett Cannone9746892008-04-12 23:44:07 +0000420 # Removal of onceregistry is okay.
Brett Cannon672237d2008-09-09 00:49:16 +0000421 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000422 del self.module.onceregistry
423 __warningregistry__ = {}
424 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000425 self.assertEquals(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000426 finally:
427 self.module.onceregistry = original_registry
428
429 def test_showwarning_missing(self):
430 # Test that showwarning() missing is okay.
431 text = 'del showwarning test'
Brett Cannon672237d2008-09-09 00:49:16 +0000432 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000433 self.module.filterwarnings("always", category=UserWarning)
434 del self.module.showwarning
435 with test_support.captured_output('stderr') as stream:
436 self.module.warn(text)
437 result = stream.getvalue()
438 self.failUnless(text in result)
439
Benjamin Petersond2950322008-05-06 22:18:11 +0000440 def test_showwarning_not_callable(self):
441 self.module.filterwarnings("always", category=UserWarning)
442 old_showwarning = self.module.showwarning
443 self.module.showwarning = 23
444 try:
445 self.assertRaises(TypeError, self.module.warn, "Warning!")
446 finally:
447 self.module.showwarning = old_showwarning
Georg Brandl88598222008-05-14 07:18:22 +0000448 self.module.resetwarnings()
Benjamin Petersond2950322008-05-06 22:18:11 +0000449
Brett Cannone9746892008-04-12 23:44:07 +0000450 def test_show_warning_output(self):
451 # With showarning() missing, make sure that output is okay.
452 text = 'test show_warning'
Brett Cannon672237d2008-09-09 00:49:16 +0000453 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000454 self.module.filterwarnings("always", category=UserWarning)
455 del self.module.showwarning
456 with test_support.captured_output('stderr') as stream:
457 warning_tests.inner(text)
458 result = stream.getvalue()
459 self.failUnlessEqual(result.count('\n'), 2,
460 "Too many newlines in %r" % result)
461 first_line, second_line = result.split('\n', 1)
462 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Brett Cannonc4774272008-04-13 17:41:31 +0000463 first_line_parts = first_line.rsplit(':', 3)
Brett Cannon25bb8182008-04-13 17:09:43 +0000464 path, line, warning_class, message = first_line_parts
Brett Cannone9746892008-04-12 23:44:07 +0000465 line = int(line)
466 self.failUnlessEqual(expected_file, path)
467 self.failUnlessEqual(warning_class, ' ' + UserWarning.__name__)
468 self.failUnlessEqual(message, ' ' + text)
469 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
470 assert expected_line
471 self.failUnlessEqual(second_line, expected_line)
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000472
Brett Cannon53ab5b72006-06-22 16:49:14 +0000473
Brett Cannon905c31c2007-12-20 10:09:52 +0000474class WarningsDisplayTests(unittest.TestCase):
475
Brett Cannone9746892008-04-12 23:44:07 +0000476 """Test the displaying of warnings and the ability to overload functions
477 related to displaying warnings."""
478
Brett Cannon905c31c2007-12-20 10:09:52 +0000479 def test_formatwarning(self):
480 message = "msg"
481 category = Warning
482 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
483 line_num = 3
484 file_line = linecache.getline(file_name, line_num).strip()
Brett Cannone9746892008-04-12 23:44:07 +0000485 format = "%s:%s: %s: %s\n %s\n"
486 expect = format % (file_name, line_num, category.__name__, message,
487 file_line)
488 self.failUnlessEqual(expect, self.module.formatwarning(message,
489 category, file_name, line_num))
490 # Test the 'line' argument.
491 file_line += " for the win!"
492 expect = format % (file_name, line_num, category.__name__, message,
493 file_line)
494 self.failUnlessEqual(expect, self.module.formatwarning(message,
495 category, file_name, line_num, file_line))
Brett Cannon905c31c2007-12-20 10:09:52 +0000496
497 def test_showwarning(self):
498 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
499 line_num = 3
500 expected_file_line = linecache.getline(file_name, line_num).strip()
501 message = 'msg'
502 category = Warning
503 file_object = StringIO.StringIO()
Brett Cannone9746892008-04-12 23:44:07 +0000504 expect = self.module.formatwarning(message, category, file_name,
505 line_num)
506 self.module.showwarning(message, category, file_name, line_num,
Brett Cannon905c31c2007-12-20 10:09:52 +0000507 file_object)
508 self.failUnlessEqual(file_object.getvalue(), expect)
Brett Cannone9746892008-04-12 23:44:07 +0000509 # Test 'line' argument.
510 expected_file_line += "for the win!"
511 expect = self.module.formatwarning(message, category, file_name,
512 line_num, expected_file_line)
513 file_object = StringIO.StringIO()
514 self.module.showwarning(message, category, file_name, line_num,
515 file_object, expected_file_line)
516 self.failUnlessEqual(expect, file_object.getvalue())
517
Brett Cannon667bb4f2008-04-13 02:42:36 +0000518class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
Brett Cannone9746892008-04-12 23:44:07 +0000519 module = c_warnings
520
Brett Cannon667bb4f2008-04-13 02:42:36 +0000521class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
Brett Cannone9746892008-04-12 23:44:07 +0000522 module = py_warnings
Brett Cannon905c31c2007-12-20 10:09:52 +0000523
524
Brett Cannon1eaf0742008-09-02 01:25:16 +0000525class CatchWarningTests(BaseTest):
Nick Coghlan38469e22008-07-13 12:23:47 +0000526
Brett Cannon1eaf0742008-09-02 01:25:16 +0000527 """Test catch_warnings()."""
528
529 def test_catch_warnings_restore(self):
Nick Coghlan38469e22008-07-13 12:23:47 +0000530 wmod = self.module
531 orig_filters = wmod.filters
532 orig_showwarning = wmod.showwarning
Nick Coghland2e09382008-09-11 12:11:06 +0000533 # Ensure both showwarning and filters are restored when recording
534 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlan38469e22008-07-13 12:23:47 +0000535 wmod.filters = wmod.showwarning = object()
536 self.assert_(wmod.filters is orig_filters)
537 self.assert_(wmod.showwarning is orig_showwarning)
Nick Coghland2e09382008-09-11 12:11:06 +0000538 # Same test, but with recording disabled
Brett Cannon1eaf0742008-09-02 01:25:16 +0000539 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlan38469e22008-07-13 12:23:47 +0000540 wmod.filters = wmod.showwarning = object()
541 self.assert_(wmod.filters is orig_filters)
542 self.assert_(wmod.showwarning is orig_showwarning)
543
Brett Cannon1eaf0742008-09-02 01:25:16 +0000544 def test_catch_warnings_recording(self):
Nick Coghlan38469e22008-07-13 12:23:47 +0000545 wmod = self.module
Nick Coghland2e09382008-09-11 12:11:06 +0000546 # Ensure warnings are recorded when requested
Brett Cannon1eaf0742008-09-02 01:25:16 +0000547 with wmod.catch_warnings(module=wmod, record=True) as w:
548 self.assertEqual(w, [])
Nick Coghland2e09382008-09-11 12:11:06 +0000549 self.assert_(type(w) is list)
Nick Coghlan38469e22008-07-13 12:23:47 +0000550 wmod.simplefilter("always")
551 wmod.warn("foo")
Brett Cannon672237d2008-09-09 00:49:16 +0000552 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlan38469e22008-07-13 12:23:47 +0000553 wmod.warn("bar")
Brett Cannon672237d2008-09-09 00:49:16 +0000554 self.assertEqual(str(w[-1].message), "bar")
Brett Cannon1eaf0742008-09-02 01:25:16 +0000555 self.assertEqual(str(w[0].message), "foo")
556 self.assertEqual(str(w[1].message), "bar")
Brett Cannon672237d2008-09-09 00:49:16 +0000557 del w[:]
Brett Cannon1eaf0742008-09-02 01:25:16 +0000558 self.assertEqual(w, [])
Nick Coghland2e09382008-09-11 12:11:06 +0000559 # Ensure warnings are not recorded when not requested
Nick Coghlan38469e22008-07-13 12:23:47 +0000560 orig_showwarning = wmod.showwarning
Brett Cannon1eaf0742008-09-02 01:25:16 +0000561 with wmod.catch_warnings(module=wmod, record=False) as w:
Nick Coghlan38469e22008-07-13 12:23:47 +0000562 self.assert_(w is None)
563 self.assert_(wmod.showwarning is orig_showwarning)
564
Nick Coghland2e09382008-09-11 12:11:06 +0000565 def test_catch_warnings_reentry_guard(self):
566 wmod = self.module
567 # Ensure catch_warnings is protected against incorrect usage
568 x = wmod.catch_warnings(module=wmod, record=True)
569 self.assertRaises(RuntimeError, x.__exit__)
570 with x:
571 self.assertRaises(RuntimeError, x.__enter__)
572 # Same test, but with recording disabled
573 x = wmod.catch_warnings(module=wmod, record=False)
574 self.assertRaises(RuntimeError, x.__exit__)
575 with x:
576 self.assertRaises(RuntimeError, x.__enter__)
577
578 def test_catch_warnings_defaults(self):
579 wmod = self.module
580 orig_filters = wmod.filters
581 orig_showwarning = wmod.showwarning
582 # Ensure default behaviour is not to record warnings
583 with wmod.catch_warnings(module=wmod) as w:
584 self.assert_(w is None)
585 self.assert_(wmod.showwarning is orig_showwarning)
586 self.assert_(wmod.filters is not orig_filters)
587 self.assert_(wmod.filters is orig_filters)
588 if wmod is sys.modules['warnings']:
589 # Ensure the default module is this one
590 with wmod.catch_warnings() as w:
591 self.assert_(w is None)
592 self.assert_(wmod.showwarning is orig_showwarning)
593 self.assert_(wmod.filters is not orig_filters)
594 self.assert_(wmod.filters is orig_filters)
595
596 def test_check_warnings(self):
597 # Explicit tests for the test_support convenience wrapper
598 wmod = self.module
599 if wmod is sys.modules['warnings']:
600 with test_support.check_warnings() as w:
601 self.assertEqual(w.warnings, [])
602 wmod.simplefilter("always")
603 wmod.warn("foo")
604 self.assertEqual(str(w.message), "foo")
605 wmod.warn("bar")
606 self.assertEqual(str(w.message), "bar")
607 self.assertEqual(str(w.warnings[0].message), "foo")
608 self.assertEqual(str(w.warnings[1].message), "bar")
609 w.reset()
610 self.assertEqual(w.warnings, [])
611
612
613
Brett Cannon1eaf0742008-09-02 01:25:16 +0000614class CCatchWarningTests(CatchWarningTests):
Nick Coghlan38469e22008-07-13 12:23:47 +0000615 module = c_warnings
616
Brett Cannon1eaf0742008-09-02 01:25:16 +0000617class PyCatchWarningTests(CatchWarningTests):
Nick Coghlan38469e22008-07-13 12:23:47 +0000618 module = py_warnings
619
620
Brett Cannon8a232cc2008-05-05 05:32:07 +0000621class ShowwarningDeprecationTests(BaseTest):
622
623 """Test the deprecation of the old warnings.showwarning() API works."""
624
625 @staticmethod
626 def bad_showwarning(message, category, filename, lineno, file=None):
627 pass
628
Brett Cannon1eaf0742008-09-02 01:25:16 +0000629 @staticmethod
630 def ok_showwarning(*args):
631 pass
632
Brett Cannon8a232cc2008-05-05 05:32:07 +0000633 def test_deprecation(self):
634 # message, category, filename, lineno[, file[, line]]
635 args = ("message", UserWarning, "file name", 42)
Brett Cannon672237d2008-09-09 00:49:16 +0000636 with original_warnings.catch_warnings(module=self.module):
Brett Cannon8a232cc2008-05-05 05:32:07 +0000637 self.module.filterwarnings("error", category=DeprecationWarning)
638 self.module.showwarning = self.bad_showwarning
639 self.assertRaises(DeprecationWarning, self.module.warn_explicit,
640 *args)
Brett Cannon1eaf0742008-09-02 01:25:16 +0000641 self.module.showwarning = self.ok_showwarning
642 try:
643 self.module.warn_explicit(*args)
644 except DeprecationWarning as exc:
645 self.fail('showwarning(*args) should not trigger a '
646 'DeprecationWarning')
Brett Cannon8a232cc2008-05-05 05:32:07 +0000647
648class CShowwarningDeprecationTests(ShowwarningDeprecationTests):
649 module = c_warnings
650
651
652class PyShowwarningDeprecationTests(ShowwarningDeprecationTests):
653 module = py_warnings
654
655
Brett Cannone9746892008-04-12 23:44:07 +0000656def test_main():
Amaury Forgeot d'Arc607bff12008-04-18 23:31:33 +0000657 py_warnings.onceregistry.clear()
658 c_warnings.onceregistry.clear()
Brett Cannon1eaf0742008-09-02 01:25:16 +0000659 test_support.run_unittest(CFilterTests, PyFilterTests,
660 CWarnTests, PyWarnTests,
Brett Cannone9746892008-04-12 23:44:07 +0000661 CWCmdLineTests, PyWCmdLineTests,
662 _WarningsTests,
663 CWarningsDisplayTests, PyWarningsDisplayTests,
Brett Cannon1eaf0742008-09-02 01:25:16 +0000664 CCatchWarningTests, PyCatchWarningTests,
Brett Cannon8a232cc2008-05-05 05:32:07 +0000665 CShowwarningDeprecationTests,
Brett Cannon1eaf0742008-09-02 01:25:16 +0000666 PyShowwarningDeprecationTests,
Brett Cannone9746892008-04-12 23:44:07 +0000667 )
668
669
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000670if __name__ == "__main__":
Brett Cannone9746892008-04-12 23:44:07 +0000671 test_main()