blob: 43b3b9c1287ae4de00ddf338fe6069af0b9b40f6 [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 Pitroucf9f9802010-11-10 13:55:25 +00008from test.script_helper import assert_python_ok
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
Brett Cannon14ad5312014-08-22 10:44:47 -040064class PublicAPITests(BaseTest):
65
66 """Ensures that the correct values are exposed in the
67 public API.
68 """
69
70 def test_module_all_attribute(self):
71 self.assertTrue(hasattr(self.module, '__all__'))
72 target_api = ["warn", "warn_explicit", "showwarning",
73 "formatwarning", "filterwarnings", "simplefilter",
74 "resetwarnings", "catch_warnings"]
75 self.assertSetEqual(set(self.module.__all__),
76 set(target_api))
77
78class CPublicAPITests(PublicAPITests, unittest.TestCase):
79 module = c_warnings
80
81class PyPublicAPITests(PublicAPITests, unittest.TestCase):
82 module = py_warnings
Christian Heimes33fe8092008-04-13 13:53:33 +000083
Ezio Melotti2688e812013-01-10 06:52:23 +020084class FilterTests(BaseTest):
Christian Heimes33fe8092008-04-13 13:53:33 +000085
86 """Testing the filtering functionality."""
87
88 def test_error(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000089 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000090 self.module.resetwarnings()
91 self.module.filterwarnings("error", category=UserWarning)
92 self.assertRaises(UserWarning, self.module.warn,
93 "FilterTests.test_error")
94
95 def test_ignore(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("ignore", category=UserWarning)
100 self.module.warn("FilterTests.test_ignore", UserWarning)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000101 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000102
103 def test_always(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000104 with original_warnings.catch_warnings(record=True,
105 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000106 self.module.resetwarnings()
107 self.module.filterwarnings("always", category=UserWarning)
108 message = "FilterTests.test_always"
109 self.module.warn(message, UserWarning)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000110 self.assertTrue(message, w[-1].message)
Christian Heimes33fe8092008-04-13 13:53:33 +0000111 self.module.warn(message, UserWarning)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000112 self.assertTrue(w[-1].message, message)
Christian Heimes33fe8092008-04-13 13:53:33 +0000113
114 def test_default(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000115 with original_warnings.catch_warnings(record=True,
116 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000117 self.module.resetwarnings()
118 self.module.filterwarnings("default", category=UserWarning)
119 message = UserWarning("FilterTests.test_default")
120 for x in range(2):
121 self.module.warn(message, UserWarning)
122 if x == 0:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000123 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000124 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000125 elif x == 1:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000126 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000127 else:
128 raise ValueError("loop variant unhandled")
129
130 def test_module(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000131 with original_warnings.catch_warnings(record=True,
132 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000133 self.module.resetwarnings()
134 self.module.filterwarnings("module", category=UserWarning)
135 message = UserWarning("FilterTests.test_module")
136 self.module.warn(message, UserWarning)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000137 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000138 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000139 self.module.warn(message, UserWarning)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000140 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000141
142 def test_once(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000143 with original_warnings.catch_warnings(record=True,
144 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000145 self.module.resetwarnings()
146 self.module.filterwarnings("once", category=UserWarning)
147 message = UserWarning("FilterTests.test_once")
148 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
149 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000150 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000151 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000152 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
153 13)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000154 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000155 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
156 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000157 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000158
159 def test_inheritance(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000160 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000161 self.module.resetwarnings()
162 self.module.filterwarnings("error", category=Warning)
163 self.assertRaises(UserWarning, self.module.warn,
164 "FilterTests.test_inheritance", UserWarning)
165
166 def test_ordering(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000167 with original_warnings.catch_warnings(record=True,
168 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000169 self.module.resetwarnings()
170 self.module.filterwarnings("ignore", category=UserWarning)
171 self.module.filterwarnings("error", category=UserWarning,
172 append=True)
Brett Cannon1cd02472008-09-09 01:52:27 +0000173 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000174 try:
175 self.module.warn("FilterTests.test_ordering", UserWarning)
176 except UserWarning:
177 self.fail("order handling for actions failed")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000178 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000179
180 def test_filterwarnings(self):
181 # Test filterwarnings().
182 # Implicitly also tests resetwarnings().
Brett Cannon1cd02472008-09-09 01:52:27 +0000183 with original_warnings.catch_warnings(record=True,
184 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000185 self.module.filterwarnings("error", "", Warning, "", 0)
186 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
187
188 self.module.resetwarnings()
189 text = 'handle normally'
190 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000191 self.assertEqual(str(w[-1].message), text)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000192 self.assertTrue(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000193
194 self.module.filterwarnings("ignore", "", Warning, "", 0)
195 text = 'filtered out'
196 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000197 self.assertNotEqual(str(w[-1].message), text)
Christian Heimes33fe8092008-04-13 13:53:33 +0000198
199 self.module.resetwarnings()
200 self.module.filterwarnings("error", "hex*", Warning, "", 0)
201 self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
202 text = 'nonmatching text'
203 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000204 self.assertEqual(str(w[-1].message), text)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000205 self.assertTrue(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000206
Ezio Melotti2688e812013-01-10 06:52:23 +0200207class CFilterTests(FilterTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000208 module = c_warnings
209
Ezio Melotti2688e812013-01-10 06:52:23 +0200210class PyFilterTests(FilterTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000211 module = py_warnings
212
213
Ezio Melotti2688e812013-01-10 06:52:23 +0200214class WarnTests(BaseTest):
Christian Heimes33fe8092008-04-13 13:53:33 +0000215
216 """Test warnings.warn() and warnings.warn_explicit()."""
217
218 def test_message(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000219 with original_warnings.catch_warnings(record=True,
220 module=self.module) as w:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000221 self.module.simplefilter("once")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000222 for i in range(4):
Christian Heimes33fe8092008-04-13 13:53:33 +0000223 text = 'multi %d' %i # Different text on each call.
224 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000225 self.assertEqual(str(w[-1].message), text)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000226 self.assertTrue(w[-1].category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000227
Brett Cannon54bd41d2008-09-02 04:01:42 +0000228 # Issue 3639
229 def test_warn_nonstandard_types(self):
230 # warn() should handle non-standard types without issue.
231 for ob in (Warning, None, 42):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000232 with original_warnings.catch_warnings(record=True,
233 module=self.module) as w:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000234 self.module.simplefilter("once")
Brett Cannon54bd41d2008-09-02 04:01:42 +0000235 self.module.warn(ob)
236 # Don't directly compare objects since
237 # ``Warning() != Warning()``.
Ezio Melottib3aedd42010-11-20 19:04:17 +0000238 self.assertEqual(str(w[-1].message), str(UserWarning(ob)))
Brett Cannon54bd41d2008-09-02 04:01:42 +0000239
Guido van Rossumd8faa362007-04-27 19:54:29 +0000240 def test_filename(self):
Christian Heimes33fe8092008-04-13 13:53:33 +0000241 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000242 with original_warnings.catch_warnings(record=True,
243 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000244 warning_tests.inner("spam1")
Brett Cannon1cd02472008-09-09 01:52:27 +0000245 self.assertEqual(os.path.basename(w[-1].filename),
246 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000247 warning_tests.outer("spam2")
Brett Cannon1cd02472008-09-09 01:52:27 +0000248 self.assertEqual(os.path.basename(w[-1].filename),
249 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000250
251 def test_stacklevel(self):
252 # Test stacklevel argument
253 # make sure all messages are different, so the warning won't be skipped
Christian Heimes33fe8092008-04-13 13:53:33 +0000254 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000255 with original_warnings.catch_warnings(record=True,
256 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000257 warning_tests.inner("spam3", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000258 self.assertEqual(os.path.basename(w[-1].filename),
259 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000260 warning_tests.outer("spam4", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000261 self.assertEqual(os.path.basename(w[-1].filename),
262 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000263
Christian Heimes33fe8092008-04-13 13:53:33 +0000264 warning_tests.inner("spam5", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000265 self.assertEqual(os.path.basename(w[-1].filename),
266 "test_warnings.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000267 warning_tests.outer("spam6", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000268 self.assertEqual(os.path.basename(w[-1].filename),
269 "warning_tests.py")
Christian Heimes5d8da202008-05-06 13:58:24 +0000270 warning_tests.outer("spam6.5", stacklevel=3)
Brett Cannon1cd02472008-09-09 01:52:27 +0000271 self.assertEqual(os.path.basename(w[-1].filename),
272 "test_warnings.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000273
Christian Heimes33fe8092008-04-13 13:53:33 +0000274 warning_tests.inner("spam7", stacklevel=9999)
Brett Cannon1cd02472008-09-09 01:52:27 +0000275 self.assertEqual(os.path.basename(w[-1].filename),
276 "sys")
Christian Heimes33fe8092008-04-13 13:53:33 +0000277
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000278 def test_missing_filename_not_main(self):
279 # If __file__ is not specified and __main__ is not the module name,
280 # then __file__ should be set to the module name.
281 filename = warning_tests.__file__
282 try:
283 del warning_tests.__file__
284 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000285 with original_warnings.catch_warnings(record=True,
286 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000287 warning_tests.inner("spam8", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000288 self.assertEqual(w[-1].filename, warning_tests.__name__)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000289 finally:
290 warning_tests.__file__ = filename
291
Serhiy Storchaka43767632013-11-03 21:31:38 +0200292 @unittest.skipUnless(hasattr(sys, 'argv'), 'test needs sys.argv')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000293 def test_missing_filename_main_with_argv(self):
294 # If __file__ is not specified and the caller is __main__ and sys.argv
295 # exists, then use sys.argv[0] as the file.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000296 filename = warning_tests.__file__
297 module_name = warning_tests.__name__
298 try:
299 del warning_tests.__file__
300 warning_tests.__name__ = '__main__'
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('spam9', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000305 self.assertEqual(w[-1].filename, sys.argv[0])
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000306 finally:
307 warning_tests.__file__ = filename
308 warning_tests.__name__ = module_name
309
310 def test_missing_filename_main_without_argv(self):
311 # If __file__ is not specified, the caller is __main__, and sys.argv
312 # is not set, then '__main__' is the file name.
313 filename = warning_tests.__file__
314 module_name = warning_tests.__name__
315 argv = sys.argv
316 try:
317 del warning_tests.__file__
318 warning_tests.__name__ = '__main__'
319 del sys.argv
320 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000321 with original_warnings.catch_warnings(record=True,
322 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000323 warning_tests.inner('spam10', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000324 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000325 finally:
326 warning_tests.__file__ = filename
327 warning_tests.__name__ = module_name
328 sys.argv = argv
329
Christian Heimesdaaf8ee2008-05-04 23:58:41 +0000330 def test_missing_filename_main_with_argv_empty_string(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000331 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
332 # is the empty string, then '__main__ is the file name.
333 # Tests issue 2743.
334 file_name = warning_tests.__file__
335 module_name = warning_tests.__name__
336 argv = sys.argv
337 try:
338 del warning_tests.__file__
339 warning_tests.__name__ = '__main__'
340 sys.argv = ['']
341 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000342 with original_warnings.catch_warnings(record=True,
343 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000344 warning_tests.inner('spam11', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000345 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000346 finally:
347 warning_tests.__file__ = file_name
348 warning_tests.__name__ = module_name
349 sys.argv = argv
350
Victor Stinnera4c704b2013-10-29 23:43:41 +0100351 def test_warn_explicit_non_ascii_filename(self):
352 with original_warnings.catch_warnings(record=True,
353 module=self.module) as w:
354 self.module.resetwarnings()
355 self.module.filterwarnings("always", category=UserWarning)
Victor Stinnerc0e07a32013-10-29 23:58:05 +0100356 for filename in ("nonascii\xe9\u20ac", "surrogate\udc80"):
357 try:
358 os.fsencode(filename)
359 except UnicodeEncodeError:
360 continue
361 self.module.warn_explicit("text", UserWarning, filename, 1)
362 self.assertEqual(w[-1].filename, filename)
Victor Stinnera4c704b2013-10-29 23:43:41 +0100363
Brett Cannondb734912008-06-27 00:52:15 +0000364 def test_warn_explicit_type_errors(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200365 # warn_explicit() should error out gracefully if it is given objects
Brett Cannondb734912008-06-27 00:52:15 +0000366 # of the wrong types.
367 # lineno is expected to be an integer.
368 self.assertRaises(TypeError, self.module.warn_explicit,
369 None, UserWarning, None, None)
370 # Either 'message' needs to be an instance of Warning or 'category'
371 # needs to be a subclass.
372 self.assertRaises(TypeError, self.module.warn_explicit,
373 None, None, None, 1)
374 # 'registry' must be a dict or None.
375 self.assertRaises((TypeError, AttributeError),
376 self.module.warn_explicit,
377 None, Warning, None, 1, registry=42)
378
Hirokazu Yamamoto1c0c0032009-07-17 06:55:42 +0000379 def test_bad_str(self):
380 # issue 6415
381 # Warnings instance with a bad format string for __str__ should not
382 # trigger a bus error.
383 class BadStrWarning(Warning):
384 """Warning with a bad format string for __str__."""
385 def __str__(self):
386 return ("A bad formatted string %(err)" %
387 {"err" : "there is no %(err)s"})
388
389 with self.assertRaises(ValueError):
390 self.module.warn(BadStrWarning())
391
392
Ezio Melotti2688e812013-01-10 06:52:23 +0200393class CWarnTests(WarnTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000394 module = c_warnings
395
Nick Coghlanfce769e2009-04-11 14:30:59 +0000396 # As an early adopter, we sanity check the
397 # test.support.import_fresh_module utility function
398 def test_accelerated(self):
399 self.assertFalse(original_warnings is self.module)
400 self.assertFalse(hasattr(self.module.warn, '__code__'))
401
Ezio Melotti2688e812013-01-10 06:52:23 +0200402class PyWarnTests(WarnTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000403 module = py_warnings
404
Nick Coghlanfce769e2009-04-11 14:30:59 +0000405 # As an early adopter, we sanity check the
406 # test.support.import_fresh_module utility function
407 def test_pure_python(self):
408 self.assertFalse(original_warnings is self.module)
409 self.assertTrue(hasattr(self.module.warn, '__code__'))
410
Christian Heimes33fe8092008-04-13 13:53:33 +0000411
Ezio Melotti2688e812013-01-10 06:52:23 +0200412class WCmdLineTests(BaseTest):
Christian Heimes33fe8092008-04-13 13:53:33 +0000413
414 def test_improper_input(self):
415 # Uses the private _setoption() function to test the parsing
416 # of command-line warning arguments
Brett Cannon1cd02472008-09-09 01:52:27 +0000417 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000418 self.assertRaises(self.module._OptionError,
419 self.module._setoption, '1:2:3:4:5:6')
420 self.assertRaises(self.module._OptionError,
421 self.module._setoption, 'bogus::Warning')
422 self.assertRaises(self.module._OptionError,
423 self.module._setoption, 'ignore:2::4:-5')
424 self.module._setoption('error::Warning::0')
425 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
426
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000427 def test_improper_option(self):
428 # Same as above, but check that the message is printed out when
429 # the interpreter is executed. This also checks that options are
430 # actually parsed at all.
431 rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")
432 self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)
433
434 def test_warnings_bootstrap(self):
435 # Check that the warnings module does get loaded when -W<some option>
436 # is used (see issue #10372 for an example of silent bootstrap failure).
437 rc, out, err = assert_python_ok("-Wi", "-c",
438 "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
439 # '-Wi' was observed
440 self.assertFalse(out.strip())
441 self.assertNotIn(b'RuntimeWarning', err)
442
Ezio Melotti2688e812013-01-10 06:52:23 +0200443class CWCmdLineTests(WCmdLineTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000444 module = c_warnings
445
Ezio Melotti2688e812013-01-10 06:52:23 +0200446class PyWCmdLineTests(WCmdLineTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000447 module = py_warnings
448
449
Ezio Melotti2688e812013-01-10 06:52:23 +0200450class _WarningsTests(BaseTest, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000451
452 """Tests specific to the _warnings module."""
453
454 module = c_warnings
455
456 def test_filter(self):
457 # Everything should function even if 'filters' is not in warnings.
Brett Cannon1cd02472008-09-09 01:52:27 +0000458 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000459 self.module.filterwarnings("error", "", Warning, "", 0)
460 self.assertRaises(UserWarning, self.module.warn,
461 'convert to error')
462 del self.module.filters
463 self.assertRaises(UserWarning, self.module.warn,
464 'convert to error')
465
466 def test_onceregistry(self):
467 # Replacing or removing the onceregistry should be okay.
468 global __warningregistry__
469 message = UserWarning('onceregistry test')
470 try:
471 original_registry = self.module.onceregistry
472 __warningregistry__ = {}
Brett Cannon1cd02472008-09-09 01:52:27 +0000473 with original_warnings.catch_warnings(record=True,
474 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000475 self.module.resetwarnings()
476 self.module.filterwarnings("once", category=UserWarning)
477 self.module.warn_explicit(message, UserWarning, "file", 42)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000478 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000479 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000480 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000481 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000482 # Test the resetting of onceregistry.
483 self.module.onceregistry = {}
484 __warningregistry__ = {}
485 self.module.warn('onceregistry test')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000486 self.assertEqual(w[-1].message.args, message.args)
Christian Heimes33fe8092008-04-13 13:53:33 +0000487 # Removal of onceregistry is okay.
Brett Cannon1cd02472008-09-09 01:52:27 +0000488 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000489 del self.module.onceregistry
490 __warningregistry__ = {}
491 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000492 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000493 finally:
494 self.module.onceregistry = original_registry
495
Brett Cannon0759dd62009-04-01 18:13:07 +0000496 def test_default_action(self):
497 # Replacing or removing defaultaction should be okay.
498 message = UserWarning("defaultaction test")
499 original = self.module.defaultaction
500 try:
501 with original_warnings.catch_warnings(record=True,
502 module=self.module) as w:
503 self.module.resetwarnings()
504 registry = {}
505 self.module.warn_explicit(message, UserWarning, "<test>", 42,
506 registry=registry)
507 self.assertEqual(w[-1].message, message)
508 self.assertEqual(len(w), 1)
509 self.assertEqual(len(registry), 1)
510 del w[:]
511 # Test removal.
512 del self.module.defaultaction
513 __warningregistry__ = {}
514 registry = {}
515 self.module.warn_explicit(message, UserWarning, "<test>", 43,
516 registry=registry)
517 self.assertEqual(w[-1].message, message)
518 self.assertEqual(len(w), 1)
519 self.assertEqual(len(registry), 1)
520 del w[:]
521 # Test setting.
522 self.module.defaultaction = "ignore"
523 __warningregistry__ = {}
524 registry = {}
525 self.module.warn_explicit(message, UserWarning, "<test>", 44,
526 registry=registry)
527 self.assertEqual(len(w), 0)
528 finally:
529 self.module.defaultaction = original
530
Christian Heimes33fe8092008-04-13 13:53:33 +0000531 def test_showwarning_missing(self):
532 # Test that showwarning() missing is okay.
533 text = 'del showwarning test'
Brett Cannon1cd02472008-09-09 01:52:27 +0000534 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000535 self.module.filterwarnings("always", category=UserWarning)
536 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000537 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000538 self.module.warn(text)
539 result = stream.getvalue()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000540 self.assertIn(text, result)
Christian Heimes33fe8092008-04-13 13:53:33 +0000541
Christian Heimes8dc226f2008-05-06 23:45:46 +0000542 def test_showwarning_not_callable(self):
Brett Cannonfcc05272009-04-01 20:27:29 +0000543 with original_warnings.catch_warnings(module=self.module):
544 self.module.filterwarnings("always", category=UserWarning)
Brett Cannon52a7d982011-07-17 19:17:55 -0700545 self.module.showwarning = print
546 with support.captured_output('stdout'):
547 self.module.warn('Warning!')
Brett Cannonfcc05272009-04-01 20:27:29 +0000548 self.module.showwarning = 23
Brett Cannon52a7d982011-07-17 19:17:55 -0700549 self.assertRaises(TypeError, self.module.warn, "Warning!")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000550
Christian Heimes33fe8092008-04-13 13:53:33 +0000551 def test_show_warning_output(self):
552 # With showarning() missing, make sure that output is okay.
553 text = 'test show_warning'
Brett Cannon1cd02472008-09-09 01:52:27 +0000554 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000555 self.module.filterwarnings("always", category=UserWarning)
556 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000557 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000558 warning_tests.inner(text)
559 result = stream.getvalue()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000560 self.assertEqual(result.count('\n'), 2,
Christian Heimes33fe8092008-04-13 13:53:33 +0000561 "Too many newlines in %r" % result)
562 first_line, second_line = result.split('\n', 1)
563 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Neal Norwitz32dde222008-04-15 06:43:13 +0000564 first_line_parts = first_line.rsplit(':', 3)
565 path, line, warning_class, message = first_line_parts
Christian Heimes33fe8092008-04-13 13:53:33 +0000566 line = int(line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000567 self.assertEqual(expected_file, path)
568 self.assertEqual(warning_class, ' ' + UserWarning.__name__)
569 self.assertEqual(message, ' ' + text)
Christian Heimes33fe8092008-04-13 13:53:33 +0000570 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
571 assert expected_line
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000572 self.assertEqual(second_line, expected_line)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000573
Victor Stinner8b0508e2011-07-04 02:43:09 +0200574 def test_filename_none(self):
575 # issue #12467: race condition if a warning is emitted at shutdown
576 globals_dict = globals()
577 oldfile = globals_dict['__file__']
578 try:
Brett Cannon52a7d982011-07-17 19:17:55 -0700579 catch = original_warnings.catch_warnings(record=True,
580 module=self.module)
581 with catch as w:
Victor Stinner8b0508e2011-07-04 02:43:09 +0200582 self.module.filterwarnings("always", category=UserWarning)
583 globals_dict['__file__'] = None
584 original_warnings.warn('test', UserWarning)
Brett Cannon52a7d982011-07-17 19:17:55 -0700585 self.assertTrue(len(w))
Victor Stinner8b0508e2011-07-04 02:43:09 +0200586 finally:
587 globals_dict['__file__'] = oldfile
588
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000589
Ezio Melotti2688e812013-01-10 06:52:23 +0200590class WarningsDisplayTests(BaseTest):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000591
Christian Heimes33fe8092008-04-13 13:53:33 +0000592 """Test the displaying of warnings and the ability to overload functions
593 related to displaying warnings."""
594
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000595 def test_formatwarning(self):
596 message = "msg"
597 category = Warning
598 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
599 line_num = 3
600 file_line = linecache.getline(file_name, line_num).strip()
Christian Heimes33fe8092008-04-13 13:53:33 +0000601 format = "%s:%s: %s: %s\n %s\n"
602 expect = format % (file_name, line_num, category.__name__, message,
603 file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000604 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000605 category, file_name, line_num))
606 # Test the 'line' argument.
607 file_line += " for the win!"
608 expect = format % (file_name, line_num, category.__name__, message,
609 file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000610 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000611 category, file_name, line_num, file_line))
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000612
613 def test_showwarning(self):
614 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
615 line_num = 3
616 expected_file_line = linecache.getline(file_name, line_num).strip()
617 message = 'msg'
618 category = Warning
619 file_object = StringIO()
Christian Heimes33fe8092008-04-13 13:53:33 +0000620 expect = self.module.formatwarning(message, category, file_name,
621 line_num)
622 self.module.showwarning(message, category, file_name, line_num,
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000623 file_object)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000624 self.assertEqual(file_object.getvalue(), expect)
Christian Heimes33fe8092008-04-13 13:53:33 +0000625 # Test 'line' argument.
626 expected_file_line += "for the win!"
627 expect = self.module.formatwarning(message, category, file_name,
628 line_num, expected_file_line)
629 file_object = StringIO()
630 self.module.showwarning(message, category, file_name, line_num,
631 file_object, expected_file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000632 self.assertEqual(expect, file_object.getvalue())
Christian Heimes33fe8092008-04-13 13:53:33 +0000633
Ezio Melotti2688e812013-01-10 06:52:23 +0200634class CWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000635 module = c_warnings
636
Ezio Melotti2688e812013-01-10 06:52:23 +0200637class PyWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000638 module = py_warnings
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000639
Brett Cannon1cd02472008-09-09 01:52:27 +0000640
Brett Cannonec92e182008-09-02 02:46:59 +0000641class CatchWarningTests(BaseTest):
Nick Coghlanb1304932008-07-13 12:25:08 +0000642
Brett Cannonec92e182008-09-02 02:46:59 +0000643 """Test catch_warnings()."""
644
645 def test_catch_warnings_restore(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000646 wmod = self.module
647 orig_filters = wmod.filters
648 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000649 # Ensure both showwarning and filters are restored when recording
650 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlanb1304932008-07-13 12:25:08 +0000651 wmod.filters = wmod.showwarning = object()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000652 self.assertTrue(wmod.filters is orig_filters)
653 self.assertTrue(wmod.showwarning is orig_showwarning)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000654 # Same test, but with recording disabled
655 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlanb1304932008-07-13 12:25:08 +0000656 wmod.filters = wmod.showwarning = object()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000657 self.assertTrue(wmod.filters is orig_filters)
658 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000659
Brett Cannonec92e182008-09-02 02:46:59 +0000660 def test_catch_warnings_recording(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000661 wmod = self.module
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000662 # Ensure warnings are recorded when requested
663 with wmod.catch_warnings(module=wmod, record=True) as w:
Brett Cannonec92e182008-09-02 02:46:59 +0000664 self.assertEqual(w, [])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000665 self.assertTrue(type(w) is list)
Nick Coghlanb1304932008-07-13 12:25:08 +0000666 wmod.simplefilter("always")
667 wmod.warn("foo")
Brett Cannon1cd02472008-09-09 01:52:27 +0000668 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlanb1304932008-07-13 12:25:08 +0000669 wmod.warn("bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000670 self.assertEqual(str(w[-1].message), "bar")
Brett Cannonec92e182008-09-02 02:46:59 +0000671 self.assertEqual(str(w[0].message), "foo")
672 self.assertEqual(str(w[1].message), "bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000673 del w[:]
Brett Cannonec92e182008-09-02 02:46:59 +0000674 self.assertEqual(w, [])
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000675 # Ensure warnings are not recorded when not requested
Nick Coghlanb1304932008-07-13 12:25:08 +0000676 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000677 with wmod.catch_warnings(module=wmod, record=False) as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000678 self.assertTrue(w is None)
679 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000680
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000681 def test_catch_warnings_reentry_guard(self):
682 wmod = self.module
683 # Ensure catch_warnings is protected against incorrect usage
684 x = wmod.catch_warnings(module=wmod, record=True)
685 self.assertRaises(RuntimeError, x.__exit__)
686 with x:
687 self.assertRaises(RuntimeError, x.__enter__)
688 # Same test, but with recording disabled
689 x = wmod.catch_warnings(module=wmod, record=False)
690 self.assertRaises(RuntimeError, x.__exit__)
691 with x:
692 self.assertRaises(RuntimeError, x.__enter__)
693
694 def test_catch_warnings_defaults(self):
695 wmod = self.module
696 orig_filters = wmod.filters
697 orig_showwarning = wmod.showwarning
698 # Ensure default behaviour is not to record warnings
699 with wmod.catch_warnings(module=wmod) as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000700 self.assertTrue(w is None)
701 self.assertTrue(wmod.showwarning is orig_showwarning)
702 self.assertTrue(wmod.filters is not orig_filters)
703 self.assertTrue(wmod.filters is orig_filters)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000704 if wmod is sys.modules['warnings']:
705 # Ensure the default module is this one
706 with wmod.catch_warnings() as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000707 self.assertTrue(w is None)
708 self.assertTrue(wmod.showwarning is orig_showwarning)
709 self.assertTrue(wmod.filters is not orig_filters)
710 self.assertTrue(wmod.filters is orig_filters)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000711
712 def test_check_warnings(self):
713 # Explicit tests for the test.support convenience wrapper
714 wmod = self.module
Florent Xicluna53b506be2010-03-18 20:00:57 +0000715 if wmod is not sys.modules['warnings']:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600716 self.skipTest('module to test is not loaded warnings module')
Florent Xicluna53b506be2010-03-18 20:00:57 +0000717 with support.check_warnings(quiet=False) as w:
718 self.assertEqual(w.warnings, [])
719 wmod.simplefilter("always")
720 wmod.warn("foo")
721 self.assertEqual(str(w.message), "foo")
722 wmod.warn("bar")
723 self.assertEqual(str(w.message), "bar")
724 self.assertEqual(str(w.warnings[0].message), "foo")
725 self.assertEqual(str(w.warnings[1].message), "bar")
726 w.reset()
727 self.assertEqual(w.warnings, [])
728
729 with support.check_warnings():
730 # defaults to quiet=True without argument
731 pass
732 with support.check_warnings(('foo', UserWarning)):
733 wmod.warn("foo")
734
735 with self.assertRaises(AssertionError):
736 with support.check_warnings(('', RuntimeWarning)):
737 # defaults to quiet=False with argument
738 pass
739 with self.assertRaises(AssertionError):
740 with support.check_warnings(('foo', RuntimeWarning)):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000741 wmod.warn("foo")
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000742
Ezio Melotti2688e812013-01-10 06:52:23 +0200743class CCatchWarningTests(CatchWarningTests, unittest.TestCase):
Nick Coghlanb1304932008-07-13 12:25:08 +0000744 module = c_warnings
745
Ezio Melotti2688e812013-01-10 06:52:23 +0200746class PyCatchWarningTests(CatchWarningTests, unittest.TestCase):
Nick Coghlanb1304932008-07-13 12:25:08 +0000747 module = py_warnings
748
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000749
Philip Jenvey0805ca32010-04-07 04:04:10 +0000750class EnvironmentVariableTests(BaseTest):
751
752 def test_single_warning(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100753 rc, stdout, stderr = assert_python_ok("-c",
754 "import sys; sys.stdout.write(str(sys.warnoptions))",
755 PYTHONWARNINGS="ignore::DeprecationWarning")
756 self.assertEqual(stdout, b"['ignore::DeprecationWarning']")
Philip Jenvey0805ca32010-04-07 04:04:10 +0000757
758 def test_comma_separated_warnings(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100759 rc, stdout, stderr = assert_python_ok("-c",
760 "import sys; sys.stdout.write(str(sys.warnoptions))",
761 PYTHONWARNINGS="ignore::DeprecationWarning,ignore::UnicodeWarning")
762 self.assertEqual(stdout,
763 b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
Philip Jenvey0805ca32010-04-07 04:04:10 +0000764
765 def test_envvar_and_command_line(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100766 rc, stdout, stderr = assert_python_ok("-Wignore::UnicodeWarning", "-c",
767 "import sys; sys.stdout.write(str(sys.warnoptions))",
768 PYTHONWARNINGS="ignore::DeprecationWarning")
769 self.assertEqual(stdout,
770 b"['ignore::UnicodeWarning', 'ignore::DeprecationWarning']")
Philip Jenvey0805ca32010-04-07 04:04:10 +0000771
Philip Jenveye53de3d2010-04-14 03:01:39 +0000772 @unittest.skipUnless(sys.getfilesystemencoding() != 'ascii',
773 'requires non-ascii filesystemencoding')
774 def test_nonascii(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 PYTHONIOENCODING="utf-8",
778 PYTHONWARNINGS="ignore:DeprecaciónWarning")
779 self.assertEqual(stdout,
780 "['ignore:DeprecaciónWarning']".encode('utf-8'))
Philip Jenveye53de3d2010-04-14 03:01:39 +0000781
Ezio Melotti2688e812013-01-10 06:52:23 +0200782class CEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
Philip Jenvey0805ca32010-04-07 04:04:10 +0000783 module = c_warnings
784
Ezio Melotti2688e812013-01-10 06:52:23 +0200785class PyEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
Philip Jenvey0805ca32010-04-07 04:04:10 +0000786 module = py_warnings
787
788
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000789class BootstrapTest(unittest.TestCase):
790 def test_issue_8766(self):
791 # "import encodings" emits a warning whereas the warnings is not loaded
Ezio Melotti42da6632011-03-15 05:18:48 +0200792 # or not completely loaded (warnings imports indirectly encodings by
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000793 # importing linecache) yet
794 with support.temp_cwd() as cwd, support.temp_cwd('encodings'):
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000795 # encodings loaded by initfsencoding()
Antoine Pitroubb08b362014-01-29 23:44:05 +0100796 assert_python_ok('-c', 'pass', PYTHONPATH=cwd)
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000797
798 # Use -W to load warnings module at startup
Antoine Pitroubb08b362014-01-29 23:44:05 +0100799 assert_python_ok('-c', 'pass', '-W', 'always', PYTHONPATH=cwd)
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000800
Victor Stinnerd1b48992013-10-28 19:16:21 +0100801class FinalizationTest(unittest.TestCase):
802 def test_finalization(self):
803 # Issue #19421: warnings.warn() should not crash
804 # during Python finalization
805 code = """
806import warnings
807warn = warnings.warn
808
809class A:
810 def __del__(self):
811 warn("test")
812
813a=A()
814 """
815 rc, out, err = assert_python_ok("-c", code)
816 # note: "__main__" filename is not correct, it should be the name
817 # of the script
818 self.assertEqual(err, b'__main__:7: UserWarning: test')
819
Ezio Melotti2688e812013-01-10 06:52:23 +0200820
821def setUpModule():
Christian Heimesdae2a892008-04-19 00:55:37 +0000822 py_warnings.onceregistry.clear()
823 c_warnings.onceregistry.clear()
Christian Heimes33fe8092008-04-13 13:53:33 +0000824
Ezio Melotti2688e812013-01-10 06:52:23 +0200825tearDownModule = setUpModule
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000826
827if __name__ == "__main__":
Ezio Melotti2688e812013-01-10 06:52:23 +0200828 unittest.main()