blob: 4b6feb37cb9102c6e86baa5de8be555a75a8c67e [file] [log] [blame]
Christian Heimes33fe8092008-04-13 13:53:33 +00001from contextlib import contextmanager
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00002import linecache
Raymond Hettingerdc9dcf12003-07-13 06:15:11 +00003import os
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00004from io import StringIO
Guido van Rossum61e21b52007-08-20 19:06:03 +00005import sys
Raymond Hettingerd6f6e502003-07-13 08:37:40 +00006import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00007from test import support
Jeremy Hylton85014662003-07-11 15:37:59 +00008
Guido van Rossum805365e2007-05-07 22:24:25 +00009from test import warning_tests
Jeremy Hylton85014662003-07-11 15:37:59 +000010
Christian Heimes33fe8092008-04-13 13:53:33 +000011import warnings as original_warnings
Jeremy Hylton85014662003-07-11 15:37:59 +000012
Christian Heimes33fe8092008-04-13 13:53:33 +000013sys.modules['_warnings'] = 0
14del sys.modules['warnings']
15
16import warnings as py_warnings
17
18del sys.modules['_warnings']
19del sys.modules['warnings']
20
21import warnings as c_warnings
22
23sys.modules['warnings'] = original_warnings
24
25
26@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
47class BaseTest(unittest.TestCase):
48
49 """Basic bookkeeping required for testing."""
50
51 def setUp(self):
52 # 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."""
73
74 def test_error(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000075 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +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 Cannon1cd02472008-09-09 01:52:27 +000082 with original_warnings.catch_warnings(record=True,
83 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000084 self.module.resetwarnings()
85 self.module.filterwarnings("ignore", category=UserWarning)
86 self.module.warn("FilterTests.test_ignore", UserWarning)
Brett Cannonec92e182008-09-02 02:46:59 +000087 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +000088
89 def test_always(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000090 with original_warnings.catch_warnings(record=True,
91 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000092 self.module.resetwarnings()
93 self.module.filterwarnings("always", category=UserWarning)
94 message = "FilterTests.test_always"
95 self.module.warn(message, UserWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +000096 self.assert_(message, w[-1].message)
Christian Heimes33fe8092008-04-13 13:53:33 +000097 self.module.warn(message, UserWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +000098 self.assert_(w[-1].message, message)
Christian Heimes33fe8092008-04-13 13:53:33 +000099
100 def test_default(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000101 with original_warnings.catch_warnings(record=True,
102 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000103 self.module.resetwarnings()
104 self.module.filterwarnings("default", category=UserWarning)
105 message = UserWarning("FilterTests.test_default")
106 for x in range(2):
107 self.module.warn(message, UserWarning)
108 if x == 0:
Brett Cannon1cd02472008-09-09 01:52:27 +0000109 self.assertEquals(w[-1].message, message)
110 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000111 elif x == 1:
Brett Cannon1cd02472008-09-09 01:52:27 +0000112 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000113 else:
114 raise ValueError("loop variant unhandled")
115
116 def test_module(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000117 with original_warnings.catch_warnings(record=True,
118 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000119 self.module.resetwarnings()
120 self.module.filterwarnings("module", category=UserWarning)
121 message = UserWarning("FilterTests.test_module")
122 self.module.warn(message, UserWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +0000123 self.assertEquals(w[-1].message, message)
124 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000125 self.module.warn(message, UserWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +0000126 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000127
128 def test_once(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000129 with original_warnings.catch_warnings(record=True,
130 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +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 Cannon1cd02472008-09-09 01:52:27 +0000136 self.assertEquals(w[-1].message, message)
137 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000138 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
139 13)
Brett Cannonec92e182008-09-02 02:46:59 +0000140 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000141 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
142 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000143 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000144
145 def test_inheritance(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000146 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +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 Cannon1cd02472008-09-09 01:52:27 +0000153 with original_warnings.catch_warnings(record=True,
154 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000155 self.module.resetwarnings()
156 self.module.filterwarnings("ignore", category=UserWarning)
157 self.module.filterwarnings("error", category=UserWarning,
158 append=True)
Brett Cannon1cd02472008-09-09 01:52:27 +0000159 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000160 try:
161 self.module.warn("FilterTests.test_ordering", UserWarning)
162 except UserWarning:
163 self.fail("order handling for actions failed")
Brett Cannonec92e182008-09-02 02:46:59 +0000164 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000165
166 def test_filterwarnings(self):
167 # Test filterwarnings().
168 # Implicitly also tests resetwarnings().
Brett Cannon1cd02472008-09-09 01:52:27 +0000169 with original_warnings.catch_warnings(record=True,
170 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +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 Cannon1cd02472008-09-09 01:52:27 +0000177 self.assertEqual(str(w[-1].message), text)
178 self.assert_(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000179
180 self.module.filterwarnings("ignore", "", Warning, "", 0)
181 text = 'filtered out'
182 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000183 self.assertNotEqual(str(w[-1].message), text)
Christian Heimes33fe8092008-04-13 13:53:33 +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 Cannon1cd02472008-09-09 01:52:27 +0000190 self.assertEqual(str(w[-1].message), text)
191 self.assert_(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000192
193class CFilterTests(BaseTest, FilterTests):
194 module = c_warnings
195
196class PyFilterTests(BaseTest, FilterTests):
197 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 Cannon1cd02472008-09-09 01:52:27 +0000205 with original_warnings.catch_warnings(record=True,
206 module=self.module) as w:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000207 for i in range(4):
Christian Heimes33fe8092008-04-13 13:53:33 +0000208 text = 'multi %d' %i # Different text on each call.
209 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000210 self.assertEqual(str(w[-1].message), text)
211 self.assert_(w[-1].category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000212
Brett Cannon54bd41d2008-09-02 04:01:42 +0000213 # Issue 3639
214 def test_warn_nonstandard_types(self):
215 # warn() should handle non-standard types without issue.
216 for ob in (Warning, None, 42):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000217 with original_warnings.catch_warnings(record=True,
218 module=self.module) as w:
Brett Cannon54bd41d2008-09-02 04:01:42 +0000219 self.module.warn(ob)
220 # Don't directly compare objects since
221 # ``Warning() != Warning()``.
Brett Cannon1cd02472008-09-09 01:52:27 +0000222 self.assertEquals(str(w[-1].message), str(UserWarning(ob)))
Brett Cannon54bd41d2008-09-02 04:01:42 +0000223
Guido van Rossumd8faa362007-04-27 19:54:29 +0000224 def test_filename(self):
Christian Heimes33fe8092008-04-13 13:53:33 +0000225 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000226 with original_warnings.catch_warnings(record=True,
227 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000228 warning_tests.inner("spam1")
Brett Cannon1cd02472008-09-09 01:52:27 +0000229 self.assertEqual(os.path.basename(w[-1].filename),
230 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000231 warning_tests.outer("spam2")
Brett Cannon1cd02472008-09-09 01:52:27 +0000232 self.assertEqual(os.path.basename(w[-1].filename),
233 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000234
235 def test_stacklevel(self):
236 # Test stacklevel argument
237 # make sure all messages are different, so the warning won't be skipped
Christian Heimes33fe8092008-04-13 13:53:33 +0000238 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000239 with original_warnings.catch_warnings(record=True,
240 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000241 warning_tests.inner("spam3", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000242 self.assertEqual(os.path.basename(w[-1].filename),
243 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000244 warning_tests.outer("spam4", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000245 self.assertEqual(os.path.basename(w[-1].filename),
246 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000247
Christian Heimes33fe8092008-04-13 13:53:33 +0000248 warning_tests.inner("spam5", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000249 self.assertEqual(os.path.basename(w[-1].filename),
250 "test_warnings.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000251 warning_tests.outer("spam6", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000252 self.assertEqual(os.path.basename(w[-1].filename),
253 "warning_tests.py")
Christian Heimes5d8da202008-05-06 13:58:24 +0000254 warning_tests.outer("spam6.5", stacklevel=3)
Brett Cannon1cd02472008-09-09 01:52:27 +0000255 self.assertEqual(os.path.basename(w[-1].filename),
256 "test_warnings.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000257
Christian Heimes33fe8092008-04-13 13:53:33 +0000258 warning_tests.inner("spam7", stacklevel=9999)
Brett Cannon1cd02472008-09-09 01:52:27 +0000259 self.assertEqual(os.path.basename(w[-1].filename),
260 "sys")
Christian Heimes33fe8092008-04-13 13:53:33 +0000261
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000262 def test_missing_filename_not_main(self):
263 # If __file__ is not specified and __main__ is not the module name,
264 # then __file__ should be set to the module name.
265 filename = warning_tests.__file__
266 try:
267 del warning_tests.__file__
268 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000269 with original_warnings.catch_warnings(record=True,
270 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000271 warning_tests.inner("spam8", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000272 self.assertEqual(w[-1].filename, warning_tests.__name__)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000273 finally:
274 warning_tests.__file__ = filename
275
276 def test_missing_filename_main_with_argv(self):
277 # If __file__ is not specified and the caller is __main__ and sys.argv
278 # exists, then use sys.argv[0] as the file.
279 if not hasattr(sys, 'argv'):
280 return
281 filename = warning_tests.__file__
282 module_name = warning_tests.__name__
283 try:
284 del warning_tests.__file__
285 warning_tests.__name__ = '__main__'
286 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000287 with original_warnings.catch_warnings(record=True,
288 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000289 warning_tests.inner('spam9', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000290 self.assertEqual(w[-1].filename, sys.argv[0])
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000291 finally:
292 warning_tests.__file__ = filename
293 warning_tests.__name__ = module_name
294
295 def test_missing_filename_main_without_argv(self):
296 # If __file__ is not specified, the caller is __main__, and sys.argv
297 # is not set, then '__main__' is the file name.
298 filename = 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 del sys.argv
305 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000306 with original_warnings.catch_warnings(record=True,
307 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000308 warning_tests.inner('spam10', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000309 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000310 finally:
311 warning_tests.__file__ = filename
312 warning_tests.__name__ = module_name
313 sys.argv = argv
314
Christian Heimesdaaf8ee2008-05-04 23:58:41 +0000315 def test_missing_filename_main_with_argv_empty_string(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000316 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
317 # is the empty string, then '__main__ is the file name.
318 # Tests issue 2743.
319 file_name = warning_tests.__file__
320 module_name = warning_tests.__name__
321 argv = sys.argv
322 try:
323 del warning_tests.__file__
324 warning_tests.__name__ = '__main__'
325 sys.argv = ['']
326 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000327 with original_warnings.catch_warnings(record=True,
328 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000329 warning_tests.inner('spam11', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000330 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000331 finally:
332 warning_tests.__file__ = file_name
333 warning_tests.__name__ = module_name
334 sys.argv = argv
335
Brett Cannondb734912008-06-27 00:52:15 +0000336 def test_warn_explicit_type_errors(self):
337 # warn_explicit() shoud error out gracefully if it is given objects
338 # of the wrong types.
339 # lineno is expected to be an integer.
340 self.assertRaises(TypeError, self.module.warn_explicit,
341 None, UserWarning, None, None)
342 # Either 'message' needs to be an instance of Warning or 'category'
343 # needs to be a subclass.
344 self.assertRaises(TypeError, self.module.warn_explicit,
345 None, None, None, 1)
346 # 'registry' must be a dict or None.
347 self.assertRaises((TypeError, AttributeError),
348 self.module.warn_explicit,
349 None, Warning, None, 1, registry=42)
350
Christian Heimes33fe8092008-04-13 13:53:33 +0000351class CWarnTests(BaseTest, WarnTests):
352 module = c_warnings
353
354class PyWarnTests(BaseTest, WarnTests):
355 module = py_warnings
356
357
358class WCmdLineTests(unittest.TestCase):
359
360 def test_improper_input(self):
361 # Uses the private _setoption() function to test the parsing
362 # of command-line warning arguments
Brett Cannon1cd02472008-09-09 01:52:27 +0000363 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000364 self.assertRaises(self.module._OptionError,
365 self.module._setoption, '1:2:3:4:5:6')
366 self.assertRaises(self.module._OptionError,
367 self.module._setoption, 'bogus::Warning')
368 self.assertRaises(self.module._OptionError,
369 self.module._setoption, 'ignore:2::4:-5')
370 self.module._setoption('error::Warning::0')
371 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
372
373class CWCmdLineTests(BaseTest, WCmdLineTests):
374 module = c_warnings
375
376class PyWCmdLineTests(BaseTest, WCmdLineTests):
377 module = py_warnings
378
379
380class _WarningsTests(BaseTest):
381
382 """Tests specific to the _warnings module."""
383
384 module = c_warnings
385
386 def test_filter(self):
387 # Everything should function even if 'filters' is not in warnings.
Brett Cannon1cd02472008-09-09 01:52:27 +0000388 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000389 self.module.filterwarnings("error", "", Warning, "", 0)
390 self.assertRaises(UserWarning, self.module.warn,
391 'convert to error')
392 del self.module.filters
393 self.assertRaises(UserWarning, self.module.warn,
394 'convert to error')
395
396 def test_onceregistry(self):
397 # Replacing or removing the onceregistry should be okay.
398 global __warningregistry__
399 message = UserWarning('onceregistry test')
400 try:
401 original_registry = self.module.onceregistry
402 __warningregistry__ = {}
Brett Cannon1cd02472008-09-09 01:52:27 +0000403 with original_warnings.catch_warnings(record=True,
404 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000405 self.module.resetwarnings()
406 self.module.filterwarnings("once", category=UserWarning)
407 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannon1cd02472008-09-09 01:52:27 +0000408 self.failUnlessEqual(w[-1].message, message)
409 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000410 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000411 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000412 # Test the resetting of onceregistry.
413 self.module.onceregistry = {}
414 __warningregistry__ = {}
415 self.module.warn('onceregistry test')
Brett Cannon1cd02472008-09-09 01:52:27 +0000416 self.failUnlessEqual(w[-1].message.args, message.args)
Christian Heimes33fe8092008-04-13 13:53:33 +0000417 # Removal of onceregistry is okay.
Brett Cannon1cd02472008-09-09 01:52:27 +0000418 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000419 del self.module.onceregistry
420 __warningregistry__ = {}
421 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000422 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000423 finally:
424 self.module.onceregistry = original_registry
425
426 def test_showwarning_missing(self):
427 # Test that showwarning() missing is okay.
428 text = 'del showwarning test'
Brett Cannon1cd02472008-09-09 01:52:27 +0000429 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000430 self.module.filterwarnings("always", category=UserWarning)
431 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000432 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000433 self.module.warn(text)
434 result = stream.getvalue()
435 self.failUnless(text in result)
436
Christian Heimes8dc226f2008-05-06 23:45:46 +0000437 def test_showwarning_not_callable(self):
438 self.module.filterwarnings("always", category=UserWarning)
439 old_showwarning = self.module.showwarning
440 self.module.showwarning = 23
441 try:
442 self.assertRaises(TypeError, self.module.warn, "Warning!")
443 finally:
444 self.module.showwarning = old_showwarning
Alexandre Vassalottie9f305f2008-05-16 04:39:54 +0000445 self.module.resetwarnings()
Christian Heimes8dc226f2008-05-06 23:45:46 +0000446
Christian Heimes33fe8092008-04-13 13:53:33 +0000447 def test_show_warning_output(self):
448 # With showarning() missing, make sure that output is okay.
449 text = 'test show_warning'
Brett Cannon1cd02472008-09-09 01:52:27 +0000450 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000451 self.module.filterwarnings("always", category=UserWarning)
452 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000453 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000454 warning_tests.inner(text)
455 result = stream.getvalue()
456 self.failUnlessEqual(result.count('\n'), 2,
457 "Too many newlines in %r" % result)
458 first_line, second_line = result.split('\n', 1)
459 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Neal Norwitz32dde222008-04-15 06:43:13 +0000460 first_line_parts = first_line.rsplit(':', 3)
461 path, line, warning_class, message = first_line_parts
Christian Heimes33fe8092008-04-13 13:53:33 +0000462 line = int(line)
463 self.failUnlessEqual(expected_file, path)
464 self.failUnlessEqual(warning_class, ' ' + UserWarning.__name__)
465 self.failUnlessEqual(message, ' ' + text)
466 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
467 assert expected_line
468 self.failUnlessEqual(second_line, expected_line)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000469
470
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000471class WarningsDisplayTests(unittest.TestCase):
472
Christian Heimes33fe8092008-04-13 13:53:33 +0000473 """Test the displaying of warnings and the ability to overload functions
474 related to displaying warnings."""
475
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000476 def test_formatwarning(self):
477 message = "msg"
478 category = Warning
479 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
480 line_num = 3
481 file_line = linecache.getline(file_name, line_num).strip()
Christian Heimes33fe8092008-04-13 13:53:33 +0000482 format = "%s:%s: %s: %s\n %s\n"
483 expect = format % (file_name, line_num, category.__name__, message,
484 file_line)
485 self.failUnlessEqual(expect, self.module.formatwarning(message,
486 category, file_name, line_num))
487 # Test the 'line' argument.
488 file_line += " for the win!"
489 expect = format % (file_name, line_num, category.__name__, message,
490 file_line)
491 self.failUnlessEqual(expect, self.module.formatwarning(message,
492 category, file_name, line_num, file_line))
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000493
494 def test_showwarning(self):
495 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
496 line_num = 3
497 expected_file_line = linecache.getline(file_name, line_num).strip()
498 message = 'msg'
499 category = Warning
500 file_object = StringIO()
Christian Heimes33fe8092008-04-13 13:53:33 +0000501 expect = self.module.formatwarning(message, category, file_name,
502 line_num)
503 self.module.showwarning(message, category, file_name, line_num,
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000504 file_object)
505 self.failUnlessEqual(file_object.getvalue(), expect)
Christian Heimes33fe8092008-04-13 13:53:33 +0000506 # Test 'line' argument.
507 expected_file_line += "for the win!"
508 expect = self.module.formatwarning(message, category, file_name,
509 line_num, expected_file_line)
510 file_object = StringIO()
511 self.module.showwarning(message, category, file_name, line_num,
512 file_object, expected_file_line)
513 self.failUnlessEqual(expect, file_object.getvalue())
514
515class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
516 module = c_warnings
517
518class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
519 module = py_warnings
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000520
Brett Cannon1cd02472008-09-09 01:52:27 +0000521
Brett Cannonec92e182008-09-02 02:46:59 +0000522class CatchWarningTests(BaseTest):
Nick Coghlanb1304932008-07-13 12:25:08 +0000523
Brett Cannonec92e182008-09-02 02:46:59 +0000524 """Test catch_warnings()."""
525
526 def test_catch_warnings_restore(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000527 wmod = self.module
528 orig_filters = wmod.filters
529 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000530 # Ensure both showwarning and filters are restored when recording
531 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlanb1304932008-07-13 12:25:08 +0000532 wmod.filters = wmod.showwarning = object()
533 self.assert_(wmod.filters is orig_filters)
534 self.assert_(wmod.showwarning is orig_showwarning)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000535 # Same test, but with recording disabled
536 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlanb1304932008-07-13 12:25:08 +0000537 wmod.filters = wmod.showwarning = object()
538 self.assert_(wmod.filters is orig_filters)
539 self.assert_(wmod.showwarning is orig_showwarning)
540
Brett Cannonec92e182008-09-02 02:46:59 +0000541 def test_catch_warnings_recording(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000542 wmod = self.module
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000543 # Ensure warnings are recorded when requested
544 with wmod.catch_warnings(module=wmod, record=True) as w:
Brett Cannonec92e182008-09-02 02:46:59 +0000545 self.assertEqual(w, [])
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000546 self.assert_(type(w) is list)
Nick Coghlanb1304932008-07-13 12:25:08 +0000547 wmod.simplefilter("always")
548 wmod.warn("foo")
Brett Cannon1cd02472008-09-09 01:52:27 +0000549 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlanb1304932008-07-13 12:25:08 +0000550 wmod.warn("bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000551 self.assertEqual(str(w[-1].message), "bar")
Brett Cannonec92e182008-09-02 02:46:59 +0000552 self.assertEqual(str(w[0].message), "foo")
553 self.assertEqual(str(w[1].message), "bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000554 del w[:]
Brett Cannonec92e182008-09-02 02:46:59 +0000555 self.assertEqual(w, [])
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000556 # Ensure warnings are not recorded when not requested
Nick Coghlanb1304932008-07-13 12:25:08 +0000557 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000558 with wmod.catch_warnings(module=wmod, record=False) as w:
Nick Coghlanb1304932008-07-13 12:25:08 +0000559 self.assert_(w is None)
560 self.assert_(wmod.showwarning is orig_showwarning)
561
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000562 def test_catch_warnings_reentry_guard(self):
563 wmod = self.module
564 # Ensure catch_warnings is protected against incorrect usage
565 x = wmod.catch_warnings(module=wmod, record=True)
566 self.assertRaises(RuntimeError, x.__exit__)
567 with x:
568 self.assertRaises(RuntimeError, x.__enter__)
569 # Same test, but with recording disabled
570 x = wmod.catch_warnings(module=wmod, record=False)
571 self.assertRaises(RuntimeError, x.__exit__)
572 with x:
573 self.assertRaises(RuntimeError, x.__enter__)
574
575 def test_catch_warnings_defaults(self):
576 wmod = self.module
577 orig_filters = wmod.filters
578 orig_showwarning = wmod.showwarning
579 # Ensure default behaviour is not to record warnings
580 with wmod.catch_warnings(module=wmod) as w:
581 self.assert_(w is None)
582 self.assert_(wmod.showwarning is orig_showwarning)
583 self.assert_(wmod.filters is not orig_filters)
584 self.assert_(wmod.filters is orig_filters)
585 if wmod is sys.modules['warnings']:
586 # Ensure the default module is this one
587 with wmod.catch_warnings() as w:
588 self.assert_(w is None)
589 self.assert_(wmod.showwarning is orig_showwarning)
590 self.assert_(wmod.filters is not orig_filters)
591 self.assert_(wmod.filters is orig_filters)
592
593 def test_check_warnings(self):
594 # Explicit tests for the test.support convenience wrapper
595 wmod = self.module
596 if wmod is sys.modules['warnings']:
597 with support.check_warnings() as w:
598 self.assertEqual(w.warnings, [])
599 wmod.simplefilter("always")
600 wmod.warn("foo")
601 self.assertEqual(str(w.message), "foo")
602 wmod.warn("bar")
603 self.assertEqual(str(w.message), "bar")
604 self.assertEqual(str(w.warnings[0].message), "foo")
605 self.assertEqual(str(w.warnings[1].message), "bar")
606 w.reset()
607 self.assertEqual(w.warnings, [])
608
Brett Cannonec92e182008-09-02 02:46:59 +0000609class CCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000610 module = c_warnings
611
Brett Cannonec92e182008-09-02 02:46:59 +0000612class PyCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000613 module = py_warnings
614
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000615
Christian Heimes33fe8092008-04-13 13:53:33 +0000616def test_main():
Christian Heimesdae2a892008-04-19 00:55:37 +0000617 py_warnings.onceregistry.clear()
618 c_warnings.onceregistry.clear()
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000619 support.run_unittest(CFilterTests,
Christian Heimes33fe8092008-04-13 13:53:33 +0000620 PyFilterTests,
621 CWarnTests,
622 PyWarnTests,
623 CWCmdLineTests, PyWCmdLineTests,
624 _WarningsTests,
625 CWarningsDisplayTests, PyWarningsDisplayTests,
Brett Cannonec92e182008-09-02 02:46:59 +0000626 CCatchWarningTests, PyCatchWarningTests,
Christian Heimes33fe8092008-04-13 13:53:33 +0000627 )
628
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000629
630if __name__ == "__main__":
Christian Heimes33fe8092008-04-13 13:53:33 +0000631 test_main()