blob: cd3288b6b596e95b7bdb35897b2b9e25fac618ce [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
Antoine Pitrou69994412014-04-29 00:56:08 +02008from test.script_helper import assert_python_ok, assert_python_failure
Jeremy Hylton85014662003-07-11 15:37:59 +00009
Guido van Rossum805365e2007-05-07 22:24:25 +000010from test import warning_tests
Jeremy Hylton85014662003-07-11 15:37:59 +000011
Christian Heimes33fe8092008-04-13 13:53:33 +000012import warnings as original_warnings
Jeremy Hylton85014662003-07-11 15:37:59 +000013
Nick Coghlan47384702009-04-22 16:13:36 +000014py_warnings = support.import_fresh_module('warnings', blocked=['_warnings'])
15c_warnings = support.import_fresh_module('warnings', fresh=['_warnings'])
Christian Heimes33fe8092008-04-13 13:53:33 +000016
17@contextmanager
18def warnings_state(module):
19 """Use a specific warnings implementation in warning_tests."""
20 global __warningregistry__
21 for to_clear in (sys, warning_tests):
22 try:
23 to_clear.__warningregistry__.clear()
24 except AttributeError:
25 pass
26 try:
27 __warningregistry__.clear()
28 except NameError:
29 pass
30 original_warnings = warning_tests.warnings
Florent Xiclunafd1b0932010-03-28 00:25:02 +000031 original_filters = module.filters
Christian Heimes33fe8092008-04-13 13:53:33 +000032 try:
Florent Xiclunafd1b0932010-03-28 00:25:02 +000033 module.filters = original_filters[:]
34 module.simplefilter("once")
Christian Heimes33fe8092008-04-13 13:53:33 +000035 warning_tests.warnings = module
36 yield
37 finally:
38 warning_tests.warnings = original_warnings
Florent Xiclunafd1b0932010-03-28 00:25:02 +000039 module.filters = original_filters
Christian Heimes33fe8092008-04-13 13:53:33 +000040
41
Ezio Melotti2688e812013-01-10 06:52:23 +020042class BaseTest:
Christian Heimes33fe8092008-04-13 13:53:33 +000043
44 """Basic bookkeeping required for testing."""
45
46 def setUp(self):
47 # The __warningregistry__ needs to be in a pristine state for tests
48 # to work properly.
49 if '__warningregistry__' in globals():
50 del globals()['__warningregistry__']
51 if hasattr(warning_tests, '__warningregistry__'):
52 del warning_tests.__warningregistry__
53 if hasattr(sys, '__warningregistry__'):
54 del sys.__warningregistry__
55 # The 'warnings' module must be explicitly set so that the proper
56 # interaction between _warnings and 'warnings' can be controlled.
57 sys.modules['warnings'] = self.module
58 super(BaseTest, self).setUp()
59
60 def tearDown(self):
61 sys.modules['warnings'] = original_warnings
62 super(BaseTest, self).tearDown()
63
64
Ezio Melotti2688e812013-01-10 06:52:23 +020065class FilterTests(BaseTest):
Christian Heimes33fe8092008-04-13 13:53:33 +000066
67 """Testing the filtering functionality."""
68
69 def test_error(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000070 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000071 self.module.resetwarnings()
72 self.module.filterwarnings("error", category=UserWarning)
73 self.assertRaises(UserWarning, self.module.warn,
74 "FilterTests.test_error")
75
76 def test_ignore(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000077 with original_warnings.catch_warnings(record=True,
78 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000079 self.module.resetwarnings()
80 self.module.filterwarnings("ignore", category=UserWarning)
81 self.module.warn("FilterTests.test_ignore", UserWarning)
Ezio Melottib3aedd42010-11-20 19:04:17 +000082 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +000083
84 def test_always(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000085 with original_warnings.catch_warnings(record=True,
86 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000087 self.module.resetwarnings()
88 self.module.filterwarnings("always", category=UserWarning)
89 message = "FilterTests.test_always"
90 self.module.warn(message, UserWarning)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000091 self.assertTrue(message, w[-1].message)
Christian Heimes33fe8092008-04-13 13:53:33 +000092 self.module.warn(message, UserWarning)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000093 self.assertTrue(w[-1].message, message)
Christian Heimes33fe8092008-04-13 13:53:33 +000094
95 def test_default(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000096 with original_warnings.catch_warnings(record=True,
97 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000098 self.module.resetwarnings()
99 self.module.filterwarnings("default", category=UserWarning)
100 message = UserWarning("FilterTests.test_default")
101 for x in range(2):
102 self.module.warn(message, UserWarning)
103 if x == 0:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000104 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000105 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000106 elif x == 1:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000107 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000108 else:
109 raise ValueError("loop variant unhandled")
110
111 def test_module(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000112 with original_warnings.catch_warnings(record=True,
113 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000114 self.module.resetwarnings()
115 self.module.filterwarnings("module", category=UserWarning)
116 message = UserWarning("FilterTests.test_module")
117 self.module.warn(message, UserWarning)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000118 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000119 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000120 self.module.warn(message, UserWarning)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000121 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000122
123 def test_once(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000124 with original_warnings.catch_warnings(record=True,
125 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000126 self.module.resetwarnings()
127 self.module.filterwarnings("once", category=UserWarning)
128 message = UserWarning("FilterTests.test_once")
129 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
130 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000131 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000132 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000133 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
134 13)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000135 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000136 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
137 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000138 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000139
140 def test_inheritance(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000141 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000142 self.module.resetwarnings()
143 self.module.filterwarnings("error", category=Warning)
144 self.assertRaises(UserWarning, self.module.warn,
145 "FilterTests.test_inheritance", UserWarning)
146
147 def test_ordering(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000148 with original_warnings.catch_warnings(record=True,
149 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000150 self.module.resetwarnings()
151 self.module.filterwarnings("ignore", category=UserWarning)
152 self.module.filterwarnings("error", category=UserWarning,
153 append=True)
Brett Cannon1cd02472008-09-09 01:52:27 +0000154 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000155 try:
156 self.module.warn("FilterTests.test_ordering", UserWarning)
157 except UserWarning:
158 self.fail("order handling for actions failed")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000159 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000160
161 def test_filterwarnings(self):
162 # Test filterwarnings().
163 # Implicitly also tests resetwarnings().
Brett Cannon1cd02472008-09-09 01:52:27 +0000164 with original_warnings.catch_warnings(record=True,
165 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000166 self.module.filterwarnings("error", "", Warning, "", 0)
167 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
168
169 self.module.resetwarnings()
170 text = 'handle normally'
171 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000172 self.assertEqual(str(w[-1].message), text)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000173 self.assertTrue(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000174
175 self.module.filterwarnings("ignore", "", Warning, "", 0)
176 text = 'filtered out'
177 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000178 self.assertNotEqual(str(w[-1].message), text)
Christian Heimes33fe8092008-04-13 13:53:33 +0000179
180 self.module.resetwarnings()
181 self.module.filterwarnings("error", "hex*", Warning, "", 0)
182 self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
183 text = 'nonmatching text'
184 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000185 self.assertEqual(str(w[-1].message), text)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000186 self.assertTrue(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000187
Ezio Melotti2688e812013-01-10 06:52:23 +0200188class CFilterTests(FilterTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000189 module = c_warnings
190
Ezio Melotti2688e812013-01-10 06:52:23 +0200191class PyFilterTests(FilterTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000192 module = py_warnings
193
194
Ezio Melotti2688e812013-01-10 06:52:23 +0200195class WarnTests(BaseTest):
Christian Heimes33fe8092008-04-13 13:53:33 +0000196
197 """Test warnings.warn() and warnings.warn_explicit()."""
198
199 def test_message(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000200 with original_warnings.catch_warnings(record=True,
201 module=self.module) as w:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000202 self.module.simplefilter("once")
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)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000207 self.assertTrue(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:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000215 self.module.simplefilter("once")
Brett Cannon54bd41d2008-09-02 04:01:42 +0000216 self.module.warn(ob)
217 # Don't directly compare objects since
218 # ``Warning() != Warning()``.
Ezio Melottib3aedd42010-11-20 19:04:17 +0000219 self.assertEqual(str(w[-1].message), str(UserWarning(ob)))
Brett Cannon54bd41d2008-09-02 04:01:42 +0000220
Guido van Rossumd8faa362007-04-27 19:54:29 +0000221 def test_filename(self):
Christian Heimes33fe8092008-04-13 13:53:33 +0000222 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000223 with original_warnings.catch_warnings(record=True,
224 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000225 warning_tests.inner("spam1")
Brett Cannon1cd02472008-09-09 01:52:27 +0000226 self.assertEqual(os.path.basename(w[-1].filename),
227 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000228 warning_tests.outer("spam2")
Brett Cannon1cd02472008-09-09 01:52:27 +0000229 self.assertEqual(os.path.basename(w[-1].filename),
230 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000231
232 def test_stacklevel(self):
233 # Test stacklevel argument
234 # make sure all messages are different, so the warning won't be skipped
Christian Heimes33fe8092008-04-13 13:53:33 +0000235 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000236 with original_warnings.catch_warnings(record=True,
237 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000238 warning_tests.inner("spam3", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000239 self.assertEqual(os.path.basename(w[-1].filename),
240 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000241 warning_tests.outer("spam4", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000242 self.assertEqual(os.path.basename(w[-1].filename),
243 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000244
Christian Heimes33fe8092008-04-13 13:53:33 +0000245 warning_tests.inner("spam5", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000246 self.assertEqual(os.path.basename(w[-1].filename),
247 "test_warnings.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000248 warning_tests.outer("spam6", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000249 self.assertEqual(os.path.basename(w[-1].filename),
250 "warning_tests.py")
Christian Heimes5d8da202008-05-06 13:58:24 +0000251 warning_tests.outer("spam6.5", stacklevel=3)
Brett Cannon1cd02472008-09-09 01:52:27 +0000252 self.assertEqual(os.path.basename(w[-1].filename),
253 "test_warnings.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000254
Christian Heimes33fe8092008-04-13 13:53:33 +0000255 warning_tests.inner("spam7", stacklevel=9999)
Brett Cannon1cd02472008-09-09 01:52:27 +0000256 self.assertEqual(os.path.basename(w[-1].filename),
257 "sys")
Christian Heimes33fe8092008-04-13 13:53:33 +0000258
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000259 def test_missing_filename_not_main(self):
260 # If __file__ is not specified and __main__ is not the module name,
261 # then __file__ should be set to the module name.
262 filename = warning_tests.__file__
263 try:
264 del warning_tests.__file__
265 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000266 with original_warnings.catch_warnings(record=True,
267 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000268 warning_tests.inner("spam8", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000269 self.assertEqual(w[-1].filename, warning_tests.__name__)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000270 finally:
271 warning_tests.__file__ = filename
272
Serhiy Storchaka43767632013-11-03 21:31:38 +0200273 @unittest.skipUnless(hasattr(sys, 'argv'), 'test needs sys.argv')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000274 def test_missing_filename_main_with_argv(self):
275 # If __file__ is not specified and the caller is __main__ and sys.argv
276 # exists, then use sys.argv[0] as the file.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000277 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
Victor Stinnera4c704b2013-10-29 23:43:41 +0100332 def test_warn_explicit_non_ascii_filename(self):
333 with original_warnings.catch_warnings(record=True,
334 module=self.module) as w:
335 self.module.resetwarnings()
336 self.module.filterwarnings("always", category=UserWarning)
Victor Stinnerc0e07a32013-10-29 23:58:05 +0100337 for filename in ("nonascii\xe9\u20ac", "surrogate\udc80"):
338 try:
339 os.fsencode(filename)
340 except UnicodeEncodeError:
341 continue
342 self.module.warn_explicit("text", UserWarning, filename, 1)
343 self.assertEqual(w[-1].filename, filename)
Victor Stinnera4c704b2013-10-29 23:43:41 +0100344
Brett Cannondb734912008-06-27 00:52:15 +0000345 def test_warn_explicit_type_errors(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200346 # warn_explicit() should error out gracefully if it is given objects
Brett Cannondb734912008-06-27 00:52:15 +0000347 # of the wrong types.
348 # lineno is expected to be an integer.
349 self.assertRaises(TypeError, self.module.warn_explicit,
350 None, UserWarning, None, None)
351 # Either 'message' needs to be an instance of Warning or 'category'
352 # needs to be a subclass.
353 self.assertRaises(TypeError, self.module.warn_explicit,
354 None, None, None, 1)
355 # 'registry' must be a dict or None.
356 self.assertRaises((TypeError, AttributeError),
357 self.module.warn_explicit,
358 None, Warning, None, 1, registry=42)
359
Hirokazu Yamamoto1c0c0032009-07-17 06:55:42 +0000360 def test_bad_str(self):
361 # issue 6415
362 # Warnings instance with a bad format string for __str__ should not
363 # trigger a bus error.
364 class BadStrWarning(Warning):
365 """Warning with a bad format string for __str__."""
366 def __str__(self):
367 return ("A bad formatted string %(err)" %
368 {"err" : "there is no %(err)s"})
369
370 with self.assertRaises(ValueError):
371 self.module.warn(BadStrWarning())
372
Berker Peksagd8089e02014-07-11 19:50:25 +0300373 def test_warning_classes(self):
374 class MyWarningClass(Warning):
375 pass
376
377 class NonWarningSubclass:
378 pass
379
380 # passing a non-subclass of Warning should raise a TypeError
381 with self.assertRaises(TypeError) as cm:
382 self.module.warn('bad warning category', '')
383 self.assertIn('category must be a Warning subclass, not ',
384 str(cm.exception))
385
386 with self.assertRaises(TypeError) as cm:
387 self.module.warn('bad warning category', NonWarningSubclass)
388 self.assertIn('category must be a Warning subclass, not ',
389 str(cm.exception))
390
391 # check that warning instances also raise a TypeError
392 with self.assertRaises(TypeError) as cm:
393 self.module.warn('bad warning category', MyWarningClass())
394 self.assertIn('category must be a Warning subclass, not ',
395 str(cm.exception))
396
397 with self.assertWarns(MyWarningClass) as cm:
398 self.module.warn('good warning category', MyWarningClass)
399 self.assertEqual('good warning category', str(cm.warning))
400
401 with self.assertWarns(UserWarning) as cm:
402 self.module.warn('good warning category', None)
403 self.assertEqual('good warning category', str(cm.warning))
404
405 with self.assertWarns(MyWarningClass) as cm:
406 self.module.warn('good warning category', MyWarningClass)
407 self.assertIsInstance(cm.warning, Warning)
Hirokazu Yamamoto1c0c0032009-07-17 06:55:42 +0000408
Ezio Melotti2688e812013-01-10 06:52:23 +0200409class CWarnTests(WarnTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000410 module = c_warnings
411
Nick Coghlanfce769e2009-04-11 14:30:59 +0000412 # As an early adopter, we sanity check the
413 # test.support.import_fresh_module utility function
414 def test_accelerated(self):
415 self.assertFalse(original_warnings is self.module)
416 self.assertFalse(hasattr(self.module.warn, '__code__'))
417
Ezio Melotti2688e812013-01-10 06:52:23 +0200418class PyWarnTests(WarnTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000419 module = py_warnings
420
Nick Coghlanfce769e2009-04-11 14:30:59 +0000421 # As an early adopter, we sanity check the
422 # test.support.import_fresh_module utility function
423 def test_pure_python(self):
424 self.assertFalse(original_warnings is self.module)
425 self.assertTrue(hasattr(self.module.warn, '__code__'))
426
Christian Heimes33fe8092008-04-13 13:53:33 +0000427
Ezio Melotti2688e812013-01-10 06:52:23 +0200428class WCmdLineTests(BaseTest):
Christian Heimes33fe8092008-04-13 13:53:33 +0000429
430 def test_improper_input(self):
431 # Uses the private _setoption() function to test the parsing
432 # of command-line warning arguments
Brett Cannon1cd02472008-09-09 01:52:27 +0000433 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000434 self.assertRaises(self.module._OptionError,
435 self.module._setoption, '1:2:3:4:5:6')
436 self.assertRaises(self.module._OptionError,
437 self.module._setoption, 'bogus::Warning')
438 self.assertRaises(self.module._OptionError,
439 self.module._setoption, 'ignore:2::4:-5')
440 self.module._setoption('error::Warning::0')
441 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
442
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000443 def test_improper_option(self):
444 # Same as above, but check that the message is printed out when
445 # the interpreter is executed. This also checks that options are
446 # actually parsed at all.
447 rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")
448 self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)
449
450 def test_warnings_bootstrap(self):
451 # Check that the warnings module does get loaded when -W<some option>
452 # is used (see issue #10372 for an example of silent bootstrap failure).
453 rc, out, err = assert_python_ok("-Wi", "-c",
454 "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
455 # '-Wi' was observed
456 self.assertFalse(out.strip())
457 self.assertNotIn(b'RuntimeWarning', err)
458
Ezio Melotti2688e812013-01-10 06:52:23 +0200459class CWCmdLineTests(WCmdLineTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000460 module = c_warnings
461
Ezio Melotti2688e812013-01-10 06:52:23 +0200462class PyWCmdLineTests(WCmdLineTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000463 module = py_warnings
464
465
Ezio Melotti2688e812013-01-10 06:52:23 +0200466class _WarningsTests(BaseTest, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000467
468 """Tests specific to the _warnings module."""
469
470 module = c_warnings
471
472 def test_filter(self):
473 # Everything should function even if 'filters' is not in warnings.
Brett Cannon1cd02472008-09-09 01:52:27 +0000474 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000475 self.module.filterwarnings("error", "", Warning, "", 0)
476 self.assertRaises(UserWarning, self.module.warn,
477 'convert to error')
478 del self.module.filters
479 self.assertRaises(UserWarning, self.module.warn,
480 'convert to error')
481
482 def test_onceregistry(self):
483 # Replacing or removing the onceregistry should be okay.
484 global __warningregistry__
485 message = UserWarning('onceregistry test')
486 try:
487 original_registry = self.module.onceregistry
488 __warningregistry__ = {}
Brett Cannon1cd02472008-09-09 01:52:27 +0000489 with original_warnings.catch_warnings(record=True,
490 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000491 self.module.resetwarnings()
492 self.module.filterwarnings("once", category=UserWarning)
493 self.module.warn_explicit(message, UserWarning, "file", 42)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000494 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000495 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000496 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000497 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000498 # Test the resetting of onceregistry.
499 self.module.onceregistry = {}
500 __warningregistry__ = {}
501 self.module.warn('onceregistry test')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000502 self.assertEqual(w[-1].message.args, message.args)
Christian Heimes33fe8092008-04-13 13:53:33 +0000503 # Removal of onceregistry is okay.
Brett Cannon1cd02472008-09-09 01:52:27 +0000504 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000505 del self.module.onceregistry
506 __warningregistry__ = {}
507 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000508 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000509 finally:
510 self.module.onceregistry = original_registry
511
Brett Cannon0759dd62009-04-01 18:13:07 +0000512 def test_default_action(self):
513 # Replacing or removing defaultaction should be okay.
514 message = UserWarning("defaultaction test")
515 original = self.module.defaultaction
516 try:
517 with original_warnings.catch_warnings(record=True,
518 module=self.module) as w:
519 self.module.resetwarnings()
520 registry = {}
521 self.module.warn_explicit(message, UserWarning, "<test>", 42,
522 registry=registry)
523 self.assertEqual(w[-1].message, message)
524 self.assertEqual(len(w), 1)
525 self.assertEqual(len(registry), 1)
526 del w[:]
527 # Test removal.
528 del self.module.defaultaction
529 __warningregistry__ = {}
530 registry = {}
531 self.module.warn_explicit(message, UserWarning, "<test>", 43,
532 registry=registry)
533 self.assertEqual(w[-1].message, message)
534 self.assertEqual(len(w), 1)
535 self.assertEqual(len(registry), 1)
536 del w[:]
537 # Test setting.
538 self.module.defaultaction = "ignore"
539 __warningregistry__ = {}
540 registry = {}
541 self.module.warn_explicit(message, UserWarning, "<test>", 44,
542 registry=registry)
543 self.assertEqual(len(w), 0)
544 finally:
545 self.module.defaultaction = original
546
Christian Heimes33fe8092008-04-13 13:53:33 +0000547 def test_showwarning_missing(self):
548 # Test that showwarning() missing is okay.
549 text = 'del showwarning test'
Brett Cannon1cd02472008-09-09 01:52:27 +0000550 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000551 self.module.filterwarnings("always", category=UserWarning)
552 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000553 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000554 self.module.warn(text)
555 result = stream.getvalue()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000556 self.assertIn(text, result)
Christian Heimes33fe8092008-04-13 13:53:33 +0000557
Christian Heimes8dc226f2008-05-06 23:45:46 +0000558 def test_showwarning_not_callable(self):
Brett Cannonfcc05272009-04-01 20:27:29 +0000559 with original_warnings.catch_warnings(module=self.module):
560 self.module.filterwarnings("always", category=UserWarning)
Brett Cannon52a7d982011-07-17 19:17:55 -0700561 self.module.showwarning = print
562 with support.captured_output('stdout'):
563 self.module.warn('Warning!')
Brett Cannonfcc05272009-04-01 20:27:29 +0000564 self.module.showwarning = 23
Brett Cannon52a7d982011-07-17 19:17:55 -0700565 self.assertRaises(TypeError, self.module.warn, "Warning!")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000566
Christian Heimes33fe8092008-04-13 13:53:33 +0000567 def test_show_warning_output(self):
568 # With showarning() missing, make sure that output is okay.
569 text = 'test show_warning'
Brett Cannon1cd02472008-09-09 01:52:27 +0000570 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000571 self.module.filterwarnings("always", category=UserWarning)
572 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000573 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000574 warning_tests.inner(text)
575 result = stream.getvalue()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000576 self.assertEqual(result.count('\n'), 2,
Christian Heimes33fe8092008-04-13 13:53:33 +0000577 "Too many newlines in %r" % result)
578 first_line, second_line = result.split('\n', 1)
579 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Neal Norwitz32dde222008-04-15 06:43:13 +0000580 first_line_parts = first_line.rsplit(':', 3)
581 path, line, warning_class, message = first_line_parts
Christian Heimes33fe8092008-04-13 13:53:33 +0000582 line = int(line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000583 self.assertEqual(expected_file, path)
584 self.assertEqual(warning_class, ' ' + UserWarning.__name__)
585 self.assertEqual(message, ' ' + text)
Christian Heimes33fe8092008-04-13 13:53:33 +0000586 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
587 assert expected_line
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000588 self.assertEqual(second_line, expected_line)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000589
Victor Stinner8b0508e2011-07-04 02:43:09 +0200590 def test_filename_none(self):
591 # issue #12467: race condition if a warning is emitted at shutdown
592 globals_dict = globals()
593 oldfile = globals_dict['__file__']
594 try:
Brett Cannon52a7d982011-07-17 19:17:55 -0700595 catch = original_warnings.catch_warnings(record=True,
596 module=self.module)
597 with catch as w:
Victor Stinner8b0508e2011-07-04 02:43:09 +0200598 self.module.filterwarnings("always", category=UserWarning)
599 globals_dict['__file__'] = None
600 original_warnings.warn('test', UserWarning)
Brett Cannon52a7d982011-07-17 19:17:55 -0700601 self.assertTrue(len(w))
Victor Stinner8b0508e2011-07-04 02:43:09 +0200602 finally:
603 globals_dict['__file__'] = oldfile
604
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000605
Ezio Melotti2688e812013-01-10 06:52:23 +0200606class WarningsDisplayTests(BaseTest):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000607
Christian Heimes33fe8092008-04-13 13:53:33 +0000608 """Test the displaying of warnings and the ability to overload functions
609 related to displaying warnings."""
610
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000611 def test_formatwarning(self):
612 message = "msg"
613 category = Warning
614 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
615 line_num = 3
616 file_line = linecache.getline(file_name, line_num).strip()
Christian Heimes33fe8092008-04-13 13:53:33 +0000617 format = "%s:%s: %s: %s\n %s\n"
618 expect = format % (file_name, line_num, category.__name__, message,
619 file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000620 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000621 category, file_name, line_num))
622 # Test the 'line' argument.
623 file_line += " for the win!"
624 expect = format % (file_name, line_num, category.__name__, message,
625 file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000626 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000627 category, file_name, line_num, file_line))
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000628
629 def test_showwarning(self):
630 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
631 line_num = 3
632 expected_file_line = linecache.getline(file_name, line_num).strip()
633 message = 'msg'
634 category = Warning
635 file_object = StringIO()
Christian Heimes33fe8092008-04-13 13:53:33 +0000636 expect = self.module.formatwarning(message, category, file_name,
637 line_num)
638 self.module.showwarning(message, category, file_name, line_num,
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000639 file_object)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000640 self.assertEqual(file_object.getvalue(), expect)
Christian Heimes33fe8092008-04-13 13:53:33 +0000641 # Test 'line' argument.
642 expected_file_line += "for the win!"
643 expect = self.module.formatwarning(message, category, file_name,
644 line_num, expected_file_line)
645 file_object = StringIO()
646 self.module.showwarning(message, category, file_name, line_num,
647 file_object, expected_file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000648 self.assertEqual(expect, file_object.getvalue())
Christian Heimes33fe8092008-04-13 13:53:33 +0000649
Ezio Melotti2688e812013-01-10 06:52:23 +0200650class CWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000651 module = c_warnings
652
Ezio Melotti2688e812013-01-10 06:52:23 +0200653class PyWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000654 module = py_warnings
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000655
Brett Cannon1cd02472008-09-09 01:52:27 +0000656
Brett Cannonec92e182008-09-02 02:46:59 +0000657class CatchWarningTests(BaseTest):
Nick Coghlanb1304932008-07-13 12:25:08 +0000658
Brett Cannonec92e182008-09-02 02:46:59 +0000659 """Test catch_warnings()."""
660
661 def test_catch_warnings_restore(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000662 wmod = self.module
663 orig_filters = wmod.filters
664 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000665 # Ensure both showwarning and filters are restored when recording
666 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlanb1304932008-07-13 12:25:08 +0000667 wmod.filters = wmod.showwarning = object()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000668 self.assertTrue(wmod.filters is orig_filters)
669 self.assertTrue(wmod.showwarning is orig_showwarning)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000670 # Same test, but with recording disabled
671 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlanb1304932008-07-13 12:25:08 +0000672 wmod.filters = wmod.showwarning = object()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000673 self.assertTrue(wmod.filters is orig_filters)
674 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000675
Brett Cannonec92e182008-09-02 02:46:59 +0000676 def test_catch_warnings_recording(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000677 wmod = self.module
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000678 # Ensure warnings are recorded when requested
679 with wmod.catch_warnings(module=wmod, record=True) as w:
Brett Cannonec92e182008-09-02 02:46:59 +0000680 self.assertEqual(w, [])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000681 self.assertTrue(type(w) is list)
Nick Coghlanb1304932008-07-13 12:25:08 +0000682 wmod.simplefilter("always")
683 wmod.warn("foo")
Brett Cannon1cd02472008-09-09 01:52:27 +0000684 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlanb1304932008-07-13 12:25:08 +0000685 wmod.warn("bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000686 self.assertEqual(str(w[-1].message), "bar")
Brett Cannonec92e182008-09-02 02:46:59 +0000687 self.assertEqual(str(w[0].message), "foo")
688 self.assertEqual(str(w[1].message), "bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000689 del w[:]
Brett Cannonec92e182008-09-02 02:46:59 +0000690 self.assertEqual(w, [])
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000691 # Ensure warnings are not recorded when not requested
Nick Coghlanb1304932008-07-13 12:25:08 +0000692 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000693 with wmod.catch_warnings(module=wmod, record=False) as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000694 self.assertTrue(w is None)
695 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000696
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000697 def test_catch_warnings_reentry_guard(self):
698 wmod = self.module
699 # Ensure catch_warnings is protected against incorrect usage
700 x = wmod.catch_warnings(module=wmod, record=True)
701 self.assertRaises(RuntimeError, x.__exit__)
702 with x:
703 self.assertRaises(RuntimeError, x.__enter__)
704 # Same test, but with recording disabled
705 x = wmod.catch_warnings(module=wmod, record=False)
706 self.assertRaises(RuntimeError, x.__exit__)
707 with x:
708 self.assertRaises(RuntimeError, x.__enter__)
709
710 def test_catch_warnings_defaults(self):
711 wmod = self.module
712 orig_filters = wmod.filters
713 orig_showwarning = wmod.showwarning
714 # Ensure default behaviour is not to record warnings
715 with wmod.catch_warnings(module=wmod) as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000716 self.assertTrue(w is None)
717 self.assertTrue(wmod.showwarning is orig_showwarning)
718 self.assertTrue(wmod.filters is not orig_filters)
719 self.assertTrue(wmod.filters is orig_filters)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000720 if wmod is sys.modules['warnings']:
721 # Ensure the default module is this one
722 with wmod.catch_warnings() as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000723 self.assertTrue(w is None)
724 self.assertTrue(wmod.showwarning is orig_showwarning)
725 self.assertTrue(wmod.filters is not orig_filters)
726 self.assertTrue(wmod.filters is orig_filters)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000727
728 def test_check_warnings(self):
729 # Explicit tests for the test.support convenience wrapper
730 wmod = self.module
Florent Xicluna53b506be2010-03-18 20:00:57 +0000731 if wmod is not sys.modules['warnings']:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600732 self.skipTest('module to test is not loaded warnings module')
Florent Xicluna53b506be2010-03-18 20:00:57 +0000733 with support.check_warnings(quiet=False) as w:
734 self.assertEqual(w.warnings, [])
735 wmod.simplefilter("always")
736 wmod.warn("foo")
737 self.assertEqual(str(w.message), "foo")
738 wmod.warn("bar")
739 self.assertEqual(str(w.message), "bar")
740 self.assertEqual(str(w.warnings[0].message), "foo")
741 self.assertEqual(str(w.warnings[1].message), "bar")
742 w.reset()
743 self.assertEqual(w.warnings, [])
744
745 with support.check_warnings():
746 # defaults to quiet=True without argument
747 pass
748 with support.check_warnings(('foo', UserWarning)):
749 wmod.warn("foo")
750
751 with self.assertRaises(AssertionError):
752 with support.check_warnings(('', RuntimeWarning)):
753 # defaults to quiet=False with argument
754 pass
755 with self.assertRaises(AssertionError):
756 with support.check_warnings(('foo', RuntimeWarning)):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000757 wmod.warn("foo")
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000758
Ezio Melotti2688e812013-01-10 06:52:23 +0200759class CCatchWarningTests(CatchWarningTests, unittest.TestCase):
Nick Coghlanb1304932008-07-13 12:25:08 +0000760 module = c_warnings
761
Ezio Melotti2688e812013-01-10 06:52:23 +0200762class PyCatchWarningTests(CatchWarningTests, unittest.TestCase):
Nick Coghlanb1304932008-07-13 12:25:08 +0000763 module = py_warnings
764
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000765
Philip Jenvey0805ca32010-04-07 04:04:10 +0000766class EnvironmentVariableTests(BaseTest):
767
768 def test_single_warning(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100769 rc, stdout, stderr = assert_python_ok("-c",
770 "import sys; sys.stdout.write(str(sys.warnoptions))",
771 PYTHONWARNINGS="ignore::DeprecationWarning")
772 self.assertEqual(stdout, b"['ignore::DeprecationWarning']")
Philip Jenvey0805ca32010-04-07 04:04:10 +0000773
774 def test_comma_separated_warnings(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100775 rc, stdout, stderr = assert_python_ok("-c",
776 "import sys; sys.stdout.write(str(sys.warnoptions))",
777 PYTHONWARNINGS="ignore::DeprecationWarning,ignore::UnicodeWarning")
778 self.assertEqual(stdout,
779 b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
Philip Jenvey0805ca32010-04-07 04:04:10 +0000780
781 def test_envvar_and_command_line(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100782 rc, stdout, stderr = assert_python_ok("-Wignore::UnicodeWarning", "-c",
783 "import sys; sys.stdout.write(str(sys.warnoptions))",
784 PYTHONWARNINGS="ignore::DeprecationWarning")
785 self.assertEqual(stdout,
Antoine Pitrou69994412014-04-29 00:56:08 +0200786 b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
787
788 def test_conflicting_envvar_and_command_line(self):
789 rc, stdout, stderr = assert_python_failure("-Werror::DeprecationWarning", "-c",
790 "import sys, warnings; sys.stdout.write(str(sys.warnoptions)); "
791 "warnings.warn('Message', DeprecationWarning)",
792 PYTHONWARNINGS="default::DeprecationWarning")
793 self.assertEqual(stdout,
794 b"['default::DeprecationWarning', 'error::DeprecationWarning']")
795 self.assertEqual(stderr.splitlines(),
796 [b"Traceback (most recent call last):",
797 b" File \"<string>\", line 1, in <module>",
798 b"DeprecationWarning: Message"])
Philip Jenvey0805ca32010-04-07 04:04:10 +0000799
Philip Jenveye53de3d2010-04-14 03:01:39 +0000800 @unittest.skipUnless(sys.getfilesystemencoding() != 'ascii',
801 'requires non-ascii filesystemencoding')
802 def test_nonascii(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100803 rc, stdout, stderr = assert_python_ok("-c",
804 "import sys; sys.stdout.write(str(sys.warnoptions))",
805 PYTHONIOENCODING="utf-8",
806 PYTHONWARNINGS="ignore:DeprecaciónWarning")
807 self.assertEqual(stdout,
808 "['ignore:DeprecaciónWarning']".encode('utf-8'))
Philip Jenveye53de3d2010-04-14 03:01:39 +0000809
Ezio Melotti2688e812013-01-10 06:52:23 +0200810class CEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
Philip Jenvey0805ca32010-04-07 04:04:10 +0000811 module = c_warnings
812
Ezio Melotti2688e812013-01-10 06:52:23 +0200813class PyEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
Philip Jenvey0805ca32010-04-07 04:04:10 +0000814 module = py_warnings
815
816
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000817class BootstrapTest(unittest.TestCase):
818 def test_issue_8766(self):
819 # "import encodings" emits a warning whereas the warnings is not loaded
Ezio Melotti42da6632011-03-15 05:18:48 +0200820 # or not completely loaded (warnings imports indirectly encodings by
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000821 # importing linecache) yet
822 with support.temp_cwd() as cwd, support.temp_cwd('encodings'):
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000823 # encodings loaded by initfsencoding()
Antoine Pitroubb08b362014-01-29 23:44:05 +0100824 assert_python_ok('-c', 'pass', PYTHONPATH=cwd)
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000825
826 # Use -W to load warnings module at startup
Antoine Pitroubb08b362014-01-29 23:44:05 +0100827 assert_python_ok('-c', 'pass', '-W', 'always', PYTHONPATH=cwd)
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000828
Victor Stinnerd1b48992013-10-28 19:16:21 +0100829class FinalizationTest(unittest.TestCase):
830 def test_finalization(self):
831 # Issue #19421: warnings.warn() should not crash
832 # during Python finalization
833 code = """
834import warnings
835warn = warnings.warn
836
837class A:
838 def __del__(self):
839 warn("test")
840
841a=A()
842 """
843 rc, out, err = assert_python_ok("-c", code)
844 # note: "__main__" filename is not correct, it should be the name
845 # of the script
846 self.assertEqual(err, b'__main__:7: UserWarning: test')
847
Ezio Melotti2688e812013-01-10 06:52:23 +0200848
849def setUpModule():
Christian Heimesdae2a892008-04-19 00:55:37 +0000850 py_warnings.onceregistry.clear()
851 c_warnings.onceregistry.clear()
Christian Heimes33fe8092008-04-13 13:53:33 +0000852
Ezio Melotti2688e812013-01-10 06:52:23 +0200853tearDownModule = setUpModule
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000854
855if __name__ == "__main__":
Ezio Melotti2688e812013-01-10 06:52:23 +0200856 unittest.main()