blob: c7d2e5cfbba87332890decf76b4c2ba5f2b92a01 [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
Berker Peksagce643912015-05-06 06:33:17 +03008from test.support.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
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
Antoine Pitroucb0a0062014-09-18 02:40:46 +020095 def test_error_after_default(self):
96 with original_warnings.catch_warnings(module=self.module) as w:
97 self.module.resetwarnings()
98 message = "FilterTests.test_ignore_after_default"
99 def f():
100 self.module.warn(message, UserWarning)
101 f()
102 self.module.filterwarnings("error", category=UserWarning)
103 self.assertRaises(UserWarning, f)
104
Christian Heimes33fe8092008-04-13 13:53:33 +0000105 def test_ignore(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000106 with original_warnings.catch_warnings(record=True,
107 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000108 self.module.resetwarnings()
109 self.module.filterwarnings("ignore", category=UserWarning)
110 self.module.warn("FilterTests.test_ignore", UserWarning)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000111 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000112
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200113 def test_ignore_after_default(self):
114 with original_warnings.catch_warnings(record=True,
115 module=self.module) as w:
116 self.module.resetwarnings()
117 message = "FilterTests.test_ignore_after_default"
118 def f():
119 self.module.warn(message, UserWarning)
120 f()
121 self.module.filterwarnings("ignore", category=UserWarning)
122 f()
123 f()
124 self.assertEqual(len(w), 1)
125
Christian Heimes33fe8092008-04-13 13:53:33 +0000126 def test_always(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000127 with original_warnings.catch_warnings(record=True,
128 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000129 self.module.resetwarnings()
130 self.module.filterwarnings("always", category=UserWarning)
131 message = "FilterTests.test_always"
132 self.module.warn(message, UserWarning)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000133 self.assertTrue(message, w[-1].message)
Christian Heimes33fe8092008-04-13 13:53:33 +0000134 self.module.warn(message, UserWarning)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000135 self.assertTrue(w[-1].message, message)
Christian Heimes33fe8092008-04-13 13:53:33 +0000136
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200137 def test_always_after_default(self):
138 with original_warnings.catch_warnings(record=True,
139 module=self.module) as w:
140 self.module.resetwarnings()
141 message = "FilterTests.test_always_after_ignore"
142 def f():
143 self.module.warn(message, UserWarning)
144 f()
145 self.assertEqual(len(w), 1)
146 self.assertEqual(w[-1].message.args[0], message)
147 f()
148 self.assertEqual(len(w), 1)
149 self.module.filterwarnings("always", category=UserWarning)
150 f()
151 self.assertEqual(len(w), 2)
152 self.assertEqual(w[-1].message.args[0], message)
153 f()
154 self.assertEqual(len(w), 3)
155 self.assertEqual(w[-1].message.args[0], message)
156
Christian Heimes33fe8092008-04-13 13:53:33 +0000157 def test_default(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000158 with original_warnings.catch_warnings(record=True,
159 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000160 self.module.resetwarnings()
161 self.module.filterwarnings("default", category=UserWarning)
162 message = UserWarning("FilterTests.test_default")
163 for x in range(2):
164 self.module.warn(message, UserWarning)
165 if x == 0:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000166 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000167 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000168 elif x == 1:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000169 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000170 else:
171 raise ValueError("loop variant unhandled")
172
173 def test_module(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000174 with original_warnings.catch_warnings(record=True,
175 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000176 self.module.resetwarnings()
177 self.module.filterwarnings("module", category=UserWarning)
178 message = UserWarning("FilterTests.test_module")
179 self.module.warn(message, UserWarning)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000180 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000181 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000182 self.module.warn(message, UserWarning)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000183 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000184
185 def test_once(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000186 with original_warnings.catch_warnings(record=True,
187 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000188 self.module.resetwarnings()
189 self.module.filterwarnings("once", category=UserWarning)
190 message = UserWarning("FilterTests.test_once")
191 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
192 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000193 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000194 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000195 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
196 13)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000197 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000198 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
199 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000200 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000201
202 def test_inheritance(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000203 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000204 self.module.resetwarnings()
205 self.module.filterwarnings("error", category=Warning)
206 self.assertRaises(UserWarning, self.module.warn,
207 "FilterTests.test_inheritance", UserWarning)
208
209 def test_ordering(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000210 with original_warnings.catch_warnings(record=True,
211 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000212 self.module.resetwarnings()
213 self.module.filterwarnings("ignore", category=UserWarning)
214 self.module.filterwarnings("error", category=UserWarning,
215 append=True)
Brett Cannon1cd02472008-09-09 01:52:27 +0000216 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000217 try:
218 self.module.warn("FilterTests.test_ordering", UserWarning)
219 except UserWarning:
220 self.fail("order handling for actions failed")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000221 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000222
223 def test_filterwarnings(self):
224 # Test filterwarnings().
225 # Implicitly also tests resetwarnings().
Brett Cannon1cd02472008-09-09 01:52:27 +0000226 with original_warnings.catch_warnings(record=True,
227 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000228 self.module.filterwarnings("error", "", Warning, "", 0)
229 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
230
231 self.module.resetwarnings()
232 text = 'handle normally'
233 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000234 self.assertEqual(str(w[-1].message), text)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000235 self.assertTrue(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000236
237 self.module.filterwarnings("ignore", "", Warning, "", 0)
238 text = 'filtered out'
239 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000240 self.assertNotEqual(str(w[-1].message), text)
Christian Heimes33fe8092008-04-13 13:53:33 +0000241
242 self.module.resetwarnings()
243 self.module.filterwarnings("error", "hex*", Warning, "", 0)
244 self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
245 text = 'nonmatching text'
246 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000247 self.assertEqual(str(w[-1].message), text)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000248 self.assertTrue(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000249
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400250 def test_mutate_filter_list(self):
251 class X:
252 def match(self, a):
253 L[:] = []
254
255 L = [("default",X(),UserWarning,X(),0) for i in range(2)]
256 with original_warnings.catch_warnings(record=True,
257 module=self.module) as w:
258 self.module.filters = L
259 self.module.warn_explicit(UserWarning("b"), None, "f.py", 42)
260 self.assertEqual(str(w[-1].message), "b")
261
Ezio Melotti2688e812013-01-10 06:52:23 +0200262class CFilterTests(FilterTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000263 module = c_warnings
264
Ezio Melotti2688e812013-01-10 06:52:23 +0200265class PyFilterTests(FilterTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000266 module = py_warnings
267
268
Ezio Melotti2688e812013-01-10 06:52:23 +0200269class WarnTests(BaseTest):
Christian Heimes33fe8092008-04-13 13:53:33 +0000270
271 """Test warnings.warn() and warnings.warn_explicit()."""
272
273 def test_message(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000274 with original_warnings.catch_warnings(record=True,
275 module=self.module) as w:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000276 self.module.simplefilter("once")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000277 for i in range(4):
Christian Heimes33fe8092008-04-13 13:53:33 +0000278 text = 'multi %d' %i # Different text on each call.
279 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000280 self.assertEqual(str(w[-1].message), text)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000281 self.assertTrue(w[-1].category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000282
Brett Cannon54bd41d2008-09-02 04:01:42 +0000283 # Issue 3639
284 def test_warn_nonstandard_types(self):
285 # warn() should handle non-standard types without issue.
286 for ob in (Warning, None, 42):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000287 with original_warnings.catch_warnings(record=True,
288 module=self.module) as w:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000289 self.module.simplefilter("once")
Brett Cannon54bd41d2008-09-02 04:01:42 +0000290 self.module.warn(ob)
291 # Don't directly compare objects since
292 # ``Warning() != Warning()``.
Ezio Melottib3aedd42010-11-20 19:04:17 +0000293 self.assertEqual(str(w[-1].message), str(UserWarning(ob)))
Brett Cannon54bd41d2008-09-02 04:01:42 +0000294
Guido van Rossumd8faa362007-04-27 19:54:29 +0000295 def test_filename(self):
Christian Heimes33fe8092008-04-13 13:53:33 +0000296 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000297 with original_warnings.catch_warnings(record=True,
298 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000299 warning_tests.inner("spam1")
Brett Cannon1cd02472008-09-09 01:52:27 +0000300 self.assertEqual(os.path.basename(w[-1].filename),
301 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000302 warning_tests.outer("spam2")
Brett Cannon1cd02472008-09-09 01:52:27 +0000303 self.assertEqual(os.path.basename(w[-1].filename),
304 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000305
306 def test_stacklevel(self):
307 # Test stacklevel argument
308 # make sure all messages are different, so the warning won't be skipped
Christian Heimes33fe8092008-04-13 13:53:33 +0000309 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000310 with original_warnings.catch_warnings(record=True,
311 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000312 warning_tests.inner("spam3", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000313 self.assertEqual(os.path.basename(w[-1].filename),
314 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000315 warning_tests.outer("spam4", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000316 self.assertEqual(os.path.basename(w[-1].filename),
317 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000318
Christian Heimes33fe8092008-04-13 13:53:33 +0000319 warning_tests.inner("spam5", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000320 self.assertEqual(os.path.basename(w[-1].filename),
321 "test_warnings.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000322 warning_tests.outer("spam6", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000323 self.assertEqual(os.path.basename(w[-1].filename),
324 "warning_tests.py")
Christian Heimes5d8da202008-05-06 13:58:24 +0000325 warning_tests.outer("spam6.5", stacklevel=3)
Brett Cannon1cd02472008-09-09 01:52:27 +0000326 self.assertEqual(os.path.basename(w[-1].filename),
327 "test_warnings.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000328
Christian Heimes33fe8092008-04-13 13:53:33 +0000329 warning_tests.inner("spam7", stacklevel=9999)
Brett Cannon1cd02472008-09-09 01:52:27 +0000330 self.assertEqual(os.path.basename(w[-1].filename),
331 "sys")
Christian Heimes33fe8092008-04-13 13:53:33 +0000332
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000333 def test_missing_filename_not_main(self):
334 # If __file__ is not specified and __main__ is not the module name,
335 # then __file__ should be set to the module name.
336 filename = warning_tests.__file__
337 try:
338 del warning_tests.__file__
339 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000340 with original_warnings.catch_warnings(record=True,
341 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000342 warning_tests.inner("spam8", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000343 self.assertEqual(w[-1].filename, warning_tests.__name__)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000344 finally:
345 warning_tests.__file__ = filename
346
Serhiy Storchaka43767632013-11-03 21:31:38 +0200347 @unittest.skipUnless(hasattr(sys, 'argv'), 'test needs sys.argv')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000348 def test_missing_filename_main_with_argv(self):
349 # If __file__ is not specified and the caller is __main__ and sys.argv
350 # exists, then use sys.argv[0] as the file.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000351 filename = warning_tests.__file__
352 module_name = warning_tests.__name__
353 try:
354 del warning_tests.__file__
355 warning_tests.__name__ = '__main__'
356 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000357 with original_warnings.catch_warnings(record=True,
358 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000359 warning_tests.inner('spam9', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000360 self.assertEqual(w[-1].filename, sys.argv[0])
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000361 finally:
362 warning_tests.__file__ = filename
363 warning_tests.__name__ = module_name
364
365 def test_missing_filename_main_without_argv(self):
366 # If __file__ is not specified, the caller is __main__, and sys.argv
367 # is not set, then '__main__' is the file name.
368 filename = warning_tests.__file__
369 module_name = warning_tests.__name__
370 argv = sys.argv
371 try:
372 del warning_tests.__file__
373 warning_tests.__name__ = '__main__'
374 del sys.argv
375 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000376 with original_warnings.catch_warnings(record=True,
377 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000378 warning_tests.inner('spam10', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000379 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000380 finally:
381 warning_tests.__file__ = filename
382 warning_tests.__name__ = module_name
383 sys.argv = argv
384
Christian Heimesdaaf8ee2008-05-04 23:58:41 +0000385 def test_missing_filename_main_with_argv_empty_string(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000386 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
387 # is the empty string, then '__main__ is the file name.
388 # Tests issue 2743.
389 file_name = warning_tests.__file__
390 module_name = warning_tests.__name__
391 argv = sys.argv
392 try:
393 del warning_tests.__file__
394 warning_tests.__name__ = '__main__'
395 sys.argv = ['']
396 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000397 with original_warnings.catch_warnings(record=True,
398 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000399 warning_tests.inner('spam11', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000400 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000401 finally:
402 warning_tests.__file__ = file_name
403 warning_tests.__name__ = module_name
404 sys.argv = argv
405
Victor Stinnera4c704b2013-10-29 23:43:41 +0100406 def test_warn_explicit_non_ascii_filename(self):
407 with original_warnings.catch_warnings(record=True,
408 module=self.module) as w:
409 self.module.resetwarnings()
410 self.module.filterwarnings("always", category=UserWarning)
Victor Stinnerc0e07a32013-10-29 23:58:05 +0100411 for filename in ("nonascii\xe9\u20ac", "surrogate\udc80"):
412 try:
413 os.fsencode(filename)
414 except UnicodeEncodeError:
415 continue
416 self.module.warn_explicit("text", UserWarning, filename, 1)
417 self.assertEqual(w[-1].filename, filename)
Victor Stinnera4c704b2013-10-29 23:43:41 +0100418
Brett Cannondb734912008-06-27 00:52:15 +0000419 def test_warn_explicit_type_errors(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200420 # warn_explicit() should error out gracefully if it is given objects
Brett Cannondb734912008-06-27 00:52:15 +0000421 # of the wrong types.
422 # lineno is expected to be an integer.
423 self.assertRaises(TypeError, self.module.warn_explicit,
424 None, UserWarning, None, None)
425 # Either 'message' needs to be an instance of Warning or 'category'
426 # needs to be a subclass.
427 self.assertRaises(TypeError, self.module.warn_explicit,
428 None, None, None, 1)
429 # 'registry' must be a dict or None.
430 self.assertRaises((TypeError, AttributeError),
431 self.module.warn_explicit,
432 None, Warning, None, 1, registry=42)
433
Hirokazu Yamamoto1c0c0032009-07-17 06:55:42 +0000434 def test_bad_str(self):
435 # issue 6415
436 # Warnings instance with a bad format string for __str__ should not
437 # trigger a bus error.
438 class BadStrWarning(Warning):
439 """Warning with a bad format string for __str__."""
440 def __str__(self):
441 return ("A bad formatted string %(err)" %
442 {"err" : "there is no %(err)s"})
443
444 with self.assertRaises(ValueError):
445 self.module.warn(BadStrWarning())
446
Berker Peksagd8089e02014-07-11 19:50:25 +0300447 def test_warning_classes(self):
448 class MyWarningClass(Warning):
449 pass
450
451 class NonWarningSubclass:
452 pass
453
454 # passing a non-subclass of Warning should raise a TypeError
455 with self.assertRaises(TypeError) as cm:
456 self.module.warn('bad warning category', '')
457 self.assertIn('category must be a Warning subclass, not ',
458 str(cm.exception))
459
460 with self.assertRaises(TypeError) as cm:
461 self.module.warn('bad warning category', NonWarningSubclass)
462 self.assertIn('category must be a Warning subclass, not ',
463 str(cm.exception))
464
465 # check that warning instances also raise a TypeError
466 with self.assertRaises(TypeError) as cm:
467 self.module.warn('bad warning category', MyWarningClass())
468 self.assertIn('category must be a Warning subclass, not ',
469 str(cm.exception))
470
Berker Peksagb8e973f2015-04-08 17:38:39 +0300471 with original_warnings.catch_warnings(module=self.module):
472 self.module.resetwarnings()
473 self.module.filterwarnings('default')
474 with self.assertWarns(MyWarningClass) as cm:
475 self.module.warn('good warning category', MyWarningClass)
476 self.assertEqual('good warning category', str(cm.warning))
Berker Peksagd8089e02014-07-11 19:50:25 +0300477
Berker Peksagb8e973f2015-04-08 17:38:39 +0300478 with self.assertWarns(UserWarning) as cm:
479 self.module.warn('good warning category', None)
480 self.assertEqual('good warning category', str(cm.warning))
Berker Peksagd8089e02014-07-11 19:50:25 +0300481
Berker Peksagb8e973f2015-04-08 17:38:39 +0300482 with self.assertWarns(MyWarningClass) as cm:
483 self.module.warn('good warning category', MyWarningClass)
484 self.assertIsInstance(cm.warning, Warning)
Hirokazu Yamamoto1c0c0032009-07-17 06:55:42 +0000485
Ezio Melotti2688e812013-01-10 06:52:23 +0200486class CWarnTests(WarnTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000487 module = c_warnings
488
Nick Coghlanfce769e2009-04-11 14:30:59 +0000489 # As an early adopter, we sanity check the
490 # test.support.import_fresh_module utility function
491 def test_accelerated(self):
492 self.assertFalse(original_warnings is self.module)
493 self.assertFalse(hasattr(self.module.warn, '__code__'))
494
Ezio Melotti2688e812013-01-10 06:52:23 +0200495class PyWarnTests(WarnTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000496 module = py_warnings
497
Nick Coghlanfce769e2009-04-11 14:30:59 +0000498 # As an early adopter, we sanity check the
499 # test.support.import_fresh_module utility function
500 def test_pure_python(self):
501 self.assertFalse(original_warnings is self.module)
502 self.assertTrue(hasattr(self.module.warn, '__code__'))
503
Christian Heimes33fe8092008-04-13 13:53:33 +0000504
Ezio Melotti2688e812013-01-10 06:52:23 +0200505class WCmdLineTests(BaseTest):
Christian Heimes33fe8092008-04-13 13:53:33 +0000506
507 def test_improper_input(self):
508 # Uses the private _setoption() function to test the parsing
509 # of command-line warning arguments
Brett Cannon1cd02472008-09-09 01:52:27 +0000510 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000511 self.assertRaises(self.module._OptionError,
512 self.module._setoption, '1:2:3:4:5:6')
513 self.assertRaises(self.module._OptionError,
514 self.module._setoption, 'bogus::Warning')
515 self.assertRaises(self.module._OptionError,
516 self.module._setoption, 'ignore:2::4:-5')
517 self.module._setoption('error::Warning::0')
518 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
519
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000520 def test_improper_option(self):
521 # Same as above, but check that the message is printed out when
522 # the interpreter is executed. This also checks that options are
523 # actually parsed at all.
524 rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")
525 self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)
526
527 def test_warnings_bootstrap(self):
528 # Check that the warnings module does get loaded when -W<some option>
529 # is used (see issue #10372 for an example of silent bootstrap failure).
530 rc, out, err = assert_python_ok("-Wi", "-c",
531 "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
532 # '-Wi' was observed
533 self.assertFalse(out.strip())
534 self.assertNotIn(b'RuntimeWarning', err)
535
Ezio Melotti2688e812013-01-10 06:52:23 +0200536class CWCmdLineTests(WCmdLineTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000537 module = c_warnings
538
Ezio Melotti2688e812013-01-10 06:52:23 +0200539class PyWCmdLineTests(WCmdLineTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000540 module = py_warnings
541
542
Ezio Melotti2688e812013-01-10 06:52:23 +0200543class _WarningsTests(BaseTest, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000544
545 """Tests specific to the _warnings module."""
546
547 module = c_warnings
548
549 def test_filter(self):
550 # Everything should function even if 'filters' is not in warnings.
Brett Cannon1cd02472008-09-09 01:52:27 +0000551 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000552 self.module.filterwarnings("error", "", Warning, "", 0)
553 self.assertRaises(UserWarning, self.module.warn,
554 'convert to error')
555 del self.module.filters
556 self.assertRaises(UserWarning, self.module.warn,
557 'convert to error')
558
559 def test_onceregistry(self):
560 # Replacing or removing the onceregistry should be okay.
561 global __warningregistry__
562 message = UserWarning('onceregistry test')
563 try:
564 original_registry = self.module.onceregistry
565 __warningregistry__ = {}
Brett Cannon1cd02472008-09-09 01:52:27 +0000566 with original_warnings.catch_warnings(record=True,
567 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000568 self.module.resetwarnings()
569 self.module.filterwarnings("once", category=UserWarning)
570 self.module.warn_explicit(message, UserWarning, "file", 42)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000571 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000572 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000573 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000574 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000575 # Test the resetting of onceregistry.
576 self.module.onceregistry = {}
577 __warningregistry__ = {}
578 self.module.warn('onceregistry test')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000579 self.assertEqual(w[-1].message.args, message.args)
Christian Heimes33fe8092008-04-13 13:53:33 +0000580 # Removal of onceregistry is okay.
Brett Cannon1cd02472008-09-09 01:52:27 +0000581 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000582 del self.module.onceregistry
583 __warningregistry__ = {}
584 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000585 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000586 finally:
587 self.module.onceregistry = original_registry
588
Brett Cannon0759dd62009-04-01 18:13:07 +0000589 def test_default_action(self):
590 # Replacing or removing defaultaction should be okay.
591 message = UserWarning("defaultaction test")
592 original = self.module.defaultaction
593 try:
594 with original_warnings.catch_warnings(record=True,
595 module=self.module) as w:
596 self.module.resetwarnings()
597 registry = {}
598 self.module.warn_explicit(message, UserWarning, "<test>", 42,
599 registry=registry)
600 self.assertEqual(w[-1].message, message)
601 self.assertEqual(len(w), 1)
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200602 # One actual registry key plus the "version" key
603 self.assertEqual(len(registry), 2)
604 self.assertIn("version", registry)
Brett Cannon0759dd62009-04-01 18:13:07 +0000605 del w[:]
606 # Test removal.
607 del self.module.defaultaction
608 __warningregistry__ = {}
609 registry = {}
610 self.module.warn_explicit(message, UserWarning, "<test>", 43,
611 registry=registry)
612 self.assertEqual(w[-1].message, message)
613 self.assertEqual(len(w), 1)
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200614 self.assertEqual(len(registry), 2)
Brett Cannon0759dd62009-04-01 18:13:07 +0000615 del w[:]
616 # Test setting.
617 self.module.defaultaction = "ignore"
618 __warningregistry__ = {}
619 registry = {}
620 self.module.warn_explicit(message, UserWarning, "<test>", 44,
621 registry=registry)
622 self.assertEqual(len(w), 0)
623 finally:
624 self.module.defaultaction = original
625
Christian Heimes33fe8092008-04-13 13:53:33 +0000626 def test_showwarning_missing(self):
627 # Test that showwarning() missing is okay.
628 text = 'del showwarning test'
Brett Cannon1cd02472008-09-09 01:52:27 +0000629 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000630 self.module.filterwarnings("always", category=UserWarning)
631 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000632 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000633 self.module.warn(text)
634 result = stream.getvalue()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000635 self.assertIn(text, result)
Christian Heimes33fe8092008-04-13 13:53:33 +0000636
Christian Heimes8dc226f2008-05-06 23:45:46 +0000637 def test_showwarning_not_callable(self):
Brett Cannonfcc05272009-04-01 20:27:29 +0000638 with original_warnings.catch_warnings(module=self.module):
639 self.module.filterwarnings("always", category=UserWarning)
Brett Cannon52a7d982011-07-17 19:17:55 -0700640 self.module.showwarning = print
641 with support.captured_output('stdout'):
642 self.module.warn('Warning!')
Brett Cannonfcc05272009-04-01 20:27:29 +0000643 self.module.showwarning = 23
Brett Cannon52a7d982011-07-17 19:17:55 -0700644 self.assertRaises(TypeError, self.module.warn, "Warning!")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000645
Christian Heimes33fe8092008-04-13 13:53:33 +0000646 def test_show_warning_output(self):
647 # With showarning() missing, make sure that output is okay.
648 text = 'test show_warning'
Brett Cannon1cd02472008-09-09 01:52:27 +0000649 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000650 self.module.filterwarnings("always", category=UserWarning)
651 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000652 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000653 warning_tests.inner(text)
654 result = stream.getvalue()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000655 self.assertEqual(result.count('\n'), 2,
Christian Heimes33fe8092008-04-13 13:53:33 +0000656 "Too many newlines in %r" % result)
657 first_line, second_line = result.split('\n', 1)
658 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Neal Norwitz32dde222008-04-15 06:43:13 +0000659 first_line_parts = first_line.rsplit(':', 3)
660 path, line, warning_class, message = first_line_parts
Christian Heimes33fe8092008-04-13 13:53:33 +0000661 line = int(line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000662 self.assertEqual(expected_file, path)
663 self.assertEqual(warning_class, ' ' + UserWarning.__name__)
664 self.assertEqual(message, ' ' + text)
Christian Heimes33fe8092008-04-13 13:53:33 +0000665 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
666 assert expected_line
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000667 self.assertEqual(second_line, expected_line)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000668
Victor Stinner8b0508e2011-07-04 02:43:09 +0200669 def test_filename_none(self):
670 # issue #12467: race condition if a warning is emitted at shutdown
671 globals_dict = globals()
672 oldfile = globals_dict['__file__']
673 try:
Brett Cannon52a7d982011-07-17 19:17:55 -0700674 catch = original_warnings.catch_warnings(record=True,
675 module=self.module)
676 with catch as w:
Victor Stinner8b0508e2011-07-04 02:43:09 +0200677 self.module.filterwarnings("always", category=UserWarning)
678 globals_dict['__file__'] = None
679 original_warnings.warn('test', UserWarning)
Brett Cannon52a7d982011-07-17 19:17:55 -0700680 self.assertTrue(len(w))
Victor Stinner8b0508e2011-07-04 02:43:09 +0200681 finally:
682 globals_dict['__file__'] = oldfile
683
Serhiy Storchaka60599522014-12-10 22:59:55 +0200684 def test_stderr_none(self):
685 rc, stdout, stderr = assert_python_ok("-c",
686 "import sys; sys.stderr = None; "
687 "import warnings; warnings.simplefilter('always'); "
688 "warnings.warn('Warning!')")
689 self.assertEqual(stdout, b'')
690 self.assertNotIn(b'Warning!', stderr)
691 self.assertNotIn(b'Error', stderr)
692
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000693
Ezio Melotti2688e812013-01-10 06:52:23 +0200694class WarningsDisplayTests(BaseTest):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000695
Christian Heimes33fe8092008-04-13 13:53:33 +0000696 """Test the displaying of warnings and the ability to overload functions
697 related to displaying warnings."""
698
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000699 def test_formatwarning(self):
700 message = "msg"
701 category = Warning
702 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
703 line_num = 3
704 file_line = linecache.getline(file_name, line_num).strip()
Christian Heimes33fe8092008-04-13 13:53:33 +0000705 format = "%s:%s: %s: %s\n %s\n"
706 expect = format % (file_name, line_num, category.__name__, message,
707 file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000708 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000709 category, file_name, line_num))
710 # Test the 'line' argument.
711 file_line += " for the win!"
712 expect = format % (file_name, line_num, category.__name__, message,
713 file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000714 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000715 category, file_name, line_num, file_line))
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000716
717 def test_showwarning(self):
718 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
719 line_num = 3
720 expected_file_line = linecache.getline(file_name, line_num).strip()
721 message = 'msg'
722 category = Warning
723 file_object = StringIO()
Christian Heimes33fe8092008-04-13 13:53:33 +0000724 expect = self.module.formatwarning(message, category, file_name,
725 line_num)
726 self.module.showwarning(message, category, file_name, line_num,
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000727 file_object)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000728 self.assertEqual(file_object.getvalue(), expect)
Christian Heimes33fe8092008-04-13 13:53:33 +0000729 # Test 'line' argument.
730 expected_file_line += "for the win!"
731 expect = self.module.formatwarning(message, category, file_name,
732 line_num, expected_file_line)
733 file_object = StringIO()
734 self.module.showwarning(message, category, file_name, line_num,
735 file_object, expected_file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000736 self.assertEqual(expect, file_object.getvalue())
Christian Heimes33fe8092008-04-13 13:53:33 +0000737
Ezio Melotti2688e812013-01-10 06:52:23 +0200738class CWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000739 module = c_warnings
740
Ezio Melotti2688e812013-01-10 06:52:23 +0200741class PyWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000742 module = py_warnings
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000743
Brett Cannon1cd02472008-09-09 01:52:27 +0000744
Brett Cannonec92e182008-09-02 02:46:59 +0000745class CatchWarningTests(BaseTest):
Nick Coghlanb1304932008-07-13 12:25:08 +0000746
Brett Cannonec92e182008-09-02 02:46:59 +0000747 """Test catch_warnings()."""
748
749 def test_catch_warnings_restore(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000750 wmod = self.module
751 orig_filters = wmod.filters
752 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000753 # Ensure both showwarning and filters are restored when recording
754 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlanb1304932008-07-13 12:25:08 +0000755 wmod.filters = wmod.showwarning = object()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000756 self.assertTrue(wmod.filters is orig_filters)
757 self.assertTrue(wmod.showwarning is orig_showwarning)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000758 # Same test, but with recording disabled
759 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlanb1304932008-07-13 12:25:08 +0000760 wmod.filters = wmod.showwarning = object()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000761 self.assertTrue(wmod.filters is orig_filters)
762 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000763
Brett Cannonec92e182008-09-02 02:46:59 +0000764 def test_catch_warnings_recording(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000765 wmod = self.module
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000766 # Ensure warnings are recorded when requested
767 with wmod.catch_warnings(module=wmod, record=True) as w:
Brett Cannonec92e182008-09-02 02:46:59 +0000768 self.assertEqual(w, [])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000769 self.assertTrue(type(w) is list)
Nick Coghlanb1304932008-07-13 12:25:08 +0000770 wmod.simplefilter("always")
771 wmod.warn("foo")
Brett Cannon1cd02472008-09-09 01:52:27 +0000772 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlanb1304932008-07-13 12:25:08 +0000773 wmod.warn("bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000774 self.assertEqual(str(w[-1].message), "bar")
Brett Cannonec92e182008-09-02 02:46:59 +0000775 self.assertEqual(str(w[0].message), "foo")
776 self.assertEqual(str(w[1].message), "bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000777 del w[:]
Brett Cannonec92e182008-09-02 02:46:59 +0000778 self.assertEqual(w, [])
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000779 # Ensure warnings are not recorded when not requested
Nick Coghlanb1304932008-07-13 12:25:08 +0000780 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000781 with wmod.catch_warnings(module=wmod, record=False) as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000782 self.assertTrue(w is None)
783 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000784
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000785 def test_catch_warnings_reentry_guard(self):
786 wmod = self.module
787 # Ensure catch_warnings is protected against incorrect usage
788 x = wmod.catch_warnings(module=wmod, record=True)
789 self.assertRaises(RuntimeError, x.__exit__)
790 with x:
791 self.assertRaises(RuntimeError, x.__enter__)
792 # Same test, but with recording disabled
793 x = wmod.catch_warnings(module=wmod, record=False)
794 self.assertRaises(RuntimeError, x.__exit__)
795 with x:
796 self.assertRaises(RuntimeError, x.__enter__)
797
798 def test_catch_warnings_defaults(self):
799 wmod = self.module
800 orig_filters = wmod.filters
801 orig_showwarning = wmod.showwarning
802 # Ensure default behaviour is not to record warnings
803 with wmod.catch_warnings(module=wmod) as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000804 self.assertTrue(w is None)
805 self.assertTrue(wmod.showwarning is orig_showwarning)
806 self.assertTrue(wmod.filters is not orig_filters)
807 self.assertTrue(wmod.filters is orig_filters)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000808 if wmod is sys.modules['warnings']:
809 # Ensure the default module is this one
810 with wmod.catch_warnings() as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000811 self.assertTrue(w is None)
812 self.assertTrue(wmod.showwarning is orig_showwarning)
813 self.assertTrue(wmod.filters is not orig_filters)
814 self.assertTrue(wmod.filters is orig_filters)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000815
816 def test_check_warnings(self):
817 # Explicit tests for the test.support convenience wrapper
818 wmod = self.module
Florent Xicluna53b506be2010-03-18 20:00:57 +0000819 if wmod is not sys.modules['warnings']:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600820 self.skipTest('module to test is not loaded warnings module')
Florent Xicluna53b506be2010-03-18 20:00:57 +0000821 with support.check_warnings(quiet=False) as w:
822 self.assertEqual(w.warnings, [])
823 wmod.simplefilter("always")
824 wmod.warn("foo")
825 self.assertEqual(str(w.message), "foo")
826 wmod.warn("bar")
827 self.assertEqual(str(w.message), "bar")
828 self.assertEqual(str(w.warnings[0].message), "foo")
829 self.assertEqual(str(w.warnings[1].message), "bar")
830 w.reset()
831 self.assertEqual(w.warnings, [])
832
833 with support.check_warnings():
834 # defaults to quiet=True without argument
835 pass
836 with support.check_warnings(('foo', UserWarning)):
837 wmod.warn("foo")
838
839 with self.assertRaises(AssertionError):
840 with support.check_warnings(('', RuntimeWarning)):
841 # defaults to quiet=False with argument
842 pass
843 with self.assertRaises(AssertionError):
844 with support.check_warnings(('foo', RuntimeWarning)):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000845 wmod.warn("foo")
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000846
Ezio Melotti2688e812013-01-10 06:52:23 +0200847class CCatchWarningTests(CatchWarningTests, unittest.TestCase):
Nick Coghlanb1304932008-07-13 12:25:08 +0000848 module = c_warnings
849
Ezio Melotti2688e812013-01-10 06:52:23 +0200850class PyCatchWarningTests(CatchWarningTests, unittest.TestCase):
Nick Coghlanb1304932008-07-13 12:25:08 +0000851 module = py_warnings
852
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000853
Philip Jenvey0805ca32010-04-07 04:04:10 +0000854class EnvironmentVariableTests(BaseTest):
855
856 def test_single_warning(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100857 rc, stdout, stderr = assert_python_ok("-c",
858 "import sys; sys.stdout.write(str(sys.warnoptions))",
859 PYTHONWARNINGS="ignore::DeprecationWarning")
860 self.assertEqual(stdout, b"['ignore::DeprecationWarning']")
Philip Jenvey0805ca32010-04-07 04:04:10 +0000861
862 def test_comma_separated_warnings(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100863 rc, stdout, stderr = assert_python_ok("-c",
864 "import sys; sys.stdout.write(str(sys.warnoptions))",
865 PYTHONWARNINGS="ignore::DeprecationWarning,ignore::UnicodeWarning")
866 self.assertEqual(stdout,
867 b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
Philip Jenvey0805ca32010-04-07 04:04:10 +0000868
869 def test_envvar_and_command_line(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100870 rc, stdout, stderr = assert_python_ok("-Wignore::UnicodeWarning", "-c",
871 "import sys; sys.stdout.write(str(sys.warnoptions))",
872 PYTHONWARNINGS="ignore::DeprecationWarning")
873 self.assertEqual(stdout,
Antoine Pitrou69994412014-04-29 00:56:08 +0200874 b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
875
876 def test_conflicting_envvar_and_command_line(self):
877 rc, stdout, stderr = assert_python_failure("-Werror::DeprecationWarning", "-c",
878 "import sys, warnings; sys.stdout.write(str(sys.warnoptions)); "
879 "warnings.warn('Message', DeprecationWarning)",
880 PYTHONWARNINGS="default::DeprecationWarning")
881 self.assertEqual(stdout,
882 b"['default::DeprecationWarning', 'error::DeprecationWarning']")
883 self.assertEqual(stderr.splitlines(),
884 [b"Traceback (most recent call last):",
885 b" File \"<string>\", line 1, in <module>",
886 b"DeprecationWarning: Message"])
Philip Jenvey0805ca32010-04-07 04:04:10 +0000887
Philip Jenveye53de3d2010-04-14 03:01:39 +0000888 @unittest.skipUnless(sys.getfilesystemencoding() != 'ascii',
889 'requires non-ascii filesystemencoding')
890 def test_nonascii(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100891 rc, stdout, stderr = assert_python_ok("-c",
892 "import sys; sys.stdout.write(str(sys.warnoptions))",
893 PYTHONIOENCODING="utf-8",
894 PYTHONWARNINGS="ignore:DeprecaciónWarning")
895 self.assertEqual(stdout,
896 "['ignore:DeprecaciónWarning']".encode('utf-8'))
Philip Jenveye53de3d2010-04-14 03:01:39 +0000897
Ezio Melotti2688e812013-01-10 06:52:23 +0200898class CEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
Philip Jenvey0805ca32010-04-07 04:04:10 +0000899 module = c_warnings
900
Ezio Melotti2688e812013-01-10 06:52:23 +0200901class PyEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
Philip Jenvey0805ca32010-04-07 04:04:10 +0000902 module = py_warnings
903
904
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000905class BootstrapTest(unittest.TestCase):
906 def test_issue_8766(self):
907 # "import encodings" emits a warning whereas the warnings is not loaded
Ezio Melotti42da6632011-03-15 05:18:48 +0200908 # or not completely loaded (warnings imports indirectly encodings by
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000909 # importing linecache) yet
910 with support.temp_cwd() as cwd, support.temp_cwd('encodings'):
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000911 # encodings loaded by initfsencoding()
Antoine Pitroubb08b362014-01-29 23:44:05 +0100912 assert_python_ok('-c', 'pass', PYTHONPATH=cwd)
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000913
914 # Use -W to load warnings module at startup
Antoine Pitroubb08b362014-01-29 23:44:05 +0100915 assert_python_ok('-c', 'pass', '-W', 'always', PYTHONPATH=cwd)
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000916
Victor Stinnerd1b48992013-10-28 19:16:21 +0100917class FinalizationTest(unittest.TestCase):
918 def test_finalization(self):
919 # Issue #19421: warnings.warn() should not crash
920 # during Python finalization
921 code = """
922import warnings
923warn = warnings.warn
924
925class A:
926 def __del__(self):
927 warn("test")
928
929a=A()
930 """
931 rc, out, err = assert_python_ok("-c", code)
932 # note: "__main__" filename is not correct, it should be the name
933 # of the script
934 self.assertEqual(err, b'__main__:7: UserWarning: test')
935
Ezio Melotti2688e812013-01-10 06:52:23 +0200936
937def setUpModule():
Christian Heimesdae2a892008-04-19 00:55:37 +0000938 py_warnings.onceregistry.clear()
939 c_warnings.onceregistry.clear()
Christian Heimes33fe8092008-04-13 13:53:33 +0000940
Ezio Melotti2688e812013-01-10 06:52:23 +0200941tearDownModule = setUpModule
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000942
943if __name__ == "__main__":
Ezio Melotti2688e812013-01-10 06:52:23 +0200944 unittest.main()