blob: dda704e22f5a47b73e375ece8972c9d6a17b4d1f [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)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000086 self.assertTrue(message, w[-1].message)
Christian Heimes33fe8092008-04-13 13:53:33 +000087 self.module.warn(message, UserWarning)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000088 self.assertTrue(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)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000168 self.assertTrue(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)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000181 self.assertTrue(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)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000201 self.assertTrue(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
Hirokazu Yamamoto1c0c0032009-07-17 06:55:42 +0000341 def test_bad_str(self):
342 # issue 6415
343 # Warnings instance with a bad format string for __str__ should not
344 # trigger a bus error.
345 class BadStrWarning(Warning):
346 """Warning with a bad format string for __str__."""
347 def __str__(self):
348 return ("A bad formatted string %(err)" %
349 {"err" : "there is no %(err)s"})
350
351 with self.assertRaises(ValueError):
352 self.module.warn(BadStrWarning())
353
354
Christian Heimes33fe8092008-04-13 13:53:33 +0000355class CWarnTests(BaseTest, WarnTests):
356 module = c_warnings
357
Nick Coghlanfce769e2009-04-11 14:30:59 +0000358 # As an early adopter, we sanity check the
359 # test.support.import_fresh_module utility function
360 def test_accelerated(self):
361 self.assertFalse(original_warnings is self.module)
362 self.assertFalse(hasattr(self.module.warn, '__code__'))
363
Christian Heimes33fe8092008-04-13 13:53:33 +0000364class PyWarnTests(BaseTest, WarnTests):
365 module = py_warnings
366
Nick Coghlanfce769e2009-04-11 14:30:59 +0000367 # As an early adopter, we sanity check the
368 # test.support.import_fresh_module utility function
369 def test_pure_python(self):
370 self.assertFalse(original_warnings is self.module)
371 self.assertTrue(hasattr(self.module.warn, '__code__'))
372
Christian Heimes33fe8092008-04-13 13:53:33 +0000373
374class WCmdLineTests(unittest.TestCase):
375
376 def test_improper_input(self):
377 # Uses the private _setoption() function to test the parsing
378 # of command-line warning arguments
Brett Cannon1cd02472008-09-09 01:52:27 +0000379 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000380 self.assertRaises(self.module._OptionError,
381 self.module._setoption, '1:2:3:4:5:6')
382 self.assertRaises(self.module._OptionError,
383 self.module._setoption, 'bogus::Warning')
384 self.assertRaises(self.module._OptionError,
385 self.module._setoption, 'ignore:2::4:-5')
386 self.module._setoption('error::Warning::0')
387 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
388
389class CWCmdLineTests(BaseTest, WCmdLineTests):
390 module = c_warnings
391
392class PyWCmdLineTests(BaseTest, WCmdLineTests):
393 module = py_warnings
394
395
396class _WarningsTests(BaseTest):
397
398 """Tests specific to the _warnings module."""
399
400 module = c_warnings
401
402 def test_filter(self):
403 # Everything should function even if 'filters' is not in warnings.
Brett Cannon1cd02472008-09-09 01:52:27 +0000404 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000405 self.module.filterwarnings("error", "", Warning, "", 0)
406 self.assertRaises(UserWarning, self.module.warn,
407 'convert to error')
408 del self.module.filters
409 self.assertRaises(UserWarning, self.module.warn,
410 'convert to error')
411
412 def test_onceregistry(self):
413 # Replacing or removing the onceregistry should be okay.
414 global __warningregistry__
415 message = UserWarning('onceregistry test')
416 try:
417 original_registry = self.module.onceregistry
418 __warningregistry__ = {}
Brett Cannon1cd02472008-09-09 01:52:27 +0000419 with original_warnings.catch_warnings(record=True,
420 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000421 self.module.resetwarnings()
422 self.module.filterwarnings("once", category=UserWarning)
423 self.module.warn_explicit(message, UserWarning, "file", 42)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000424 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000425 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000426 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000427 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000428 # Test the resetting of onceregistry.
429 self.module.onceregistry = {}
430 __warningregistry__ = {}
431 self.module.warn('onceregistry test')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000432 self.assertEqual(w[-1].message.args, message.args)
Christian Heimes33fe8092008-04-13 13:53:33 +0000433 # Removal of onceregistry is okay.
Brett Cannon1cd02472008-09-09 01:52:27 +0000434 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000435 del self.module.onceregistry
436 __warningregistry__ = {}
437 self.module.warn_explicit(message, UserWarning, "file", 42)
Brett Cannonec92e182008-09-02 02:46:59 +0000438 self.assertEquals(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000439 finally:
440 self.module.onceregistry = original_registry
441
Brett Cannon0759dd62009-04-01 18:13:07 +0000442 def test_default_action(self):
443 # Replacing or removing defaultaction should be okay.
444 message = UserWarning("defaultaction test")
445 original = self.module.defaultaction
446 try:
447 with original_warnings.catch_warnings(record=True,
448 module=self.module) as w:
449 self.module.resetwarnings()
450 registry = {}
451 self.module.warn_explicit(message, UserWarning, "<test>", 42,
452 registry=registry)
453 self.assertEqual(w[-1].message, message)
454 self.assertEqual(len(w), 1)
455 self.assertEqual(len(registry), 1)
456 del w[:]
457 # Test removal.
458 del self.module.defaultaction
459 __warningregistry__ = {}
460 registry = {}
461 self.module.warn_explicit(message, UserWarning, "<test>", 43,
462 registry=registry)
463 self.assertEqual(w[-1].message, message)
464 self.assertEqual(len(w), 1)
465 self.assertEqual(len(registry), 1)
466 del w[:]
467 # Test setting.
468 self.module.defaultaction = "ignore"
469 __warningregistry__ = {}
470 registry = {}
471 self.module.warn_explicit(message, UserWarning, "<test>", 44,
472 registry=registry)
473 self.assertEqual(len(w), 0)
474 finally:
475 self.module.defaultaction = original
476
Christian Heimes33fe8092008-04-13 13:53:33 +0000477 def test_showwarning_missing(self):
478 # Test that showwarning() missing is okay.
479 text = 'del showwarning test'
Brett Cannon1cd02472008-09-09 01:52:27 +0000480 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000481 self.module.filterwarnings("always", category=UserWarning)
482 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000483 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000484 self.module.warn(text)
485 result = stream.getvalue()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000486 self.assertIn(text, result)
Christian Heimes33fe8092008-04-13 13:53:33 +0000487
Christian Heimes8dc226f2008-05-06 23:45:46 +0000488 def test_showwarning_not_callable(self):
Brett Cannonfcc05272009-04-01 20:27:29 +0000489 with original_warnings.catch_warnings(module=self.module):
490 self.module.filterwarnings("always", category=UserWarning)
491 old_showwarning = self.module.showwarning
492 self.module.showwarning = 23
493 try:
494 self.assertRaises(TypeError, self.module.warn, "Warning!")
495 finally:
496 self.module.showwarning = old_showwarning
Christian Heimes8dc226f2008-05-06 23:45:46 +0000497
Christian Heimes33fe8092008-04-13 13:53:33 +0000498 def test_show_warning_output(self):
499 # With showarning() missing, make sure that output is okay.
500 text = 'test show_warning'
Brett Cannon1cd02472008-09-09 01:52:27 +0000501 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000502 self.module.filterwarnings("always", category=UserWarning)
503 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000504 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000505 warning_tests.inner(text)
506 result = stream.getvalue()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000507 self.assertEqual(result.count('\n'), 2,
Christian Heimes33fe8092008-04-13 13:53:33 +0000508 "Too many newlines in %r" % result)
509 first_line, second_line = result.split('\n', 1)
510 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Neal Norwitz32dde222008-04-15 06:43:13 +0000511 first_line_parts = first_line.rsplit(':', 3)
512 path, line, warning_class, message = first_line_parts
Christian Heimes33fe8092008-04-13 13:53:33 +0000513 line = int(line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000514 self.assertEqual(expected_file, path)
515 self.assertEqual(warning_class, ' ' + UserWarning.__name__)
516 self.assertEqual(message, ' ' + text)
Christian Heimes33fe8092008-04-13 13:53:33 +0000517 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
518 assert expected_line
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000519 self.assertEqual(second_line, expected_line)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000520
521
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000522class WarningsDisplayTests(unittest.TestCase):
523
Christian Heimes33fe8092008-04-13 13:53:33 +0000524 """Test the displaying of warnings and the ability to overload functions
525 related to displaying warnings."""
526
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000527 def test_formatwarning(self):
528 message = "msg"
529 category = Warning
530 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
531 line_num = 3
532 file_line = linecache.getline(file_name, line_num).strip()
Christian Heimes33fe8092008-04-13 13:53:33 +0000533 format = "%s:%s: %s: %s\n %s\n"
534 expect = format % (file_name, line_num, category.__name__, message,
535 file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000536 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000537 category, file_name, line_num))
538 # Test the 'line' argument.
539 file_line += " for the win!"
540 expect = format % (file_name, line_num, category.__name__, message,
541 file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000542 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000543 category, file_name, line_num, file_line))
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000544
545 def test_showwarning(self):
546 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
547 line_num = 3
548 expected_file_line = linecache.getline(file_name, line_num).strip()
549 message = 'msg'
550 category = Warning
551 file_object = StringIO()
Christian Heimes33fe8092008-04-13 13:53:33 +0000552 expect = self.module.formatwarning(message, category, file_name,
553 line_num)
554 self.module.showwarning(message, category, file_name, line_num,
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000555 file_object)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000556 self.assertEqual(file_object.getvalue(), expect)
Christian Heimes33fe8092008-04-13 13:53:33 +0000557 # Test 'line' argument.
558 expected_file_line += "for the win!"
559 expect = self.module.formatwarning(message, category, file_name,
560 line_num, expected_file_line)
561 file_object = StringIO()
562 self.module.showwarning(message, category, file_name, line_num,
563 file_object, expected_file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000564 self.assertEqual(expect, file_object.getvalue())
Christian Heimes33fe8092008-04-13 13:53:33 +0000565
566class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
567 module = c_warnings
568
569class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
570 module = py_warnings
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000571
Brett Cannon1cd02472008-09-09 01:52:27 +0000572
Brett Cannonec92e182008-09-02 02:46:59 +0000573class CatchWarningTests(BaseTest):
Nick Coghlanb1304932008-07-13 12:25:08 +0000574
Brett Cannonec92e182008-09-02 02:46:59 +0000575 """Test catch_warnings()."""
576
577 def test_catch_warnings_restore(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000578 wmod = self.module
579 orig_filters = wmod.filters
580 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000581 # Ensure both showwarning and filters are restored when recording
582 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlanb1304932008-07-13 12:25:08 +0000583 wmod.filters = wmod.showwarning = object()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000584 self.assertTrue(wmod.filters is orig_filters)
585 self.assertTrue(wmod.showwarning is orig_showwarning)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000586 # Same test, but with recording disabled
587 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlanb1304932008-07-13 12:25:08 +0000588 wmod.filters = wmod.showwarning = object()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000589 self.assertTrue(wmod.filters is orig_filters)
590 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000591
Brett Cannonec92e182008-09-02 02:46:59 +0000592 def test_catch_warnings_recording(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000593 wmod = self.module
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000594 # Ensure warnings are recorded when requested
595 with wmod.catch_warnings(module=wmod, record=True) as w:
Brett Cannonec92e182008-09-02 02:46:59 +0000596 self.assertEqual(w, [])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000597 self.assertTrue(type(w) is list)
Nick Coghlanb1304932008-07-13 12:25:08 +0000598 wmod.simplefilter("always")
599 wmod.warn("foo")
Brett Cannon1cd02472008-09-09 01:52:27 +0000600 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlanb1304932008-07-13 12:25:08 +0000601 wmod.warn("bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000602 self.assertEqual(str(w[-1].message), "bar")
Brett Cannonec92e182008-09-02 02:46:59 +0000603 self.assertEqual(str(w[0].message), "foo")
604 self.assertEqual(str(w[1].message), "bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000605 del w[:]
Brett Cannonec92e182008-09-02 02:46:59 +0000606 self.assertEqual(w, [])
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000607 # Ensure warnings are not recorded when not requested
Nick Coghlanb1304932008-07-13 12:25:08 +0000608 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000609 with wmod.catch_warnings(module=wmod, record=False) as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000610 self.assertTrue(w is None)
611 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000612
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000613 def test_catch_warnings_reentry_guard(self):
614 wmod = self.module
615 # Ensure catch_warnings is protected against incorrect usage
616 x = wmod.catch_warnings(module=wmod, record=True)
617 self.assertRaises(RuntimeError, x.__exit__)
618 with x:
619 self.assertRaises(RuntimeError, x.__enter__)
620 # Same test, but with recording disabled
621 x = wmod.catch_warnings(module=wmod, record=False)
622 self.assertRaises(RuntimeError, x.__exit__)
623 with x:
624 self.assertRaises(RuntimeError, x.__enter__)
625
626 def test_catch_warnings_defaults(self):
627 wmod = self.module
628 orig_filters = wmod.filters
629 orig_showwarning = wmod.showwarning
630 # Ensure default behaviour is not to record warnings
631 with wmod.catch_warnings(module=wmod) as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000632 self.assertTrue(w is None)
633 self.assertTrue(wmod.showwarning is orig_showwarning)
634 self.assertTrue(wmod.filters is not orig_filters)
635 self.assertTrue(wmod.filters is orig_filters)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000636 if wmod is sys.modules['warnings']:
637 # Ensure the default module is this one
638 with wmod.catch_warnings() as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000639 self.assertTrue(w is None)
640 self.assertTrue(wmod.showwarning is orig_showwarning)
641 self.assertTrue(wmod.filters is not orig_filters)
642 self.assertTrue(wmod.filters is orig_filters)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000643
644 def test_check_warnings(self):
645 # Explicit tests for the test.support convenience wrapper
646 wmod = self.module
Florent Xicluna53b506be2010-03-18 20:00:57 +0000647 if wmod is not sys.modules['warnings']:
648 return
649 with support.check_warnings(quiet=False) as w:
650 self.assertEqual(w.warnings, [])
651 wmod.simplefilter("always")
652 wmod.warn("foo")
653 self.assertEqual(str(w.message), "foo")
654 wmod.warn("bar")
655 self.assertEqual(str(w.message), "bar")
656 self.assertEqual(str(w.warnings[0].message), "foo")
657 self.assertEqual(str(w.warnings[1].message), "bar")
658 w.reset()
659 self.assertEqual(w.warnings, [])
660
661 with support.check_warnings():
662 # defaults to quiet=True without argument
663 pass
664 with support.check_warnings(('foo', UserWarning)):
665 wmod.warn("foo")
666
667 with self.assertRaises(AssertionError):
668 with support.check_warnings(('', RuntimeWarning)):
669 # defaults to quiet=False with argument
670 pass
671 with self.assertRaises(AssertionError):
672 with support.check_warnings(('foo', RuntimeWarning)):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000673 wmod.warn("foo")
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000674
Brett Cannonec92e182008-09-02 02:46:59 +0000675class CCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000676 module = c_warnings
677
Brett Cannonec92e182008-09-02 02:46:59 +0000678class PyCatchWarningTests(CatchWarningTests):
Nick Coghlanb1304932008-07-13 12:25:08 +0000679 module = py_warnings
680
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000681
Christian Heimes33fe8092008-04-13 13:53:33 +0000682def test_main():
Christian Heimesdae2a892008-04-19 00:55:37 +0000683 py_warnings.onceregistry.clear()
684 c_warnings.onceregistry.clear()
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000685 support.run_unittest(CFilterTests,
Christian Heimes33fe8092008-04-13 13:53:33 +0000686 PyFilterTests,
687 CWarnTests,
688 PyWarnTests,
689 CWCmdLineTests, PyWCmdLineTests,
690 _WarningsTests,
691 CWarningsDisplayTests, PyWarningsDisplayTests,
Brett Cannonec92e182008-09-02 02:46:59 +0000692 CCatchWarningTests, PyCatchWarningTests,
Christian Heimes33fe8092008-04-13 13:53:33 +0000693 )
694
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000695
696if __name__ == "__main__":
Christian Heimes33fe8092008-04-13 13:53:33 +0000697 test_main()