blob: 9fca0802473f94eb22ae02e2ec6a7d1edb7869e1 [file] [log] [blame]
Brett Cannone9746892008-04-12 23:44:07 +00001from contextlib import contextmanager
Brett Cannon905c31c2007-12-20 10:09:52 +00002import linecache
Raymond Hettingerdc9dcf12003-07-13 06:15:11 +00003import os
Brett Cannon905c31c2007-12-20 10:09:52 +00004import StringIO
Brett Cannon855da6c2007-08-17 20:16:15 +00005import sys
Raymond Hettingerd6f6e502003-07-13 08:37:40 +00006import unittest
7from test import test_support
Jeremy Hylton85014662003-07-11 15:37:59 +00008
Walter Dörwalde1a9b422007-04-03 16:53:43 +00009import warning_tests
10
Brett Cannon667bb4f2008-04-13 02:42:36 +000011import warnings as original_warnings
12
Brett Cannone9746892008-04-12 23:44:07 +000013sys.modules['_warnings'] = 0
Brett Cannon667bb4f2008-04-13 02:42:36 +000014del sys.modules['warnings']
Jeremy Hylton85014662003-07-11 15:37:59 +000015
Brett Cannone9746892008-04-12 23:44:07 +000016import warnings as py_warnings
17
18del sys.modules['_warnings']
19del sys.modules['warnings']
20
21import warnings as c_warnings
22
Brett Cannon667bb4f2008-04-13 02:42:36 +000023sys.modules['warnings'] = original_warnings
24
25
Brett Cannone9746892008-04-12 23:44:07 +000026@contextmanager
27def warnings_state(module):
28 """Use a specific warnings implementation in warning_tests."""
29 global __warningregistry__
30 for to_clear in (sys, warning_tests):
31 try:
32 to_clear.__warningregistry__.clear()
33 except AttributeError:
34 pass
35 try:
36 __warningregistry__.clear()
37 except NameError:
38 pass
39 original_warnings = warning_tests.warnings
40 try:
41 warning_tests.warnings = module
42 yield
43 finally:
44 warning_tests.warnings = original_warnings
45
46
Brett Cannon667bb4f2008-04-13 02:42:36 +000047class BaseTest(unittest.TestCase):
Brett Cannone9746892008-04-12 23:44:07 +000048
Brett Cannon667bb4f2008-04-13 02:42:36 +000049 """Basic bookkeeping required for testing."""
Brett Cannone9746892008-04-12 23:44:07 +000050
51 def setUp(self):
Brett Cannon667bb4f2008-04-13 02:42:36 +000052 # The __warningregistry__ needs to be in a pristine state for tests
53 # to work properly.
54 if '__warningregistry__' in globals():
55 del globals()['__warningregistry__']
56 if hasattr(warning_tests, '__warningregistry__'):
57 del warning_tests.__warningregistry__
58 if hasattr(sys, '__warningregistry__'):
59 del sys.__warningregistry__
60 # The 'warnings' module must be explicitly set so that the proper
61 # interaction between _warnings and 'warnings' can be controlled.
62 sys.modules['warnings'] = self.module
63 super(BaseTest, self).setUp()
64
65 def tearDown(self):
66 sys.modules['warnings'] = original_warnings
67 super(BaseTest, self).tearDown()
68
69
70class FilterTests(object):
71
72 """Testing the filtering functionality."""
Brett Cannone9746892008-04-12 23:44:07 +000073
74 def test_error(self):
75 with test_support.catch_warning(self.module) as w:
76 self.module.resetwarnings()
77 self.module.filterwarnings("error", category=UserWarning)
78 self.assertRaises(UserWarning, self.module.warn,
79 "FilterTests.test_error")
80
81 def test_ignore(self):
82 with test_support.catch_warning(self.module) as w:
83 self.module.resetwarnings()
84 self.module.filterwarnings("ignore", category=UserWarning)
85 self.module.warn("FilterTests.test_ignore", UserWarning)
86 self.assert_(not w.message)
87
88 def test_always(self):
89 with test_support.catch_warning(self.module) as w:
90 self.module.resetwarnings()
91 self.module.filterwarnings("always", category=UserWarning)
92 message = "FilterTests.test_always"
93 self.module.warn(message, UserWarning)
94 self.assert_(message, w.message)
95 w.message = None # Reset.
96 self.module.warn(message, UserWarning)
97 self.assert_(w.message, message)
98
99 def test_default(self):
100 with test_support.catch_warning(self.module) as w:
101 self.module.resetwarnings()
102 self.module.filterwarnings("default", category=UserWarning)
103 message = UserWarning("FilterTests.test_default")
104 for x in xrange(2):
105 self.module.warn(message, UserWarning)
106 if x == 0:
107 self.assertEquals(w.message, message)
108 w.reset()
109 elif x == 1:
110 self.assert_(not w.message, "unexpected warning: " + str(w))
111 else:
112 raise ValueError("loop variant unhandled")
113
114 def test_module(self):
115 with test_support.catch_warning(self.module) as w:
116 self.module.resetwarnings()
117 self.module.filterwarnings("module", category=UserWarning)
118 message = UserWarning("FilterTests.test_module")
119 self.module.warn(message, UserWarning)
120 self.assertEquals(w.message, message)
121 w.reset()
122 self.module.warn(message, UserWarning)
123 self.assert_(not w.message, "unexpected message: " + str(w))
124
125 def test_once(self):
126 with test_support.catch_warning(self.module) as w:
127 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)
132 self.assertEquals(w.message, message)
133 w.reset()
134 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
135 13)
136 self.assert_(not w.message)
137 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
138 42)
139 self.assert_(not w.message)
140
141 def test_inheritance(self):
142 with test_support.catch_warning(self.module) as w:
143 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):
149 with test_support.catch_warning(self.module) as w:
150 self.module.resetwarnings()
151 self.module.filterwarnings("ignore", category=UserWarning)
152 self.module.filterwarnings("error", category=UserWarning,
153 append=True)
154 w.reset()
155 try:
156 self.module.warn("FilterTests.test_ordering", UserWarning)
157 except UserWarning:
158 self.fail("order handling for actions failed")
159 self.assert_(not w.message)
160
161 def test_filterwarnings(self):
162 # Test filterwarnings().
163 # Implicitly also tests resetwarnings().
164 with test_support.catch_warning(self.module) as w:
165 self.module.filterwarnings("error", "", Warning, "", 0)
166 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
167
168 self.module.resetwarnings()
169 text = 'handle normally'
170 self.module.warn(text)
171 self.assertEqual(str(w.message), text)
172 self.assert_(w.category is UserWarning)
173
174 self.module.filterwarnings("ignore", "", Warning, "", 0)
175 text = 'filtered out'
176 self.module.warn(text)
177 self.assertNotEqual(str(w.message), text)
178
179 self.module.resetwarnings()
180 self.module.filterwarnings("error", "hex*", Warning, "", 0)
181 self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
182 text = 'nonmatching text'
183 self.module.warn(text)
184 self.assertEqual(str(w.message), text)
185 self.assert_(w.category is UserWarning)
186
Brett Cannon667bb4f2008-04-13 02:42:36 +0000187class CFilterTests(BaseTest, FilterTests):
Brett Cannone9746892008-04-12 23:44:07 +0000188 module = c_warnings
189
Brett Cannon667bb4f2008-04-13 02:42:36 +0000190class PyFilterTests(BaseTest, FilterTests):
Brett Cannone9746892008-04-12 23:44:07 +0000191 module = py_warnings
192
193
194class WarnTests(unittest.TestCase):
195
196 """Test warnings.warn() and warnings.warn_explicit()."""
197
198 def test_message(self):
199 with test_support.catch_warning(self.module) as w:
Walter Dörwalde6dae6c2007-04-03 18:33:29 +0000200 for i in range(4):
Brett Cannone9746892008-04-12 23:44:07 +0000201 text = 'multi %d' %i # Different text on each call.
202 self.module.warn(text)
Walter Dörwalde6dae6c2007-04-03 18:33:29 +0000203 self.assertEqual(str(w.message), text)
204 self.assert_(w.category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000205
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000206 def test_filename(self):
Brett Cannone9746892008-04-12 23:44:07 +0000207 with warnings_state(self.module):
208 with test_support.catch_warning(self.module) as w:
209 warning_tests.inner("spam1")
210 self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
211 warning_tests.outer("spam2")
212 self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000213
214 def test_stacklevel(self):
215 # Test stacklevel argument
216 # make sure all messages are different, so the warning won't be skipped
Brett Cannone9746892008-04-12 23:44:07 +0000217 with warnings_state(self.module):
218 with test_support.catch_warning(self.module) as w:
219 warning_tests.inner("spam3", stacklevel=1)
220 self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
221 warning_tests.outer("spam4", stacklevel=1)
222 self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000223
Brett Cannone9746892008-04-12 23:44:07 +0000224 warning_tests.inner("spam5", stacklevel=2)
225 self.assertEqual(os.path.basename(w.filename), "test_warnings.py")
226 warning_tests.outer("spam6", stacklevel=2)
227 self.assertEqual(os.path.basename(w.filename), "warning_tests.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000228
Brett Cannone9746892008-04-12 23:44:07 +0000229 warning_tests.inner("spam7", stacklevel=9999)
230 self.assertEqual(os.path.basename(w.filename), "sys")
231
232
Brett Cannon667bb4f2008-04-13 02:42:36 +0000233class CWarnTests(BaseTest, WarnTests):
Brett Cannone9746892008-04-12 23:44:07 +0000234 module = c_warnings
235
Brett Cannon667bb4f2008-04-13 02:42:36 +0000236class PyWarnTests(BaseTest, WarnTests):
Brett Cannone9746892008-04-12 23:44:07 +0000237 module = py_warnings
238
239
240class WCmdLineTests(unittest.TestCase):
241
242 def test_improper_input(self):
243 # Uses the private _setoption() function to test the parsing
244 # of command-line warning arguments
245 with test_support.catch_warning(self.module):
246 self.assertRaises(self.module._OptionError,
247 self.module._setoption, '1:2:3:4:5:6')
248 self.assertRaises(self.module._OptionError,
249 self.module._setoption, 'bogus::Warning')
250 self.assertRaises(self.module._OptionError,
251 self.module._setoption, 'ignore:2::4:-5')
252 self.module._setoption('error::Warning::0')
253 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
254
Brett Cannon667bb4f2008-04-13 02:42:36 +0000255class CWCmdLineTests(BaseTest, WCmdLineTests):
Brett Cannone9746892008-04-12 23:44:07 +0000256 module = c_warnings
257
Brett Cannon667bb4f2008-04-13 02:42:36 +0000258class PyWCmdLineTests(BaseTest, WCmdLineTests):
Brett Cannone9746892008-04-12 23:44:07 +0000259 module = py_warnings
260
261
Brett Cannon667bb4f2008-04-13 02:42:36 +0000262class _WarningsTests(BaseTest):
Brett Cannone9746892008-04-12 23:44:07 +0000263
264 """Tests specific to the _warnings module."""
265
266 module = c_warnings
267
268 def test_filter(self):
269 # Everything should function even if 'filters' is not in warnings.
270 with test_support.catch_warning(self.module) as w:
271 self.module.filterwarnings("error", "", Warning, "", 0)
272 self.assertRaises(UserWarning, self.module.warn,
273 'convert to error')
274 del self.module.filters
275 self.assertRaises(UserWarning, self.module.warn,
276 'convert to error')
277
278 def test_onceregistry(self):
279 # Replacing or removing the onceregistry should be okay.
280 global __warningregistry__
281 message = UserWarning('onceregistry test')
282 try:
283 original_registry = self.module.onceregistry
284 __warningregistry__ = {}
285 with test_support.catch_warning(self.module) as w:
286 self.module.resetwarnings()
287 self.module.filterwarnings("once", category=UserWarning)
288 self.module.warn_explicit(message, UserWarning, "file", 42)
289 self.failUnlessEqual(w.message, message)
290 w.reset()
291 self.module.warn_explicit(message, UserWarning, "file", 42)
292 self.assert_(not w.message)
293 # Test the resetting of onceregistry.
294 self.module.onceregistry = {}
295 __warningregistry__ = {}
296 self.module.warn('onceregistry test')
297 self.failUnlessEqual(w.message.args, message.args)
298 # Removal of onceregistry is okay.
299 w.reset()
300 del self.module.onceregistry
301 __warningregistry__ = {}
302 self.module.warn_explicit(message, UserWarning, "file", 42)
303 self.failUnless(not w.message)
304 finally:
305 self.module.onceregistry = original_registry
306
307 def test_showwarning_missing(self):
308 # Test that showwarning() missing is okay.
309 text = 'del showwarning test'
310 with test_support.catch_warning(self.module):
311 self.module.filterwarnings("always", category=UserWarning)
312 del self.module.showwarning
313 with test_support.captured_output('stderr') as stream:
314 self.module.warn(text)
315 result = stream.getvalue()
316 self.failUnless(text in result)
317
318 def test_show_warning_output(self):
319 # With showarning() missing, make sure that output is okay.
320 text = 'test show_warning'
321 with test_support.catch_warning(self.module):
322 self.module.filterwarnings("always", category=UserWarning)
323 del self.module.showwarning
324 with test_support.captured_output('stderr') as stream:
325 warning_tests.inner(text)
326 result = stream.getvalue()
327 self.failUnlessEqual(result.count('\n'), 2,
328 "Too many newlines in %r" % result)
329 first_line, second_line = result.split('\n', 1)
330 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Brett Cannonc4774272008-04-13 17:41:31 +0000331 first_line_parts = first_line.rsplit(':', 3)
Brett Cannon25bb8182008-04-13 17:09:43 +0000332 path, line, warning_class, message = first_line_parts
Brett Cannone9746892008-04-12 23:44:07 +0000333 line = int(line)
334 self.failUnlessEqual(expected_file, path)
335 self.failUnlessEqual(warning_class, ' ' + UserWarning.__name__)
336 self.failUnlessEqual(message, ' ' + text)
337 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
338 assert expected_line
339 self.failUnlessEqual(second_line, expected_line)
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000340
Brett Cannon53ab5b72006-06-22 16:49:14 +0000341
Brett Cannon905c31c2007-12-20 10:09:52 +0000342class WarningsDisplayTests(unittest.TestCase):
343
Brett Cannone9746892008-04-12 23:44:07 +0000344 """Test the displaying of warnings and the ability to overload functions
345 related to displaying warnings."""
346
Brett Cannon905c31c2007-12-20 10:09:52 +0000347 def test_formatwarning(self):
348 message = "msg"
349 category = Warning
350 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
351 line_num = 3
352 file_line = linecache.getline(file_name, line_num).strip()
Brett Cannone9746892008-04-12 23:44:07 +0000353 format = "%s:%s: %s: %s\n %s\n"
354 expect = format % (file_name, line_num, category.__name__, message,
355 file_line)
356 self.failUnlessEqual(expect, self.module.formatwarning(message,
357 category, file_name, line_num))
358 # Test the 'line' argument.
359 file_line += " for the win!"
360 expect = format % (file_name, line_num, category.__name__, message,
361 file_line)
362 self.failUnlessEqual(expect, self.module.formatwarning(message,
363 category, file_name, line_num, file_line))
Brett Cannon905c31c2007-12-20 10:09:52 +0000364
365 def test_showwarning(self):
366 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
367 line_num = 3
368 expected_file_line = linecache.getline(file_name, line_num).strip()
369 message = 'msg'
370 category = Warning
371 file_object = StringIO.StringIO()
Brett Cannone9746892008-04-12 23:44:07 +0000372 expect = self.module.formatwarning(message, category, file_name,
373 line_num)
374 self.module.showwarning(message, category, file_name, line_num,
Brett Cannon905c31c2007-12-20 10:09:52 +0000375 file_object)
376 self.failUnlessEqual(file_object.getvalue(), expect)
Brett Cannone9746892008-04-12 23:44:07 +0000377 # Test 'line' argument.
378 expected_file_line += "for the win!"
379 expect = self.module.formatwarning(message, category, file_name,
380 line_num, expected_file_line)
381 file_object = StringIO.StringIO()
382 self.module.showwarning(message, category, file_name, line_num,
383 file_object, expected_file_line)
384 self.failUnlessEqual(expect, file_object.getvalue())
385
Brett Cannon667bb4f2008-04-13 02:42:36 +0000386class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
Brett Cannone9746892008-04-12 23:44:07 +0000387 module = c_warnings
388
Brett Cannon667bb4f2008-04-13 02:42:36 +0000389class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
Brett Cannone9746892008-04-12 23:44:07 +0000390 module = py_warnings
Brett Cannon905c31c2007-12-20 10:09:52 +0000391
392
Brett Cannone9746892008-04-12 23:44:07 +0000393def test_main():
Amaury Forgeot d'Arc607bff12008-04-18 23:31:33 +0000394 py_warnings.onceregistry.clear()
395 c_warnings.onceregistry.clear()
Brett Cannon667bb4f2008-04-13 02:42:36 +0000396 test_support.run_unittest(CFilterTests,
397 PyFilterTests,
398 CWarnTests,
399 PyWarnTests,
Brett Cannone9746892008-04-12 23:44:07 +0000400 CWCmdLineTests, PyWCmdLineTests,
401 _WarningsTests,
402 CWarningsDisplayTests, PyWarningsDisplayTests,
403 )
404
405
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000406if __name__ == "__main__":
Brett Cannone9746892008-04-12 23:44:07 +0000407 test_main()