blob: 4bcc210f989fe5b8f9c6fee35b5b2fe5641f6b13 [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
Nick Coghlan47384702009-04-22 16:13:36 +000013py_warnings = support.import_fresh_module('warnings', blocked=['_warnings'])
14c_warnings = support.import_fresh_module('warnings', fresh=['_warnings'])
Christian Heimes33fe8092008-04-13 13:53:33 +000015
16@contextmanager
17def warnings_state(module):
18 """Use a specific warnings implementation in warning_tests."""
19 global __warningregistry__
20 for to_clear in (sys, warning_tests):
21 try:
22 to_clear.__warningregistry__.clear()
23 except AttributeError:
24 pass
25 try:
26 __warningregistry__.clear()
27 except NameError:
28 pass
29 original_warnings = warning_tests.warnings
30 try:
31 warning_tests.warnings = module
32 yield
33 finally:
34 warning_tests.warnings = original_warnings
35
36
37class BaseTest(unittest.TestCase):
38
39 """Basic bookkeeping required for testing."""
40
41 def setUp(self):
42 # The __warningregistry__ needs to be in a pristine state for tests
43 # to work properly.
44 if '__warningregistry__' in globals():
45 del globals()['__warningregistry__']
46 if hasattr(warning_tests, '__warningregistry__'):
47 del warning_tests.__warningregistry__
48 if hasattr(sys, '__warningregistry__'):
49 del sys.__warningregistry__
50 # The 'warnings' module must be explicitly set so that the proper
51 # interaction between _warnings and 'warnings' can be controlled.
52 sys.modules['warnings'] = self.module
53 super(BaseTest, self).setUp()
54
55 def tearDown(self):
56 sys.modules['warnings'] = original_warnings
57 super(BaseTest, self).tearDown()
58
59
60class FilterTests(object):
61
62 """Testing the filtering functionality."""
63
64 def test_error(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000065 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000066 self.module.resetwarnings()
67 self.module.filterwarnings("error", category=UserWarning)
68 self.assertRaises(UserWarning, self.module.warn,
69 "FilterTests.test_error")
70
71 def test_ignore(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000072 with original_warnings.catch_warnings(record=True,
73 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000074 self.module.resetwarnings()
75 self.module.filterwarnings("ignore", category=UserWarning)
76 self.module.warn("FilterTests.test_ignore", UserWarning)
Brett Cannonec92e182008-09-02 02:46:59 +000077 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +000078
79 def test_always(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000080 with original_warnings.catch_warnings(record=True,
81 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000082 self.module.resetwarnings()
83 self.module.filterwarnings("always", category=UserWarning)
84 message = "FilterTests.test_always"
85 self.module.warn(message, UserWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +000086 self.assert_(message, w[-1].message)
Christian Heimes33fe8092008-04-13 13:53:33 +000087 self.module.warn(message, UserWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +000088 self.assert_(w[-1].message, message)
Christian Heimes33fe8092008-04-13 13:53:33 +000089
90 def test_default(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000091 with original_warnings.catch_warnings(record=True,
92 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000093 self.module.resetwarnings()
94 self.module.filterwarnings("default", category=UserWarning)
95 message = UserWarning("FilterTests.test_default")
96 for x in range(2):
97 self.module.warn(message, UserWarning)
98 if x == 0:
Brett Cannon1cd02472008-09-09 01:52:27 +000099 self.assertEquals(w[-1].message, message)
100 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000101 elif x == 1:
Brett Cannon1cd02472008-09-09 01:52:27 +0000102 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000103 else:
104 raise ValueError("loop variant unhandled")
105
106 def test_module(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000107 with original_warnings.catch_warnings(record=True,
108 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000109 self.module.resetwarnings()
110 self.module.filterwarnings("module", category=UserWarning)
111 message = UserWarning("FilterTests.test_module")
112 self.module.warn(message, UserWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +0000113 self.assertEquals(w[-1].message, message)
114 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000115 self.module.warn(message, UserWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +0000116 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000117
118 def test_once(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000119 with original_warnings.catch_warnings(record=True,
120 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000121 self.module.resetwarnings()
122 self.module.filterwarnings("once", category=UserWarning)
123 message = UserWarning("FilterTests.test_once")
124 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
125 42)
Brett Cannon1cd02472008-09-09 01:52:27 +0000126 self.assertEquals(w[-1].message, message)
127 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000128 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
129 13)
Brett Cannonec92e182008-09-02 02:46:59 +0000130 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000131 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
132 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000133 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000134
135 def test_inheritance(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000136 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000137 self.module.resetwarnings()
138 self.module.filterwarnings("error", category=Warning)
139 self.assertRaises(UserWarning, self.module.warn,
140 "FilterTests.test_inheritance", UserWarning)
141
142 def test_ordering(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000143 with original_warnings.catch_warnings(record=True,
144 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000145 self.module.resetwarnings()
146 self.module.filterwarnings("ignore", category=UserWarning)
147 self.module.filterwarnings("error", category=UserWarning,
148 append=True)
Brett Cannon1cd02472008-09-09 01:52:27 +0000149 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000150 try:
151 self.module.warn("FilterTests.test_ordering", UserWarning)
152 except UserWarning:
153 self.fail("order handling for actions failed")
Brett Cannonec92e182008-09-02 02:46:59 +0000154 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000155
156 def test_filterwarnings(self):
157 # Test filterwarnings().
158 # Implicitly also tests resetwarnings().
Brett Cannon1cd02472008-09-09 01:52:27 +0000159 with original_warnings.catch_warnings(record=True,
160 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000161 self.module.filterwarnings("error", "", Warning, "", 0)
162 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
163
164 self.module.resetwarnings()
165 text = 'handle normally'
166 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000167 self.assertEqual(str(w[-1].message), text)
168 self.assert_(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000169
170 self.module.filterwarnings("ignore", "", Warning, "", 0)
171 text = 'filtered out'
172 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000173 self.assertNotEqual(str(w[-1].message), text)
Christian Heimes33fe8092008-04-13 13:53:33 +0000174
175 self.module.resetwarnings()
176 self.module.filterwarnings("error", "hex*", Warning, "", 0)
177 self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
178 text = 'nonmatching text'
179 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000180 self.assertEqual(str(w[-1].message), text)
181 self.assert_(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000182
183class CFilterTests(BaseTest, FilterTests):
184 module = c_warnings
185
186class PyFilterTests(BaseTest, FilterTests):
187 module = py_warnings
188
189
190class WarnTests(unittest.TestCase):
191
192 """Test warnings.warn() and warnings.warn_explicit()."""
193
194 def test_message(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000195 with original_warnings.catch_warnings(record=True,
196 module=self.module) as w:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000197 for i in range(4):
Christian Heimes33fe8092008-04-13 13:53:33 +0000198 text = 'multi %d' %i # Different text on each call.
199 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000200 self.assertEqual(str(w[-1].message), text)
201 self.assert_(w[-1].category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000202
Brett Cannon54bd41d2008-09-02 04:01:42 +0000203 # Issue 3639
204 def test_warn_nonstandard_types(self):
205 # warn() should handle non-standard types without issue.
206 for ob in (Warning, None, 42):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000207 with original_warnings.catch_warnings(record=True,
208 module=self.module) as w:
Brett Cannon54bd41d2008-09-02 04:01:42 +0000209 self.module.warn(ob)
210 # Don't directly compare objects since
211 # ``Warning() != Warning()``.
Brett Cannon1cd02472008-09-09 01:52:27 +0000212 self.assertEquals(str(w[-1].message), str(UserWarning(ob)))
Brett Cannon54bd41d2008-09-02 04:01:42 +0000213
Guido van Rossumd8faa362007-04-27 19:54:29 +0000214 def test_filename(self):
Christian Heimes33fe8092008-04-13 13:53:33 +0000215 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000216 with original_warnings.catch_warnings(record=True,
217 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000218 warning_tests.inner("spam1")
Brett Cannon1cd02472008-09-09 01:52:27 +0000219 self.assertEqual(os.path.basename(w[-1].filename),
220 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000221 warning_tests.outer("spam2")
Brett Cannon1cd02472008-09-09 01:52:27 +0000222 self.assertEqual(os.path.basename(w[-1].filename),
223 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000224
225 def test_stacklevel(self):
226 # Test stacklevel argument
227 # make sure all messages are different, so the warning won't be skipped
Christian Heimes33fe8092008-04-13 13:53:33 +0000228 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000229 with original_warnings.catch_warnings(record=True,
230 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000231 warning_tests.inner("spam3", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000232 self.assertEqual(os.path.basename(w[-1].filename),
233 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000234 warning_tests.outer("spam4", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000235 self.assertEqual(os.path.basename(w[-1].filename),
236 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000237
Christian Heimes33fe8092008-04-13 13:53:33 +0000238 warning_tests.inner("spam5", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000239 self.assertEqual(os.path.basename(w[-1].filename),
240 "test_warnings.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000241 warning_tests.outer("spam6", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000242 self.assertEqual(os.path.basename(w[-1].filename),
243 "warning_tests.py")
Christian Heimes5d8da202008-05-06 13:58:24 +0000244 warning_tests.outer("spam6.5", stacklevel=3)
Brett Cannon1cd02472008-09-09 01:52:27 +0000245 self.assertEqual(os.path.basename(w[-1].filename),
246 "test_warnings.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000247
Christian Heimes33fe8092008-04-13 13:53:33 +0000248 warning_tests.inner("spam7", stacklevel=9999)
Brett Cannon1cd02472008-09-09 01:52:27 +0000249 self.assertEqual(os.path.basename(w[-1].filename),
250 "sys")
Christian Heimes33fe8092008-04-13 13:53:33 +0000251
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000252 def test_missing_filename_not_main(self):
253 # If __file__ is not specified and __main__ is not the module name,
254 # then __file__ should be set to the module name.
255 filename = warning_tests.__file__
256 try:
257 del warning_tests.__file__
258 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000259 with original_warnings.catch_warnings(record=True,
260 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000261 warning_tests.inner("spam8", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000262 self.assertEqual(w[-1].filename, warning_tests.__name__)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000263 finally:
264 warning_tests.__file__ = filename
265
266 def test_missing_filename_main_with_argv(self):
267 # If __file__ is not specified and the caller is __main__ and sys.argv
268 # exists, then use sys.argv[0] as the file.
269 if not hasattr(sys, 'argv'):
270 return
271 filename = warning_tests.__file__
272 module_name = warning_tests.__name__
273 try:
274 del warning_tests.__file__
275 warning_tests.__name__ = '__main__'
276 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000277 with original_warnings.catch_warnings(record=True,
278 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000279 warning_tests.inner('spam9', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000280 self.assertEqual(w[-1].filename, sys.argv[0])
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000281 finally:
282 warning_tests.__file__ = filename
283 warning_tests.__name__ = module_name
284
285 def test_missing_filename_main_without_argv(self):
286 # If __file__ is not specified, the caller is __main__, and sys.argv
287 # is not set, then '__main__' is the file name.
288 filename = warning_tests.__file__
289 module_name = warning_tests.__name__
290 argv = sys.argv
291 try:
292 del warning_tests.__file__
293 warning_tests.__name__ = '__main__'
294 del sys.argv
295 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000296 with original_warnings.catch_warnings(record=True,
297 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000298 warning_tests.inner('spam10', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000299 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000300 finally:
301 warning_tests.__file__ = filename
302 warning_tests.__name__ = module_name
303 sys.argv = argv
304
Christian Heimesdaaf8ee2008-05-04 23:58:41 +0000305 def test_missing_filename_main_with_argv_empty_string(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000306 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
307 # is the empty string, then '__main__ is the file name.
308 # Tests issue 2743.
309 file_name = warning_tests.__file__
310 module_name = warning_tests.__name__
311 argv = sys.argv
312 try:
313 del warning_tests.__file__
314 warning_tests.__name__ = '__main__'
315 sys.argv = ['']
316 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000317 with original_warnings.catch_warnings(record=True,
318 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000319 warning_tests.inner('spam11', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000320 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000321 finally:
322 warning_tests.__file__ = file_name
323 warning_tests.__name__ = module_name
324 sys.argv = argv
325
Brett Cannondb734912008-06-27 00:52:15 +0000326 def test_warn_explicit_type_errors(self):
327 # warn_explicit() shoud error out gracefully if it is given objects
328 # of the wrong types.
329 # lineno is expected to be an integer.
330 self.assertRaises(TypeError, self.module.warn_explicit,
331 None, UserWarning, None, None)
332 # Either 'message' needs to be an instance of Warning or 'category'
333 # needs to be a subclass.
334 self.assertRaises(TypeError, self.module.warn_explicit,
335 None, None, None, 1)
336 # 'registry' must be a dict or None.
337 self.assertRaises((TypeError, AttributeError),
338 self.module.warn_explicit,
339 None, Warning, None, 1, registry=42)
340
Christian Heimes33fe8092008-04-13 13:53:33 +0000341class CWarnTests(BaseTest, WarnTests):
342 module = c_warnings
343
Nick Coghlanfce769e2009-04-11 14:30:59 +0000344 # As an early adopter, we sanity check the
345 # test.support.import_fresh_module utility function
346 def test_accelerated(self):
347 self.assertFalse(original_warnings is self.module)
348 self.assertFalse(hasattr(self.module.warn, '__code__'))
349
Christian Heimes33fe8092008-04-13 13:53:33 +0000350class PyWarnTests(BaseTest, WarnTests):
351 module = py_warnings
352
Nick Coghlanfce769e2009-04-11 14:30:59 +0000353 # As an early adopter, we sanity check the
354 # test.support.import_fresh_module utility function
355 def test_pure_python(self):
356 self.assertFalse(original_warnings is self.module)
357 self.assertTrue(hasattr(self.module.warn, '__code__'))
358
Christian Heimes33fe8092008-04-13 13:53:33 +0000359
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 Cannon1cd02472008-09-09 01:52:27 +0000365 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +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
375class CWCmdLineTests(BaseTest, WCmdLineTests):
376 module = c_warnings
377
378class PyWCmdLineTests(BaseTest, WCmdLineTests):
379 module = py_warnings
380
381
382class _WarningsTests(BaseTest):
383
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 Cannon1cd02472008-09-09 01:52:27 +0000390 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +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 Cannon1cd02472008-09-09 01:52:27 +0000405 with original_warnings.catch_warnings(record=True,
406 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000407 self.module.resetwarnings()
408 self.module.filterwarnings("once", category=UserWarning)
409 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannon1cd02472008-09-09 01:52:27 +0000410 self.failUnlessEqual(w[-1].message, message)
411 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000412 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000413 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000414 # Test the resetting of onceregistry.
415 self.module.onceregistry = {}
416 __warningregistry__ = {}
417 self.module.warn('onceregistry test')
Brett Cannon1cd02472008-09-09 01:52:27 +0000418 self.failUnlessEqual(w[-1].message.args, message.args)
Christian Heimes33fe8092008-04-13 13:53:33 +0000419 # Removal of onceregistry is okay.
Brett Cannon1cd02472008-09-09 01:52:27 +0000420 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000421 del self.module.onceregistry
422 __warningregistry__ = {}
423 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000424 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000425 finally:
426 self.module.onceregistry = original_registry
427
Brett Cannon0759dd62009-04-01 18:13:07 +0000428 def test_default_action(self):
429 # Replacing or removing defaultaction should be okay.
430 message = UserWarning("defaultaction test")
431 original = self.module.defaultaction
432 try:
433 with original_warnings.catch_warnings(record=True,
434 module=self.module) as w:
435 self.module.resetwarnings()
436 registry = {}
437 self.module.warn_explicit(message, UserWarning, "<test>", 42,
438 registry=registry)
439 self.assertEqual(w[-1].message, message)
440 self.assertEqual(len(w), 1)
441 self.assertEqual(len(registry), 1)
442 del w[:]
443 # Test removal.
444 del self.module.defaultaction
445 __warningregistry__ = {}
446 registry = {}
447 self.module.warn_explicit(message, UserWarning, "<test>", 43,
448 registry=registry)
449 self.assertEqual(w[-1].message, message)
450 self.assertEqual(len(w), 1)
451 self.assertEqual(len(registry), 1)
452 del w[:]
453 # Test setting.
454 self.module.defaultaction = "ignore"
455 __warningregistry__ = {}
456 registry = {}
457 self.module.warn_explicit(message, UserWarning, "<test>", 44,
458 registry=registry)
459 self.assertEqual(len(w), 0)
460 finally:
461 self.module.defaultaction = original
462
Christian Heimes33fe8092008-04-13 13:53:33 +0000463 def test_showwarning_missing(self):
464 # Test that showwarning() missing is okay.
465 text = 'del showwarning test'
Brett Cannon1cd02472008-09-09 01:52:27 +0000466 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000467 self.module.filterwarnings("always", category=UserWarning)
468 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000469 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000470 self.module.warn(text)
471 result = stream.getvalue()
472 self.failUnless(text in result)
473
Christian Heimes8dc226f2008-05-06 23:45:46 +0000474 def test_showwarning_not_callable(self):
Brett Cannonfcc05272009-04-01 20:27:29 +0000475 with original_warnings.catch_warnings(module=self.module):
476 self.module.filterwarnings("always", category=UserWarning)
477 old_showwarning = self.module.showwarning
478 self.module.showwarning = 23
479 try:
480 self.assertRaises(TypeError, self.module.warn, "Warning!")
481 finally:
482 self.module.showwarning = old_showwarning
Christian Heimes8dc226f2008-05-06 23:45:46 +0000483
Christian Heimes33fe8092008-04-13 13:53:33 +0000484 def test_show_warning_output(self):
485 # With showarning() missing, make sure that output is okay.
486 text = 'test show_warning'
Brett Cannon1cd02472008-09-09 01:52:27 +0000487 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000488 self.module.filterwarnings("always", category=UserWarning)
489 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000490 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000491 warning_tests.inner(text)
492 result = stream.getvalue()
493 self.failUnlessEqual(result.count('\n'), 2,
494 "Too many newlines in %r" % result)
495 first_line, second_line = result.split('\n', 1)
496 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Neal Norwitz32dde222008-04-15 06:43:13 +0000497 first_line_parts = first_line.rsplit(':', 3)
498 path, line, warning_class, message = first_line_parts
Christian Heimes33fe8092008-04-13 13:53:33 +0000499 line = int(line)
500 self.failUnlessEqual(expected_file, path)
501 self.failUnlessEqual(warning_class, ' ' + UserWarning.__name__)
502 self.failUnlessEqual(message, ' ' + text)
503 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
504 assert expected_line
505 self.failUnlessEqual(second_line, expected_line)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000506
507
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000508class WarningsDisplayTests(unittest.TestCase):
509
Christian Heimes33fe8092008-04-13 13:53:33 +0000510 """Test the displaying of warnings and the ability to overload functions
511 related to displaying warnings."""
512
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000513 def test_formatwarning(self):
514 message = "msg"
515 category = Warning
516 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
517 line_num = 3
518 file_line = linecache.getline(file_name, line_num).strip()
Christian Heimes33fe8092008-04-13 13:53:33 +0000519 format = "%s:%s: %s: %s\n %s\n"
520 expect = format % (file_name, line_num, category.__name__, message,
521 file_line)
522 self.failUnlessEqual(expect, self.module.formatwarning(message,
523 category, file_name, line_num))
524 # Test the 'line' argument.
525 file_line += " for the win!"
526 expect = format % (file_name, line_num, category.__name__, message,
527 file_line)
528 self.failUnlessEqual(expect, self.module.formatwarning(message,
529 category, file_name, line_num, file_line))
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000530
531 def test_showwarning(self):
532 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
533 line_num = 3
534 expected_file_line = linecache.getline(file_name, line_num).strip()
535 message = 'msg'
536 category = Warning
537 file_object = StringIO()
Christian Heimes33fe8092008-04-13 13:53:33 +0000538 expect = self.module.formatwarning(message, category, file_name,
539 line_num)
540 self.module.showwarning(message, category, file_name, line_num,
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000541 file_object)
542 self.failUnlessEqual(file_object.getvalue(), expect)
Christian Heimes33fe8092008-04-13 13:53:33 +0000543 # Test 'line' argument.
544 expected_file_line += "for the win!"
545 expect = self.module.formatwarning(message, category, file_name,
546 line_num, expected_file_line)
547 file_object = StringIO()
548 self.module.showwarning(message, category, file_name, line_num,
549 file_object, expected_file_line)
550 self.failUnlessEqual(expect, file_object.getvalue())
551
552class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
553 module = c_warnings
554
555class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
556 module = py_warnings
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000557
Brett Cannon1cd02472008-09-09 01:52:27 +0000558
Brett Cannonec92e182008-09-02 02:46:59 +0000559class CatchWarningTests(BaseTest):
Nick Coghlanb1304932008-07-13 12:25:08 +0000560
Brett Cannonec92e182008-09-02 02:46:59 +0000561 """Test catch_warnings()."""
562
563 def test_catch_warnings_restore(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000564 wmod = self.module
565 orig_filters = wmod.filters
566 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000567 # Ensure both showwarning and filters are restored when recording
568 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlanb1304932008-07-13 12:25:08 +0000569 wmod.filters = wmod.showwarning = object()
570 self.assert_(wmod.filters is orig_filters)
571 self.assert_(wmod.showwarning is orig_showwarning)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000572 # Same test, but with recording disabled
573 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlanb1304932008-07-13 12:25:08 +0000574 wmod.filters = wmod.showwarning = object()
575 self.assert_(wmod.filters is orig_filters)
576 self.assert_(wmod.showwarning is orig_showwarning)
577
Brett Cannonec92e182008-09-02 02:46:59 +0000578 def test_catch_warnings_recording(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000579 wmod = self.module
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000580 # Ensure warnings are recorded when requested
581 with wmod.catch_warnings(module=wmod, record=True) as w:
Brett Cannonec92e182008-09-02 02:46:59 +0000582 self.assertEqual(w, [])
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000583 self.assert_(type(w) is list)
Nick Coghlanb1304932008-07-13 12:25:08 +0000584 wmod.simplefilter("always")
585 wmod.warn("foo")
Brett Cannon1cd02472008-09-09 01:52:27 +0000586 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlanb1304932008-07-13 12:25:08 +0000587 wmod.warn("bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000588 self.assertEqual(str(w[-1].message), "bar")
Brett Cannonec92e182008-09-02 02:46:59 +0000589 self.assertEqual(str(w[0].message), "foo")
590 self.assertEqual(str(w[1].message), "bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000591 del w[:]
Brett Cannonec92e182008-09-02 02:46:59 +0000592 self.assertEqual(w, [])
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000593 # Ensure warnings are not recorded when not requested
Nick Coghlanb1304932008-07-13 12:25:08 +0000594 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000595 with wmod.catch_warnings(module=wmod, record=False) as w:
Nick Coghlanb1304932008-07-13 12:25:08 +0000596 self.assert_(w is None)
597 self.assert_(wmod.showwarning is orig_showwarning)
598
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000599 def test_catch_warnings_reentry_guard(self):
600 wmod = self.module
601 # Ensure catch_warnings is protected against incorrect usage
602 x = wmod.catch_warnings(module=wmod, record=True)
603 self.assertRaises(RuntimeError, x.__exit__)
604 with x:
605 self.assertRaises(RuntimeError, x.__enter__)
606 # Same test, but with recording disabled
607 x = wmod.catch_warnings(module=wmod, record=False)
608 self.assertRaises(RuntimeError, x.__exit__)
609 with x:
610 self.assertRaises(RuntimeError, x.__enter__)
611
612 def test_catch_warnings_defaults(self):
613 wmod = self.module
614 orig_filters = wmod.filters
615 orig_showwarning = wmod.showwarning
616 # Ensure default behaviour is not to record warnings
617 with wmod.catch_warnings(module=wmod) as w:
618 self.assert_(w is None)
619 self.assert_(wmod.showwarning is orig_showwarning)
620 self.assert_(wmod.filters is not orig_filters)
621 self.assert_(wmod.filters is orig_filters)
622 if wmod is sys.modules['warnings']:
623 # Ensure the default module is this one
624 with wmod.catch_warnings() as w:
625 self.assert_(w is None)
626 self.assert_(wmod.showwarning is orig_showwarning)
627 self.assert_(wmod.filters is not orig_filters)
628 self.assert_(wmod.filters is orig_filters)
629
630 def test_check_warnings(self):
631 # Explicit tests for the test.support convenience wrapper
632 wmod = self.module
633 if wmod is sys.modules['warnings']:
634 with support.check_warnings() as w:
635 self.assertEqual(w.warnings, [])
636 wmod.simplefilter("always")
637 wmod.warn("foo")
638 self.assertEqual(str(w.message), "foo")
639 wmod.warn("bar")
640 self.assertEqual(str(w.message), "bar")
641 self.assertEqual(str(w.warnings[0].message), "foo")
642 self.assertEqual(str(w.warnings[1].message), "bar")
643 w.reset()
644 self.assertEqual(w.warnings, [])
645
Brett Cannonec92e182008-09-02 02:46:59 +0000646class CCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000647 module = c_warnings
648
Brett Cannonec92e182008-09-02 02:46:59 +0000649class PyCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000650 module = py_warnings
651
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000652
Christian Heimes33fe8092008-04-13 13:53:33 +0000653def test_main():
Christian Heimesdae2a892008-04-19 00:55:37 +0000654 py_warnings.onceregistry.clear()
655 c_warnings.onceregistry.clear()
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000656 support.run_unittest(CFilterTests,
Christian Heimes33fe8092008-04-13 13:53:33 +0000657 PyFilterTests,
658 CWarnTests,
659 PyWarnTests,
660 CWCmdLineTests, PyWCmdLineTests,
661 _WarningsTests,
662 CWarningsDisplayTests, PyWarningsDisplayTests,
Brett Cannonec92e182008-09-02 02:46:59 +0000663 CCatchWarningTests, PyCatchWarningTests,
Christian Heimes33fe8092008-04-13 13:53:33 +0000664 )
665
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000666
667if __name__ == "__main__":
Christian Heimes33fe8092008-04-13 13:53:33 +0000668 test_main()