blob: cf7f747753c011c0d794cd1d66d6376fd667efbc [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
373
Ezio Melotti2688e812013-01-10 06:52:23 +0200374class CWarnTests(WarnTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000375 module = c_warnings
376
Nick Coghlanfce769e2009-04-11 14:30:59 +0000377 # As an early adopter, we sanity check the
378 # test.support.import_fresh_module utility function
379 def test_accelerated(self):
380 self.assertFalse(original_warnings is self.module)
381 self.assertFalse(hasattr(self.module.warn, '__code__'))
382
Ezio Melotti2688e812013-01-10 06:52:23 +0200383class PyWarnTests(WarnTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000384 module = py_warnings
385
Nick Coghlanfce769e2009-04-11 14:30:59 +0000386 # As an early adopter, we sanity check the
387 # test.support.import_fresh_module utility function
388 def test_pure_python(self):
389 self.assertFalse(original_warnings is self.module)
390 self.assertTrue(hasattr(self.module.warn, '__code__'))
391
Christian Heimes33fe8092008-04-13 13:53:33 +0000392
Ezio Melotti2688e812013-01-10 06:52:23 +0200393class WCmdLineTests(BaseTest):
Christian Heimes33fe8092008-04-13 13:53:33 +0000394
395 def test_improper_input(self):
396 # Uses the private _setoption() function to test the parsing
397 # of command-line warning arguments
Brett Cannon1cd02472008-09-09 01:52:27 +0000398 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000399 self.assertRaises(self.module._OptionError,
400 self.module._setoption, '1:2:3:4:5:6')
401 self.assertRaises(self.module._OptionError,
402 self.module._setoption, 'bogus::Warning')
403 self.assertRaises(self.module._OptionError,
404 self.module._setoption, 'ignore:2::4:-5')
405 self.module._setoption('error::Warning::0')
406 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
407
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000408 def test_improper_option(self):
409 # Same as above, but check that the message is printed out when
410 # the interpreter is executed. This also checks that options are
411 # actually parsed at all.
412 rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")
413 self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)
414
415 def test_warnings_bootstrap(self):
416 # Check that the warnings module does get loaded when -W<some option>
417 # is used (see issue #10372 for an example of silent bootstrap failure).
418 rc, out, err = assert_python_ok("-Wi", "-c",
419 "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
420 # '-Wi' was observed
421 self.assertFalse(out.strip())
422 self.assertNotIn(b'RuntimeWarning', err)
423
Ezio Melotti2688e812013-01-10 06:52:23 +0200424class CWCmdLineTests(WCmdLineTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000425 module = c_warnings
426
Ezio Melotti2688e812013-01-10 06:52:23 +0200427class PyWCmdLineTests(WCmdLineTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000428 module = py_warnings
429
430
Ezio Melotti2688e812013-01-10 06:52:23 +0200431class _WarningsTests(BaseTest, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000432
433 """Tests specific to the _warnings module."""
434
435 module = c_warnings
436
437 def test_filter(self):
438 # Everything should function even if 'filters' is not in warnings.
Brett Cannon1cd02472008-09-09 01:52:27 +0000439 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000440 self.module.filterwarnings("error", "", Warning, "", 0)
441 self.assertRaises(UserWarning, self.module.warn,
442 'convert to error')
443 del self.module.filters
444 self.assertRaises(UserWarning, self.module.warn,
445 'convert to error')
446
447 def test_onceregistry(self):
448 # Replacing or removing the onceregistry should be okay.
449 global __warningregistry__
450 message = UserWarning('onceregistry test')
451 try:
452 original_registry = self.module.onceregistry
453 __warningregistry__ = {}
Brett Cannon1cd02472008-09-09 01:52:27 +0000454 with original_warnings.catch_warnings(record=True,
455 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000456 self.module.resetwarnings()
457 self.module.filterwarnings("once", category=UserWarning)
458 self.module.warn_explicit(message, UserWarning, "file", 42)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000459 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000460 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000461 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000462 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000463 # Test the resetting of onceregistry.
464 self.module.onceregistry = {}
465 __warningregistry__ = {}
466 self.module.warn('onceregistry test')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000467 self.assertEqual(w[-1].message.args, message.args)
Christian Heimes33fe8092008-04-13 13:53:33 +0000468 # Removal of onceregistry is okay.
Brett Cannon1cd02472008-09-09 01:52:27 +0000469 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000470 del self.module.onceregistry
471 __warningregistry__ = {}
472 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000473 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000474 finally:
475 self.module.onceregistry = original_registry
476
Brett Cannon0759dd62009-04-01 18:13:07 +0000477 def test_default_action(self):
478 # Replacing or removing defaultaction should be okay.
479 message = UserWarning("defaultaction test")
480 original = self.module.defaultaction
481 try:
482 with original_warnings.catch_warnings(record=True,
483 module=self.module) as w:
484 self.module.resetwarnings()
485 registry = {}
486 self.module.warn_explicit(message, UserWarning, "<test>", 42,
487 registry=registry)
488 self.assertEqual(w[-1].message, message)
489 self.assertEqual(len(w), 1)
490 self.assertEqual(len(registry), 1)
491 del w[:]
492 # Test removal.
493 del self.module.defaultaction
494 __warningregistry__ = {}
495 registry = {}
496 self.module.warn_explicit(message, UserWarning, "<test>", 43,
497 registry=registry)
498 self.assertEqual(w[-1].message, message)
499 self.assertEqual(len(w), 1)
500 self.assertEqual(len(registry), 1)
501 del w[:]
502 # Test setting.
503 self.module.defaultaction = "ignore"
504 __warningregistry__ = {}
505 registry = {}
506 self.module.warn_explicit(message, UserWarning, "<test>", 44,
507 registry=registry)
508 self.assertEqual(len(w), 0)
509 finally:
510 self.module.defaultaction = original
511
Christian Heimes33fe8092008-04-13 13:53:33 +0000512 def test_showwarning_missing(self):
513 # Test that showwarning() missing is okay.
514 text = 'del showwarning test'
Brett Cannon1cd02472008-09-09 01:52:27 +0000515 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000516 self.module.filterwarnings("always", category=UserWarning)
517 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000518 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000519 self.module.warn(text)
520 result = stream.getvalue()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000521 self.assertIn(text, result)
Christian Heimes33fe8092008-04-13 13:53:33 +0000522
Christian Heimes8dc226f2008-05-06 23:45:46 +0000523 def test_showwarning_not_callable(self):
Brett Cannonfcc05272009-04-01 20:27:29 +0000524 with original_warnings.catch_warnings(module=self.module):
525 self.module.filterwarnings("always", category=UserWarning)
Brett Cannon52a7d982011-07-17 19:17:55 -0700526 self.module.showwarning = print
527 with support.captured_output('stdout'):
528 self.module.warn('Warning!')
Brett Cannonfcc05272009-04-01 20:27:29 +0000529 self.module.showwarning = 23
Brett Cannon52a7d982011-07-17 19:17:55 -0700530 self.assertRaises(TypeError, self.module.warn, "Warning!")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000531
Christian Heimes33fe8092008-04-13 13:53:33 +0000532 def test_show_warning_output(self):
533 # With showarning() missing, make sure that output is okay.
534 text = 'test show_warning'
Brett Cannon1cd02472008-09-09 01:52:27 +0000535 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000536 self.module.filterwarnings("always", category=UserWarning)
537 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000538 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000539 warning_tests.inner(text)
540 result = stream.getvalue()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000541 self.assertEqual(result.count('\n'), 2,
Christian Heimes33fe8092008-04-13 13:53:33 +0000542 "Too many newlines in %r" % result)
543 first_line, second_line = result.split('\n', 1)
544 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Neal Norwitz32dde222008-04-15 06:43:13 +0000545 first_line_parts = first_line.rsplit(':', 3)
546 path, line, warning_class, message = first_line_parts
Christian Heimes33fe8092008-04-13 13:53:33 +0000547 line = int(line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000548 self.assertEqual(expected_file, path)
549 self.assertEqual(warning_class, ' ' + UserWarning.__name__)
550 self.assertEqual(message, ' ' + text)
Christian Heimes33fe8092008-04-13 13:53:33 +0000551 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
552 assert expected_line
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000553 self.assertEqual(second_line, expected_line)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000554
Victor Stinner8b0508e2011-07-04 02:43:09 +0200555 def test_filename_none(self):
556 # issue #12467: race condition if a warning is emitted at shutdown
557 globals_dict = globals()
558 oldfile = globals_dict['__file__']
559 try:
Brett Cannon52a7d982011-07-17 19:17:55 -0700560 catch = original_warnings.catch_warnings(record=True,
561 module=self.module)
562 with catch as w:
Victor Stinner8b0508e2011-07-04 02:43:09 +0200563 self.module.filterwarnings("always", category=UserWarning)
564 globals_dict['__file__'] = None
565 original_warnings.warn('test', UserWarning)
Brett Cannon52a7d982011-07-17 19:17:55 -0700566 self.assertTrue(len(w))
Victor Stinner8b0508e2011-07-04 02:43:09 +0200567 finally:
568 globals_dict['__file__'] = oldfile
569
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000570
Ezio Melotti2688e812013-01-10 06:52:23 +0200571class WarningsDisplayTests(BaseTest):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000572
Christian Heimes33fe8092008-04-13 13:53:33 +0000573 """Test the displaying of warnings and the ability to overload functions
574 related to displaying warnings."""
575
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000576 def test_formatwarning(self):
577 message = "msg"
578 category = Warning
579 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
580 line_num = 3
581 file_line = linecache.getline(file_name, line_num).strip()
Christian Heimes33fe8092008-04-13 13:53:33 +0000582 format = "%s:%s: %s: %s\n %s\n"
583 expect = format % (file_name, line_num, category.__name__, message,
584 file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000585 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000586 category, file_name, line_num))
587 # Test the 'line' argument.
588 file_line += " for the win!"
589 expect = format % (file_name, line_num, category.__name__, message,
590 file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000591 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000592 category, file_name, line_num, file_line))
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000593
594 def test_showwarning(self):
595 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
596 line_num = 3
597 expected_file_line = linecache.getline(file_name, line_num).strip()
598 message = 'msg'
599 category = Warning
600 file_object = StringIO()
Christian Heimes33fe8092008-04-13 13:53:33 +0000601 expect = self.module.formatwarning(message, category, file_name,
602 line_num)
603 self.module.showwarning(message, category, file_name, line_num,
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000604 file_object)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000605 self.assertEqual(file_object.getvalue(), expect)
Christian Heimes33fe8092008-04-13 13:53:33 +0000606 # Test 'line' argument.
607 expected_file_line += "for the win!"
608 expect = self.module.formatwarning(message, category, file_name,
609 line_num, expected_file_line)
610 file_object = StringIO()
611 self.module.showwarning(message, category, file_name, line_num,
612 file_object, expected_file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000613 self.assertEqual(expect, file_object.getvalue())
Christian Heimes33fe8092008-04-13 13:53:33 +0000614
Ezio Melotti2688e812013-01-10 06:52:23 +0200615class CWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000616 module = c_warnings
617
Ezio Melotti2688e812013-01-10 06:52:23 +0200618class PyWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000619 module = py_warnings
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000620
Brett Cannon1cd02472008-09-09 01:52:27 +0000621
Brett Cannonec92e182008-09-02 02:46:59 +0000622class CatchWarningTests(BaseTest):
Nick Coghlanb1304932008-07-13 12:25:08 +0000623
Brett Cannonec92e182008-09-02 02:46:59 +0000624 """Test catch_warnings()."""
625
626 def test_catch_warnings_restore(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000627 wmod = self.module
628 orig_filters = wmod.filters
629 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000630 # Ensure both showwarning and filters are restored when recording
631 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlanb1304932008-07-13 12:25:08 +0000632 wmod.filters = wmod.showwarning = object()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000633 self.assertTrue(wmod.filters is orig_filters)
634 self.assertTrue(wmod.showwarning is orig_showwarning)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000635 # Same test, but with recording disabled
636 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlanb1304932008-07-13 12:25:08 +0000637 wmod.filters = wmod.showwarning = object()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000638 self.assertTrue(wmod.filters is orig_filters)
639 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000640
Brett Cannonec92e182008-09-02 02:46:59 +0000641 def test_catch_warnings_recording(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000642 wmod = self.module
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000643 # Ensure warnings are recorded when requested
644 with wmod.catch_warnings(module=wmod, record=True) as w:
Brett Cannonec92e182008-09-02 02:46:59 +0000645 self.assertEqual(w, [])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000646 self.assertTrue(type(w) is list)
Nick Coghlanb1304932008-07-13 12:25:08 +0000647 wmod.simplefilter("always")
648 wmod.warn("foo")
Brett Cannon1cd02472008-09-09 01:52:27 +0000649 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlanb1304932008-07-13 12:25:08 +0000650 wmod.warn("bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000651 self.assertEqual(str(w[-1].message), "bar")
Brett Cannonec92e182008-09-02 02:46:59 +0000652 self.assertEqual(str(w[0].message), "foo")
653 self.assertEqual(str(w[1].message), "bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000654 del w[:]
Brett Cannonec92e182008-09-02 02:46:59 +0000655 self.assertEqual(w, [])
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000656 # Ensure warnings are not recorded when not requested
Nick Coghlanb1304932008-07-13 12:25:08 +0000657 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000658 with wmod.catch_warnings(module=wmod, record=False) as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000659 self.assertTrue(w is None)
660 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000661
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000662 def test_catch_warnings_reentry_guard(self):
663 wmod = self.module
664 # Ensure catch_warnings is protected against incorrect usage
665 x = wmod.catch_warnings(module=wmod, record=True)
666 self.assertRaises(RuntimeError, x.__exit__)
667 with x:
668 self.assertRaises(RuntimeError, x.__enter__)
669 # Same test, but with recording disabled
670 x = wmod.catch_warnings(module=wmod, record=False)
671 self.assertRaises(RuntimeError, x.__exit__)
672 with x:
673 self.assertRaises(RuntimeError, x.__enter__)
674
675 def test_catch_warnings_defaults(self):
676 wmod = self.module
677 orig_filters = wmod.filters
678 orig_showwarning = wmod.showwarning
679 # Ensure default behaviour is not to record warnings
680 with wmod.catch_warnings(module=wmod) as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000681 self.assertTrue(w is None)
682 self.assertTrue(wmod.showwarning is orig_showwarning)
683 self.assertTrue(wmod.filters is not orig_filters)
684 self.assertTrue(wmod.filters is orig_filters)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000685 if wmod is sys.modules['warnings']:
686 # Ensure the default module is this one
687 with wmod.catch_warnings() as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000688 self.assertTrue(w is None)
689 self.assertTrue(wmod.showwarning is orig_showwarning)
690 self.assertTrue(wmod.filters is not orig_filters)
691 self.assertTrue(wmod.filters is orig_filters)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000692
693 def test_check_warnings(self):
694 # Explicit tests for the test.support convenience wrapper
695 wmod = self.module
Florent Xicluna53b506be2010-03-18 20:00:57 +0000696 if wmod is not sys.modules['warnings']:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600697 self.skipTest('module to test is not loaded warnings module')
Florent Xicluna53b506be2010-03-18 20:00:57 +0000698 with support.check_warnings(quiet=False) as w:
699 self.assertEqual(w.warnings, [])
700 wmod.simplefilter("always")
701 wmod.warn("foo")
702 self.assertEqual(str(w.message), "foo")
703 wmod.warn("bar")
704 self.assertEqual(str(w.message), "bar")
705 self.assertEqual(str(w.warnings[0].message), "foo")
706 self.assertEqual(str(w.warnings[1].message), "bar")
707 w.reset()
708 self.assertEqual(w.warnings, [])
709
710 with support.check_warnings():
711 # defaults to quiet=True without argument
712 pass
713 with support.check_warnings(('foo', UserWarning)):
714 wmod.warn("foo")
715
716 with self.assertRaises(AssertionError):
717 with support.check_warnings(('', RuntimeWarning)):
718 # defaults to quiet=False with argument
719 pass
720 with self.assertRaises(AssertionError):
721 with support.check_warnings(('foo', RuntimeWarning)):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000722 wmod.warn("foo")
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000723
Ezio Melotti2688e812013-01-10 06:52:23 +0200724class CCatchWarningTests(CatchWarningTests, unittest.TestCase):
Nick Coghlanb1304932008-07-13 12:25:08 +0000725 module = c_warnings
726
Ezio Melotti2688e812013-01-10 06:52:23 +0200727class PyCatchWarningTests(CatchWarningTests, unittest.TestCase):
Nick Coghlanb1304932008-07-13 12:25:08 +0000728 module = py_warnings
729
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000730
Philip Jenvey0805ca32010-04-07 04:04:10 +0000731class EnvironmentVariableTests(BaseTest):
732
733 def test_single_warning(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100734 rc, stdout, stderr = assert_python_ok("-c",
735 "import sys; sys.stdout.write(str(sys.warnoptions))",
736 PYTHONWARNINGS="ignore::DeprecationWarning")
737 self.assertEqual(stdout, b"['ignore::DeprecationWarning']")
Philip Jenvey0805ca32010-04-07 04:04:10 +0000738
739 def test_comma_separated_warnings(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100740 rc, stdout, stderr = assert_python_ok("-c",
741 "import sys; sys.stdout.write(str(sys.warnoptions))",
742 PYTHONWARNINGS="ignore::DeprecationWarning,ignore::UnicodeWarning")
743 self.assertEqual(stdout,
744 b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
Philip Jenvey0805ca32010-04-07 04:04:10 +0000745
746 def test_envvar_and_command_line(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100747 rc, stdout, stderr = assert_python_ok("-Wignore::UnicodeWarning", "-c",
748 "import sys; sys.stdout.write(str(sys.warnoptions))",
749 PYTHONWARNINGS="ignore::DeprecationWarning")
750 self.assertEqual(stdout,
Antoine Pitrou69994412014-04-29 00:56:08 +0200751 b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
752
753 def test_conflicting_envvar_and_command_line(self):
754 rc, stdout, stderr = assert_python_failure("-Werror::DeprecationWarning", "-c",
755 "import sys, warnings; sys.stdout.write(str(sys.warnoptions)); "
756 "warnings.warn('Message', DeprecationWarning)",
757 PYTHONWARNINGS="default::DeprecationWarning")
758 self.assertEqual(stdout,
759 b"['default::DeprecationWarning', 'error::DeprecationWarning']")
760 self.assertEqual(stderr.splitlines(),
761 [b"Traceback (most recent call last):",
762 b" File \"<string>\", line 1, in <module>",
763 b"DeprecationWarning: Message"])
Philip Jenvey0805ca32010-04-07 04:04:10 +0000764
Philip Jenveye53de3d2010-04-14 03:01:39 +0000765 @unittest.skipUnless(sys.getfilesystemencoding() != 'ascii',
766 'requires non-ascii filesystemencoding')
767 def test_nonascii(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100768 rc, stdout, stderr = assert_python_ok("-c",
769 "import sys; sys.stdout.write(str(sys.warnoptions))",
770 PYTHONIOENCODING="utf-8",
771 PYTHONWARNINGS="ignore:DeprecaciónWarning")
772 self.assertEqual(stdout,
773 "['ignore:DeprecaciónWarning']".encode('utf-8'))
Philip Jenveye53de3d2010-04-14 03:01:39 +0000774
Ezio Melotti2688e812013-01-10 06:52:23 +0200775class CEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
Philip Jenvey0805ca32010-04-07 04:04:10 +0000776 module = c_warnings
777
Ezio Melotti2688e812013-01-10 06:52:23 +0200778class PyEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
Philip Jenvey0805ca32010-04-07 04:04:10 +0000779 module = py_warnings
780
781
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000782class BootstrapTest(unittest.TestCase):
783 def test_issue_8766(self):
784 # "import encodings" emits a warning whereas the warnings is not loaded
Ezio Melotti42da6632011-03-15 05:18:48 +0200785 # or not completely loaded (warnings imports indirectly encodings by
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000786 # importing linecache) yet
787 with support.temp_cwd() as cwd, support.temp_cwd('encodings'):
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000788 # encodings loaded by initfsencoding()
Antoine Pitroubb08b362014-01-29 23:44:05 +0100789 assert_python_ok('-c', 'pass', PYTHONPATH=cwd)
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000790
791 # Use -W to load warnings module at startup
Antoine Pitroubb08b362014-01-29 23:44:05 +0100792 assert_python_ok('-c', 'pass', '-W', 'always', PYTHONPATH=cwd)
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000793
Victor Stinnerd1b48992013-10-28 19:16:21 +0100794class FinalizationTest(unittest.TestCase):
795 def test_finalization(self):
796 # Issue #19421: warnings.warn() should not crash
797 # during Python finalization
798 code = """
799import warnings
800warn = warnings.warn
801
802class A:
803 def __del__(self):
804 warn("test")
805
806a=A()
807 """
808 rc, out, err = assert_python_ok("-c", code)
809 # note: "__main__" filename is not correct, it should be the name
810 # of the script
811 self.assertEqual(err, b'__main__:7: UserWarning: test')
812
Ezio Melotti2688e812013-01-10 06:52:23 +0200813
814def setUpModule():
Christian Heimesdae2a892008-04-19 00:55:37 +0000815 py_warnings.onceregistry.clear()
816 c_warnings.onceregistry.clear()
Christian Heimes33fe8092008-04-13 13:53:33 +0000817
Ezio Melotti2688e812013-01-10 06:52:23 +0200818tearDownModule = setUpModule
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000819
820if __name__ == "__main__":
Ezio Melotti2688e812013-01-10 06:52:23 +0200821 unittest.main()