blob: 1f377ad7f89a4802cb25f8e59eebf15bc79bb092 [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 Coghlanfce769e2009-04-11 14:30:59 +000013py_warnings = support.import_fresh_module('warnings', ['_warnings'])
14# XXX (ncoghlan 20090412):
15# Something in Py3k doesn't like sharing the same instance of
16# _warnings between original_warnings and c_warnings
17# Will leave issue 5354 open until I understand why 3.x breaks
18# without the next line, while 2.x doesn't care
Christian Heimes33fe8092008-04-13 13:53:33 +000019del sys.modules['_warnings']
Nick Coghlanfce769e2009-04-11 14:30:59 +000020c_warnings = support.import_fresh_module('warnings')
Christian Heimes33fe8092008-04-13 13:53:33 +000021
22@contextmanager
23def warnings_state(module):
24 """Use a specific warnings implementation in warning_tests."""
25 global __warningregistry__
26 for to_clear in (sys, warning_tests):
27 try:
28 to_clear.__warningregistry__.clear()
29 except AttributeError:
30 pass
31 try:
32 __warningregistry__.clear()
33 except NameError:
34 pass
35 original_warnings = warning_tests.warnings
36 try:
37 warning_tests.warnings = module
38 yield
39 finally:
40 warning_tests.warnings = original_warnings
41
42
43class BaseTest(unittest.TestCase):
44
45 """Basic bookkeeping required for testing."""
46
47 def setUp(self):
48 # The __warningregistry__ needs to be in a pristine state for tests
49 # to work properly.
50 if '__warningregistry__' in globals():
51 del globals()['__warningregistry__']
52 if hasattr(warning_tests, '__warningregistry__'):
53 del warning_tests.__warningregistry__
54 if hasattr(sys, '__warningregistry__'):
55 del sys.__warningregistry__
56 # The 'warnings' module must be explicitly set so that the proper
57 # interaction between _warnings and 'warnings' can be controlled.
58 sys.modules['warnings'] = self.module
59 super(BaseTest, self).setUp()
60
61 def tearDown(self):
62 sys.modules['warnings'] = original_warnings
63 super(BaseTest, self).tearDown()
64
65
66class FilterTests(object):
67
68 """Testing the filtering functionality."""
69
70 def test_error(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000071 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000072 self.module.resetwarnings()
73 self.module.filterwarnings("error", category=UserWarning)
74 self.assertRaises(UserWarning, self.module.warn,
75 "FilterTests.test_error")
76
77 def test_ignore(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000078 with original_warnings.catch_warnings(record=True,
79 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000080 self.module.resetwarnings()
81 self.module.filterwarnings("ignore", category=UserWarning)
82 self.module.warn("FilterTests.test_ignore", UserWarning)
Brett Cannonec92e182008-09-02 02:46:59 +000083 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +000084
85 def test_always(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000086 with original_warnings.catch_warnings(record=True,
87 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000088 self.module.resetwarnings()
89 self.module.filterwarnings("always", category=UserWarning)
90 message = "FilterTests.test_always"
91 self.module.warn(message, UserWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +000092 self.assert_(message, w[-1].message)
Christian Heimes33fe8092008-04-13 13:53:33 +000093 self.module.warn(message, UserWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +000094 self.assert_(w[-1].message, message)
Christian Heimes33fe8092008-04-13 13:53:33 +000095
96 def test_default(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000097 with original_warnings.catch_warnings(record=True,
98 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000099 self.module.resetwarnings()
100 self.module.filterwarnings("default", category=UserWarning)
101 message = UserWarning("FilterTests.test_default")
102 for x in range(2):
103 self.module.warn(message, UserWarning)
104 if x == 0:
Brett Cannon1cd02472008-09-09 01:52:27 +0000105 self.assertEquals(w[-1].message, message)
106 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000107 elif x == 1:
Brett Cannon1cd02472008-09-09 01:52:27 +0000108 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000109 else:
110 raise ValueError("loop variant unhandled")
111
112 def test_module(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000113 with original_warnings.catch_warnings(record=True,
114 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000115 self.module.resetwarnings()
116 self.module.filterwarnings("module", category=UserWarning)
117 message = UserWarning("FilterTests.test_module")
118 self.module.warn(message, UserWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +0000119 self.assertEquals(w[-1].message, message)
120 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000121 self.module.warn(message, UserWarning)
Brett Cannon1cd02472008-09-09 01:52:27 +0000122 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000123
124 def test_once(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000125 with original_warnings.catch_warnings(record=True,
126 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000127 self.module.resetwarnings()
128 self.module.filterwarnings("once", category=UserWarning)
129 message = UserWarning("FilterTests.test_once")
130 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
131 42)
Brett Cannon1cd02472008-09-09 01:52:27 +0000132 self.assertEquals(w[-1].message, message)
133 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000134 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
135 13)
Brett Cannonec92e182008-09-02 02:46:59 +0000136 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000137 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
138 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000139 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000140
141 def test_inheritance(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000142 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000143 self.module.resetwarnings()
144 self.module.filterwarnings("error", category=Warning)
145 self.assertRaises(UserWarning, self.module.warn,
146 "FilterTests.test_inheritance", UserWarning)
147
148 def test_ordering(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000149 with original_warnings.catch_warnings(record=True,
150 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000151 self.module.resetwarnings()
152 self.module.filterwarnings("ignore", category=UserWarning)
153 self.module.filterwarnings("error", category=UserWarning,
154 append=True)
Brett Cannon1cd02472008-09-09 01:52:27 +0000155 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000156 try:
157 self.module.warn("FilterTests.test_ordering", UserWarning)
158 except UserWarning:
159 self.fail("order handling for actions failed")
Brett Cannonec92e182008-09-02 02:46:59 +0000160 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000161
162 def test_filterwarnings(self):
163 # Test filterwarnings().
164 # Implicitly also tests resetwarnings().
Brett Cannon1cd02472008-09-09 01:52:27 +0000165 with original_warnings.catch_warnings(record=True,
166 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000167 self.module.filterwarnings("error", "", Warning, "", 0)
168 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
169
170 self.module.resetwarnings()
171 text = 'handle normally'
172 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000173 self.assertEqual(str(w[-1].message), text)
174 self.assert_(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000175
176 self.module.filterwarnings("ignore", "", Warning, "", 0)
177 text = 'filtered out'
178 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000179 self.assertNotEqual(str(w[-1].message), text)
Christian Heimes33fe8092008-04-13 13:53:33 +0000180
181 self.module.resetwarnings()
182 self.module.filterwarnings("error", "hex*", Warning, "", 0)
183 self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
184 text = 'nonmatching text'
185 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000186 self.assertEqual(str(w[-1].message), text)
187 self.assert_(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000188
189class CFilterTests(BaseTest, FilterTests):
190 module = c_warnings
191
192class PyFilterTests(BaseTest, FilterTests):
193 module = py_warnings
194
195
196class WarnTests(unittest.TestCase):
197
198 """Test warnings.warn() and warnings.warn_explicit()."""
199
200 def test_message(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000201 with original_warnings.catch_warnings(record=True,
202 module=self.module) as w:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000203 for i in range(4):
Christian Heimes33fe8092008-04-13 13:53:33 +0000204 text = 'multi %d' %i # Different text on each call.
205 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000206 self.assertEqual(str(w[-1].message), text)
207 self.assert_(w[-1].category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000208
Brett Cannon54bd41d2008-09-02 04:01:42 +0000209 # Issue 3639
210 def test_warn_nonstandard_types(self):
211 # warn() should handle non-standard types without issue.
212 for ob in (Warning, None, 42):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000213 with original_warnings.catch_warnings(record=True,
214 module=self.module) as w:
Brett Cannon54bd41d2008-09-02 04:01:42 +0000215 self.module.warn(ob)
216 # Don't directly compare objects since
217 # ``Warning() != Warning()``.
Brett Cannon1cd02472008-09-09 01:52:27 +0000218 self.assertEquals(str(w[-1].message), str(UserWarning(ob)))
Brett Cannon54bd41d2008-09-02 04:01:42 +0000219
Guido van Rossumd8faa362007-04-27 19:54:29 +0000220 def test_filename(self):
Christian Heimes33fe8092008-04-13 13:53:33 +0000221 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000222 with original_warnings.catch_warnings(record=True,
223 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000224 warning_tests.inner("spam1")
Brett Cannon1cd02472008-09-09 01:52:27 +0000225 self.assertEqual(os.path.basename(w[-1].filename),
226 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000227 warning_tests.outer("spam2")
Brett Cannon1cd02472008-09-09 01:52:27 +0000228 self.assertEqual(os.path.basename(w[-1].filename),
229 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000230
231 def test_stacklevel(self):
232 # Test stacklevel argument
233 # make sure all messages are different, so the warning won't be skipped
Christian Heimes33fe8092008-04-13 13:53:33 +0000234 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000235 with original_warnings.catch_warnings(record=True,
236 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000237 warning_tests.inner("spam3", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000238 self.assertEqual(os.path.basename(w[-1].filename),
239 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000240 warning_tests.outer("spam4", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000241 self.assertEqual(os.path.basename(w[-1].filename),
242 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000243
Christian Heimes33fe8092008-04-13 13:53:33 +0000244 warning_tests.inner("spam5", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000245 self.assertEqual(os.path.basename(w[-1].filename),
246 "test_warnings.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000247 warning_tests.outer("spam6", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000248 self.assertEqual(os.path.basename(w[-1].filename),
249 "warning_tests.py")
Christian Heimes5d8da202008-05-06 13:58:24 +0000250 warning_tests.outer("spam6.5", stacklevel=3)
Brett Cannon1cd02472008-09-09 01:52:27 +0000251 self.assertEqual(os.path.basename(w[-1].filename),
252 "test_warnings.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000253
Christian Heimes33fe8092008-04-13 13:53:33 +0000254 warning_tests.inner("spam7", stacklevel=9999)
Brett Cannon1cd02472008-09-09 01:52:27 +0000255 self.assertEqual(os.path.basename(w[-1].filename),
256 "sys")
Christian Heimes33fe8092008-04-13 13:53:33 +0000257
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000258 def test_missing_filename_not_main(self):
259 # If __file__ is not specified and __main__ is not the module name,
260 # then __file__ should be set to the module name.
261 filename = warning_tests.__file__
262 try:
263 del warning_tests.__file__
264 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000265 with original_warnings.catch_warnings(record=True,
266 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000267 warning_tests.inner("spam8", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000268 self.assertEqual(w[-1].filename, warning_tests.__name__)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000269 finally:
270 warning_tests.__file__ = filename
271
272 def test_missing_filename_main_with_argv(self):
273 # If __file__ is not specified and the caller is __main__ and sys.argv
274 # exists, then use sys.argv[0] as the file.
275 if not hasattr(sys, 'argv'):
276 return
277 filename = warning_tests.__file__
278 module_name = warning_tests.__name__
279 try:
280 del warning_tests.__file__
281 warning_tests.__name__ = '__main__'
282 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000283 with original_warnings.catch_warnings(record=True,
284 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000285 warning_tests.inner('spam9', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000286 self.assertEqual(w[-1].filename, sys.argv[0])
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000287 finally:
288 warning_tests.__file__ = filename
289 warning_tests.__name__ = module_name
290
291 def test_missing_filename_main_without_argv(self):
292 # If __file__ is not specified, the caller is __main__, and sys.argv
293 # is not set, then '__main__' is the file name.
294 filename = warning_tests.__file__
295 module_name = warning_tests.__name__
296 argv = sys.argv
297 try:
298 del warning_tests.__file__
299 warning_tests.__name__ = '__main__'
300 del sys.argv
301 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000302 with original_warnings.catch_warnings(record=True,
303 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000304 warning_tests.inner('spam10', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000305 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000306 finally:
307 warning_tests.__file__ = filename
308 warning_tests.__name__ = module_name
309 sys.argv = argv
310
Christian Heimesdaaf8ee2008-05-04 23:58:41 +0000311 def test_missing_filename_main_with_argv_empty_string(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000312 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
313 # is the empty string, then '__main__ is the file name.
314 # Tests issue 2743.
315 file_name = warning_tests.__file__
316 module_name = warning_tests.__name__
317 argv = sys.argv
318 try:
319 del warning_tests.__file__
320 warning_tests.__name__ = '__main__'
321 sys.argv = ['']
322 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000323 with original_warnings.catch_warnings(record=True,
324 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000325 warning_tests.inner('spam11', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000326 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000327 finally:
328 warning_tests.__file__ = file_name
329 warning_tests.__name__ = module_name
330 sys.argv = argv
331
Brett Cannondb734912008-06-27 00:52:15 +0000332 def test_warn_explicit_type_errors(self):
333 # warn_explicit() shoud error out gracefully if it is given objects
334 # of the wrong types.
335 # lineno is expected to be an integer.
336 self.assertRaises(TypeError, self.module.warn_explicit,
337 None, UserWarning, None, None)
338 # Either 'message' needs to be an instance of Warning or 'category'
339 # needs to be a subclass.
340 self.assertRaises(TypeError, self.module.warn_explicit,
341 None, None, None, 1)
342 # 'registry' must be a dict or None.
343 self.assertRaises((TypeError, AttributeError),
344 self.module.warn_explicit,
345 None, Warning, None, 1, registry=42)
346
Christian Heimes33fe8092008-04-13 13:53:33 +0000347class CWarnTests(BaseTest, WarnTests):
348 module = c_warnings
349
Nick Coghlanfce769e2009-04-11 14:30:59 +0000350 # As an early adopter, we sanity check the
351 # test.support.import_fresh_module utility function
352 def test_accelerated(self):
353 self.assertFalse(original_warnings is self.module)
354 self.assertFalse(hasattr(self.module.warn, '__code__'))
355
Christian Heimes33fe8092008-04-13 13:53:33 +0000356class PyWarnTests(BaseTest, WarnTests):
357 module = py_warnings
358
Nick Coghlanfce769e2009-04-11 14:30:59 +0000359 # As an early adopter, we sanity check the
360 # test.support.import_fresh_module utility function
361 def test_pure_python(self):
362 self.assertFalse(original_warnings is self.module)
363 self.assertTrue(hasattr(self.module.warn, '__code__'))
364
Christian Heimes33fe8092008-04-13 13:53:33 +0000365
366class WCmdLineTests(unittest.TestCase):
367
368 def test_improper_input(self):
369 # Uses the private _setoption() function to test the parsing
370 # of command-line warning arguments
Brett Cannon1cd02472008-09-09 01:52:27 +0000371 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000372 self.assertRaises(self.module._OptionError,
373 self.module._setoption, '1:2:3:4:5:6')
374 self.assertRaises(self.module._OptionError,
375 self.module._setoption, 'bogus::Warning')
376 self.assertRaises(self.module._OptionError,
377 self.module._setoption, 'ignore:2::4:-5')
378 self.module._setoption('error::Warning::0')
379 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
380
381class CWCmdLineTests(BaseTest, WCmdLineTests):
382 module = c_warnings
383
384class PyWCmdLineTests(BaseTest, WCmdLineTests):
385 module = py_warnings
386
387
388class _WarningsTests(BaseTest):
389
390 """Tests specific to the _warnings module."""
391
392 module = c_warnings
393
394 def test_filter(self):
395 # Everything should function even if 'filters' is not in warnings.
Brett Cannon1cd02472008-09-09 01:52:27 +0000396 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000397 self.module.filterwarnings("error", "", Warning, "", 0)
398 self.assertRaises(UserWarning, self.module.warn,
399 'convert to error')
400 del self.module.filters
401 self.assertRaises(UserWarning, self.module.warn,
402 'convert to error')
403
404 def test_onceregistry(self):
405 # Replacing or removing the onceregistry should be okay.
406 global __warningregistry__
407 message = UserWarning('onceregistry test')
408 try:
409 original_registry = self.module.onceregistry
410 __warningregistry__ = {}
Brett Cannon1cd02472008-09-09 01:52:27 +0000411 with original_warnings.catch_warnings(record=True,
412 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000413 self.module.resetwarnings()
414 self.module.filterwarnings("once", category=UserWarning)
415 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannon1cd02472008-09-09 01:52:27 +0000416 self.failUnlessEqual(w[-1].message, message)
417 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000418 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000419 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000420 # Test the resetting of onceregistry.
421 self.module.onceregistry = {}
422 __warningregistry__ = {}
423 self.module.warn('onceregistry test')
Brett Cannon1cd02472008-09-09 01:52:27 +0000424 self.failUnlessEqual(w[-1].message.args, message.args)
Christian Heimes33fe8092008-04-13 13:53:33 +0000425 # Removal of onceregistry is okay.
Brett Cannon1cd02472008-09-09 01:52:27 +0000426 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000427 del self.module.onceregistry
428 __warningregistry__ = {}
429 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000430 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000431 finally:
432 self.module.onceregistry = original_registry
433
Brett Cannon0759dd62009-04-01 18:13:07 +0000434 def test_default_action(self):
435 # Replacing or removing defaultaction should be okay.
436 message = UserWarning("defaultaction test")
437 original = self.module.defaultaction
438 try:
439 with original_warnings.catch_warnings(record=True,
440 module=self.module) as w:
441 self.module.resetwarnings()
442 registry = {}
443 self.module.warn_explicit(message, UserWarning, "<test>", 42,
444 registry=registry)
445 self.assertEqual(w[-1].message, message)
446 self.assertEqual(len(w), 1)
447 self.assertEqual(len(registry), 1)
448 del w[:]
449 # Test removal.
450 del self.module.defaultaction
451 __warningregistry__ = {}
452 registry = {}
453 self.module.warn_explicit(message, UserWarning, "<test>", 43,
454 registry=registry)
455 self.assertEqual(w[-1].message, message)
456 self.assertEqual(len(w), 1)
457 self.assertEqual(len(registry), 1)
458 del w[:]
459 # Test setting.
460 self.module.defaultaction = "ignore"
461 __warningregistry__ = {}
462 registry = {}
463 self.module.warn_explicit(message, UserWarning, "<test>", 44,
464 registry=registry)
465 self.assertEqual(len(w), 0)
466 finally:
467 self.module.defaultaction = original
468
Christian Heimes33fe8092008-04-13 13:53:33 +0000469 def test_showwarning_missing(self):
470 # Test that showwarning() missing is okay.
471 text = 'del showwarning test'
Brett Cannon1cd02472008-09-09 01:52:27 +0000472 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000473 self.module.filterwarnings("always", category=UserWarning)
474 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000475 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000476 self.module.warn(text)
477 result = stream.getvalue()
478 self.failUnless(text in result)
479
Christian Heimes8dc226f2008-05-06 23:45:46 +0000480 def test_showwarning_not_callable(self):
Brett Cannonfcc05272009-04-01 20:27:29 +0000481 with original_warnings.catch_warnings(module=self.module):
482 self.module.filterwarnings("always", category=UserWarning)
483 old_showwarning = self.module.showwarning
484 self.module.showwarning = 23
485 try:
486 self.assertRaises(TypeError, self.module.warn, "Warning!")
487 finally:
488 self.module.showwarning = old_showwarning
Christian Heimes8dc226f2008-05-06 23:45:46 +0000489
Christian Heimes33fe8092008-04-13 13:53:33 +0000490 def test_show_warning_output(self):
491 # With showarning() missing, make sure that output is okay.
492 text = 'test show_warning'
Brett Cannon1cd02472008-09-09 01:52:27 +0000493 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000494 self.module.filterwarnings("always", category=UserWarning)
495 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000496 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000497 warning_tests.inner(text)
498 result = stream.getvalue()
499 self.failUnlessEqual(result.count('\n'), 2,
500 "Too many newlines in %r" % result)
501 first_line, second_line = result.split('\n', 1)
502 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Neal Norwitz32dde222008-04-15 06:43:13 +0000503 first_line_parts = first_line.rsplit(':', 3)
504 path, line, warning_class, message = first_line_parts
Christian Heimes33fe8092008-04-13 13:53:33 +0000505 line = int(line)
506 self.failUnlessEqual(expected_file, path)
507 self.failUnlessEqual(warning_class, ' ' + UserWarning.__name__)
508 self.failUnlessEqual(message, ' ' + text)
509 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
510 assert expected_line
511 self.failUnlessEqual(second_line, expected_line)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000512
513
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000514class WarningsDisplayTests(unittest.TestCase):
515
Christian Heimes33fe8092008-04-13 13:53:33 +0000516 """Test the displaying of warnings and the ability to overload functions
517 related to displaying warnings."""
518
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000519 def test_formatwarning(self):
520 message = "msg"
521 category = Warning
522 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
523 line_num = 3
524 file_line = linecache.getline(file_name, line_num).strip()
Christian Heimes33fe8092008-04-13 13:53:33 +0000525 format = "%s:%s: %s: %s\n %s\n"
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))
530 # Test the 'line' argument.
531 file_line += " for the win!"
532 expect = format % (file_name, line_num, category.__name__, message,
533 file_line)
534 self.failUnlessEqual(expect, self.module.formatwarning(message,
535 category, file_name, line_num, file_line))
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000536
537 def test_showwarning(self):
538 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
539 line_num = 3
540 expected_file_line = linecache.getline(file_name, line_num).strip()
541 message = 'msg'
542 category = Warning
543 file_object = StringIO()
Christian Heimes33fe8092008-04-13 13:53:33 +0000544 expect = self.module.formatwarning(message, category, file_name,
545 line_num)
546 self.module.showwarning(message, category, file_name, line_num,
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000547 file_object)
548 self.failUnlessEqual(file_object.getvalue(), expect)
Christian Heimes33fe8092008-04-13 13:53:33 +0000549 # Test 'line' argument.
550 expected_file_line += "for the win!"
551 expect = self.module.formatwarning(message, category, file_name,
552 line_num, expected_file_line)
553 file_object = StringIO()
554 self.module.showwarning(message, category, file_name, line_num,
555 file_object, expected_file_line)
556 self.failUnlessEqual(expect, file_object.getvalue())
557
558class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
559 module = c_warnings
560
561class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
562 module = py_warnings
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000563
Brett Cannon1cd02472008-09-09 01:52:27 +0000564
Brett Cannonec92e182008-09-02 02:46:59 +0000565class CatchWarningTests(BaseTest):
Nick Coghlanb1304932008-07-13 12:25:08 +0000566
Brett Cannonec92e182008-09-02 02:46:59 +0000567 """Test catch_warnings()."""
568
569 def test_catch_warnings_restore(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000570 wmod = self.module
571 orig_filters = wmod.filters
572 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000573 # Ensure both showwarning and filters are restored when recording
574 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlanb1304932008-07-13 12:25:08 +0000575 wmod.filters = wmod.showwarning = object()
576 self.assert_(wmod.filters is orig_filters)
577 self.assert_(wmod.showwarning is orig_showwarning)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000578 # Same test, but with recording disabled
579 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlanb1304932008-07-13 12:25:08 +0000580 wmod.filters = wmod.showwarning = object()
581 self.assert_(wmod.filters is orig_filters)
582 self.assert_(wmod.showwarning is orig_showwarning)
583
Brett Cannonec92e182008-09-02 02:46:59 +0000584 def test_catch_warnings_recording(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000585 wmod = self.module
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000586 # Ensure warnings are recorded when requested
587 with wmod.catch_warnings(module=wmod, record=True) as w:
Brett Cannonec92e182008-09-02 02:46:59 +0000588 self.assertEqual(w, [])
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000589 self.assert_(type(w) is list)
Nick Coghlanb1304932008-07-13 12:25:08 +0000590 wmod.simplefilter("always")
591 wmod.warn("foo")
Brett Cannon1cd02472008-09-09 01:52:27 +0000592 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlanb1304932008-07-13 12:25:08 +0000593 wmod.warn("bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000594 self.assertEqual(str(w[-1].message), "bar")
Brett Cannonec92e182008-09-02 02:46:59 +0000595 self.assertEqual(str(w[0].message), "foo")
596 self.assertEqual(str(w[1].message), "bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000597 del w[:]
Brett Cannonec92e182008-09-02 02:46:59 +0000598 self.assertEqual(w, [])
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000599 # Ensure warnings are not recorded when not requested
Nick Coghlanb1304932008-07-13 12:25:08 +0000600 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000601 with wmod.catch_warnings(module=wmod, record=False) as w:
Nick Coghlanb1304932008-07-13 12:25:08 +0000602 self.assert_(w is None)
603 self.assert_(wmod.showwarning is orig_showwarning)
604
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000605 def test_catch_warnings_reentry_guard(self):
606 wmod = self.module
607 # Ensure catch_warnings is protected against incorrect usage
608 x = wmod.catch_warnings(module=wmod, record=True)
609 self.assertRaises(RuntimeError, x.__exit__)
610 with x:
611 self.assertRaises(RuntimeError, x.__enter__)
612 # Same test, but with recording disabled
613 x = wmod.catch_warnings(module=wmod, record=False)
614 self.assertRaises(RuntimeError, x.__exit__)
615 with x:
616 self.assertRaises(RuntimeError, x.__enter__)
617
618 def test_catch_warnings_defaults(self):
619 wmod = self.module
620 orig_filters = wmod.filters
621 orig_showwarning = wmod.showwarning
622 # Ensure default behaviour is not to record warnings
623 with wmod.catch_warnings(module=wmod) as w:
624 self.assert_(w is None)
625 self.assert_(wmod.showwarning is orig_showwarning)
626 self.assert_(wmod.filters is not orig_filters)
627 self.assert_(wmod.filters is orig_filters)
628 if wmod is sys.modules['warnings']:
629 # Ensure the default module is this one
630 with wmod.catch_warnings() as w:
631 self.assert_(w is None)
632 self.assert_(wmod.showwarning is orig_showwarning)
633 self.assert_(wmod.filters is not orig_filters)
634 self.assert_(wmod.filters is orig_filters)
635
636 def test_check_warnings(self):
637 # Explicit tests for the test.support convenience wrapper
638 wmod = self.module
639 if wmod is sys.modules['warnings']:
640 with support.check_warnings() as w:
641 self.assertEqual(w.warnings, [])
642 wmod.simplefilter("always")
643 wmod.warn("foo")
644 self.assertEqual(str(w.message), "foo")
645 wmod.warn("bar")
646 self.assertEqual(str(w.message), "bar")
647 self.assertEqual(str(w.warnings[0].message), "foo")
648 self.assertEqual(str(w.warnings[1].message), "bar")
649 w.reset()
650 self.assertEqual(w.warnings, [])
651
Brett Cannonec92e182008-09-02 02:46:59 +0000652class CCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000653 module = c_warnings
654
Brett Cannonec92e182008-09-02 02:46:59 +0000655class PyCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000656 module = py_warnings
657
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000658
Christian Heimes33fe8092008-04-13 13:53:33 +0000659def test_main():
Christian Heimesdae2a892008-04-19 00:55:37 +0000660 py_warnings.onceregistry.clear()
661 c_warnings.onceregistry.clear()
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000662 support.run_unittest(CFilterTests,
Christian Heimes33fe8092008-04-13 13:53:33 +0000663 PyFilterTests,
664 CWarnTests,
665 PyWarnTests,
666 CWCmdLineTests, PyWCmdLineTests,
667 _WarningsTests,
668 CWarningsDisplayTests, PyWarningsDisplayTests,
Brett Cannonec92e182008-09-02 02:46:59 +0000669 CCatchWarningTests, PyCatchWarningTests,
Christian Heimes33fe8092008-04-13 13:53:33 +0000670 )
671
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000672
673if __name__ == "__main__":
Christian Heimes33fe8092008-04-13 13:53:33 +0000674 test_main()