blob: b519f0a623962f417f2b0b6e71f4cf300a0358a3 [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):
Victor Stinner1c405522015-09-03 00:07:47 +020047 self.old_unittest_module = unittest.case.warnings
Christian Heimes33fe8092008-04-13 13:53:33 +000048 # The __warningregistry__ needs to be in a pristine state for tests
49 # to work properly.
50 if '__warningregistry__' in globals():
51 del globals()['__warningregistry__']
52 if hasattr(warning_tests, '__warningregistry__'):
53 del warning_tests.__warningregistry__
54 if hasattr(sys, '__warningregistry__'):
55 del sys.__warningregistry__
56 # The 'warnings' module must be explicitly set so that the proper
57 # interaction between _warnings and 'warnings' can be controlled.
58 sys.modules['warnings'] = self.module
Victor Stinner1c405522015-09-03 00:07:47 +020059 # Ensure that unittest.TestCase.assertWarns() uses the same warnings
60 # module than warnings.catch_warnings(). Otherwise,
61 # warnings.catch_warnings() will be unable to remove the added filter.
62 unittest.case.warnings = self.module
Christian Heimes33fe8092008-04-13 13:53:33 +000063 super(BaseTest, self).setUp()
64
65 def tearDown(self):
66 sys.modules['warnings'] = original_warnings
Victor Stinner1c405522015-09-03 00:07:47 +020067 unittest.case.warnings = self.old_unittest_module
Christian Heimes33fe8092008-04-13 13:53:33 +000068 super(BaseTest, self).tearDown()
69
Brett Cannon14ad5312014-08-22 10:44:47 -040070class PublicAPITests(BaseTest):
71
72 """Ensures that the correct values are exposed in the
73 public API.
74 """
75
76 def test_module_all_attribute(self):
77 self.assertTrue(hasattr(self.module, '__all__'))
78 target_api = ["warn", "warn_explicit", "showwarning",
79 "formatwarning", "filterwarnings", "simplefilter",
80 "resetwarnings", "catch_warnings"]
81 self.assertSetEqual(set(self.module.__all__),
82 set(target_api))
83
84class CPublicAPITests(PublicAPITests, unittest.TestCase):
85 module = c_warnings
86
87class PyPublicAPITests(PublicAPITests, unittest.TestCase):
88 module = py_warnings
Christian Heimes33fe8092008-04-13 13:53:33 +000089
Ezio Melotti2688e812013-01-10 06:52:23 +020090class FilterTests(BaseTest):
Christian Heimes33fe8092008-04-13 13:53:33 +000091
92 """Testing the filtering functionality."""
93
94 def test_error(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000095 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000096 self.module.resetwarnings()
97 self.module.filterwarnings("error", category=UserWarning)
98 self.assertRaises(UserWarning, self.module.warn,
99 "FilterTests.test_error")
100
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200101 def test_error_after_default(self):
102 with original_warnings.catch_warnings(module=self.module) as w:
103 self.module.resetwarnings()
104 message = "FilterTests.test_ignore_after_default"
105 def f():
106 self.module.warn(message, UserWarning)
107 f()
108 self.module.filterwarnings("error", category=UserWarning)
109 self.assertRaises(UserWarning, f)
110
Christian Heimes33fe8092008-04-13 13:53:33 +0000111 def test_ignore(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000112 with original_warnings.catch_warnings(record=True,
113 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000114 self.module.resetwarnings()
115 self.module.filterwarnings("ignore", category=UserWarning)
116 self.module.warn("FilterTests.test_ignore", UserWarning)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000117 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000118
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200119 def test_ignore_after_default(self):
120 with original_warnings.catch_warnings(record=True,
121 module=self.module) as w:
122 self.module.resetwarnings()
123 message = "FilterTests.test_ignore_after_default"
124 def f():
125 self.module.warn(message, UserWarning)
126 f()
127 self.module.filterwarnings("ignore", category=UserWarning)
128 f()
129 f()
130 self.assertEqual(len(w), 1)
131
Christian Heimes33fe8092008-04-13 13:53:33 +0000132 def test_always(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000133 with original_warnings.catch_warnings(record=True,
134 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000135 self.module.resetwarnings()
136 self.module.filterwarnings("always", category=UserWarning)
137 message = "FilterTests.test_always"
138 self.module.warn(message, UserWarning)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000139 self.assertTrue(message, w[-1].message)
Christian Heimes33fe8092008-04-13 13:53:33 +0000140 self.module.warn(message, UserWarning)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000141 self.assertTrue(w[-1].message, message)
Christian Heimes33fe8092008-04-13 13:53:33 +0000142
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200143 def test_always_after_default(self):
144 with original_warnings.catch_warnings(record=True,
145 module=self.module) as w:
146 self.module.resetwarnings()
147 message = "FilterTests.test_always_after_ignore"
148 def f():
149 self.module.warn(message, UserWarning)
150 f()
151 self.assertEqual(len(w), 1)
152 self.assertEqual(w[-1].message.args[0], message)
153 f()
154 self.assertEqual(len(w), 1)
155 self.module.filterwarnings("always", category=UserWarning)
156 f()
157 self.assertEqual(len(w), 2)
158 self.assertEqual(w[-1].message.args[0], message)
159 f()
160 self.assertEqual(len(w), 3)
161 self.assertEqual(w[-1].message.args[0], message)
162
Christian Heimes33fe8092008-04-13 13:53:33 +0000163 def test_default(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000164 with original_warnings.catch_warnings(record=True,
165 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000166 self.module.resetwarnings()
167 self.module.filterwarnings("default", category=UserWarning)
168 message = UserWarning("FilterTests.test_default")
169 for x in range(2):
170 self.module.warn(message, UserWarning)
171 if x == 0:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000172 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000173 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000174 elif x == 1:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000175 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000176 else:
177 raise ValueError("loop variant unhandled")
178
179 def test_module(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000180 with original_warnings.catch_warnings(record=True,
181 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000182 self.module.resetwarnings()
183 self.module.filterwarnings("module", category=UserWarning)
184 message = UserWarning("FilterTests.test_module")
185 self.module.warn(message, UserWarning)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000186 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000187 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000188 self.module.warn(message, UserWarning)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000189 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000190
191 def test_once(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000192 with original_warnings.catch_warnings(record=True,
193 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000194 self.module.resetwarnings()
195 self.module.filterwarnings("once", category=UserWarning)
196 message = UserWarning("FilterTests.test_once")
197 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
198 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000199 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000200 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000201 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
202 13)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000203 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000204 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
205 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000206 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000207
208 def test_inheritance(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000209 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000210 self.module.resetwarnings()
211 self.module.filterwarnings("error", category=Warning)
212 self.assertRaises(UserWarning, self.module.warn,
213 "FilterTests.test_inheritance", UserWarning)
214
215 def test_ordering(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000216 with original_warnings.catch_warnings(record=True,
217 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000218 self.module.resetwarnings()
219 self.module.filterwarnings("ignore", category=UserWarning)
220 self.module.filterwarnings("error", category=UserWarning,
221 append=True)
Brett Cannon1cd02472008-09-09 01:52:27 +0000222 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000223 try:
224 self.module.warn("FilterTests.test_ordering", UserWarning)
225 except UserWarning:
226 self.fail("order handling for actions failed")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000227 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000228
229 def test_filterwarnings(self):
230 # Test filterwarnings().
231 # Implicitly also tests resetwarnings().
Brett Cannon1cd02472008-09-09 01:52:27 +0000232 with original_warnings.catch_warnings(record=True,
233 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000234 self.module.filterwarnings("error", "", Warning, "", 0)
235 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
236
237 self.module.resetwarnings()
238 text = 'handle normally'
239 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000240 self.assertEqual(str(w[-1].message), text)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000241 self.assertTrue(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000242
243 self.module.filterwarnings("ignore", "", Warning, "", 0)
244 text = 'filtered out'
245 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000246 self.assertNotEqual(str(w[-1].message), text)
Christian Heimes33fe8092008-04-13 13:53:33 +0000247
248 self.module.resetwarnings()
249 self.module.filterwarnings("error", "hex*", Warning, "", 0)
250 self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
251 text = 'nonmatching text'
252 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000253 self.assertEqual(str(w[-1].message), text)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000254 self.assertTrue(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000255
Benjamin Petersondeff2b72015-05-03 11:23:37 -0400256 def test_mutate_filter_list(self):
257 class X:
258 def match(self, a):
259 L[:] = []
260
261 L = [("default",X(),UserWarning,X(),0) for i in range(2)]
262 with original_warnings.catch_warnings(record=True,
263 module=self.module) as w:
264 self.module.filters = L
265 self.module.warn_explicit(UserWarning("b"), None, "f.py", 42)
266 self.assertEqual(str(w[-1].message), "b")
267
Ezio Melotti2688e812013-01-10 06:52:23 +0200268class CFilterTests(FilterTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000269 module = c_warnings
270
Ezio Melotti2688e812013-01-10 06:52:23 +0200271class PyFilterTests(FilterTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000272 module = py_warnings
273
274
Ezio Melotti2688e812013-01-10 06:52:23 +0200275class WarnTests(BaseTest):
Christian Heimes33fe8092008-04-13 13:53:33 +0000276
277 """Test warnings.warn() and warnings.warn_explicit()."""
278
279 def test_message(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000280 with original_warnings.catch_warnings(record=True,
281 module=self.module) as w:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000282 self.module.simplefilter("once")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000283 for i in range(4):
Christian Heimes33fe8092008-04-13 13:53:33 +0000284 text = 'multi %d' %i # Different text on each call.
285 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000286 self.assertEqual(str(w[-1].message), text)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000287 self.assertTrue(w[-1].category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000288
Brett Cannon54bd41d2008-09-02 04:01:42 +0000289 # Issue 3639
290 def test_warn_nonstandard_types(self):
291 # warn() should handle non-standard types without issue.
292 for ob in (Warning, None, 42):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000293 with original_warnings.catch_warnings(record=True,
294 module=self.module) as w:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000295 self.module.simplefilter("once")
Brett Cannon54bd41d2008-09-02 04:01:42 +0000296 self.module.warn(ob)
297 # Don't directly compare objects since
298 # ``Warning() != Warning()``.
Ezio Melottib3aedd42010-11-20 19:04:17 +0000299 self.assertEqual(str(w[-1].message), str(UserWarning(ob)))
Brett Cannon54bd41d2008-09-02 04:01:42 +0000300
Guido van Rossumd8faa362007-04-27 19:54:29 +0000301 def test_filename(self):
Christian Heimes33fe8092008-04-13 13:53:33 +0000302 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000303 with original_warnings.catch_warnings(record=True,
304 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000305 warning_tests.inner("spam1")
Brett Cannon1cd02472008-09-09 01:52:27 +0000306 self.assertEqual(os.path.basename(w[-1].filename),
307 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000308 warning_tests.outer("spam2")
Brett Cannon1cd02472008-09-09 01:52:27 +0000309 self.assertEqual(os.path.basename(w[-1].filename),
310 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000311
312 def test_stacklevel(self):
313 # Test stacklevel argument
314 # make sure all messages are different, so the warning won't be skipped
Christian Heimes33fe8092008-04-13 13:53:33 +0000315 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000316 with original_warnings.catch_warnings(record=True,
317 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000318 warning_tests.inner("spam3", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000319 self.assertEqual(os.path.basename(w[-1].filename),
320 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000321 warning_tests.outer("spam4", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000322 self.assertEqual(os.path.basename(w[-1].filename),
323 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000324
Christian Heimes33fe8092008-04-13 13:53:33 +0000325 warning_tests.inner("spam5", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000326 self.assertEqual(os.path.basename(w[-1].filename),
327 "test_warnings.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000328 warning_tests.outer("spam6", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000329 self.assertEqual(os.path.basename(w[-1].filename),
330 "warning_tests.py")
Christian Heimes5d8da202008-05-06 13:58:24 +0000331 warning_tests.outer("spam6.5", stacklevel=3)
Brett Cannon1cd02472008-09-09 01:52:27 +0000332 self.assertEqual(os.path.basename(w[-1].filename),
333 "test_warnings.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000334
Christian Heimes33fe8092008-04-13 13:53:33 +0000335 warning_tests.inner("spam7", stacklevel=9999)
Brett Cannon1cd02472008-09-09 01:52:27 +0000336 self.assertEqual(os.path.basename(w[-1].filename),
337 "sys")
Christian Heimes33fe8092008-04-13 13:53:33 +0000338
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000339 def test_missing_filename_not_main(self):
340 # If __file__ is not specified and __main__ is not the module name,
341 # then __file__ should be set to the module name.
342 filename = warning_tests.__file__
343 try:
344 del warning_tests.__file__
345 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000346 with original_warnings.catch_warnings(record=True,
347 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000348 warning_tests.inner("spam8", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000349 self.assertEqual(w[-1].filename, warning_tests.__name__)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000350 finally:
351 warning_tests.__file__ = filename
352
Serhiy Storchaka43767632013-11-03 21:31:38 +0200353 @unittest.skipUnless(hasattr(sys, 'argv'), 'test needs sys.argv')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000354 def test_missing_filename_main_with_argv(self):
355 # If __file__ is not specified and the caller is __main__ and sys.argv
356 # exists, then use sys.argv[0] as the file.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000357 filename = warning_tests.__file__
358 module_name = warning_tests.__name__
359 try:
360 del warning_tests.__file__
361 warning_tests.__name__ = '__main__'
362 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000363 with original_warnings.catch_warnings(record=True,
364 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000365 warning_tests.inner('spam9', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000366 self.assertEqual(w[-1].filename, sys.argv[0])
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000367 finally:
368 warning_tests.__file__ = filename
369 warning_tests.__name__ = module_name
370
371 def test_missing_filename_main_without_argv(self):
372 # If __file__ is not specified, the caller is __main__, and sys.argv
373 # is not set, then '__main__' is the file name.
374 filename = warning_tests.__file__
375 module_name = warning_tests.__name__
376 argv = sys.argv
377 try:
378 del warning_tests.__file__
379 warning_tests.__name__ = '__main__'
380 del sys.argv
381 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000382 with original_warnings.catch_warnings(record=True,
383 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000384 warning_tests.inner('spam10', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000385 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000386 finally:
387 warning_tests.__file__ = filename
388 warning_tests.__name__ = module_name
389 sys.argv = argv
390
Christian Heimesdaaf8ee2008-05-04 23:58:41 +0000391 def test_missing_filename_main_with_argv_empty_string(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000392 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
393 # is the empty string, then '__main__ is the file name.
394 # Tests issue 2743.
395 file_name = warning_tests.__file__
396 module_name = warning_tests.__name__
397 argv = sys.argv
398 try:
399 del warning_tests.__file__
400 warning_tests.__name__ = '__main__'
401 sys.argv = ['']
402 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000403 with original_warnings.catch_warnings(record=True,
404 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000405 warning_tests.inner('spam11', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000406 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000407 finally:
408 warning_tests.__file__ = file_name
409 warning_tests.__name__ = module_name
410 sys.argv = argv
411
Victor Stinnera4c704b2013-10-29 23:43:41 +0100412 def test_warn_explicit_non_ascii_filename(self):
413 with original_warnings.catch_warnings(record=True,
414 module=self.module) as w:
415 self.module.resetwarnings()
416 self.module.filterwarnings("always", category=UserWarning)
Victor Stinnerc0e07a32013-10-29 23:58:05 +0100417 for filename in ("nonascii\xe9\u20ac", "surrogate\udc80"):
418 try:
419 os.fsencode(filename)
420 except UnicodeEncodeError:
421 continue
422 self.module.warn_explicit("text", UserWarning, filename, 1)
423 self.assertEqual(w[-1].filename, filename)
Victor Stinnera4c704b2013-10-29 23:43:41 +0100424
Brett Cannondb734912008-06-27 00:52:15 +0000425 def test_warn_explicit_type_errors(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200426 # warn_explicit() should error out gracefully if it is given objects
Brett Cannondb734912008-06-27 00:52:15 +0000427 # of the wrong types.
428 # lineno is expected to be an integer.
429 self.assertRaises(TypeError, self.module.warn_explicit,
430 None, UserWarning, None, None)
431 # Either 'message' needs to be an instance of Warning or 'category'
432 # needs to be a subclass.
433 self.assertRaises(TypeError, self.module.warn_explicit,
434 None, None, None, 1)
435 # 'registry' must be a dict or None.
436 self.assertRaises((TypeError, AttributeError),
437 self.module.warn_explicit,
438 None, Warning, None, 1, registry=42)
439
Hirokazu Yamamoto1c0c0032009-07-17 06:55:42 +0000440 def test_bad_str(self):
441 # issue 6415
442 # Warnings instance with a bad format string for __str__ should not
443 # trigger a bus error.
444 class BadStrWarning(Warning):
445 """Warning with a bad format string for __str__."""
446 def __str__(self):
447 return ("A bad formatted string %(err)" %
448 {"err" : "there is no %(err)s"})
449
450 with self.assertRaises(ValueError):
451 self.module.warn(BadStrWarning())
452
453
Ezio Melotti2688e812013-01-10 06:52:23 +0200454class CWarnTests(WarnTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000455 module = c_warnings
456
Nick Coghlanfce769e2009-04-11 14:30:59 +0000457 # As an early adopter, we sanity check the
458 # test.support.import_fresh_module utility function
459 def test_accelerated(self):
460 self.assertFalse(original_warnings is self.module)
461 self.assertFalse(hasattr(self.module.warn, '__code__'))
462
Ezio Melotti2688e812013-01-10 06:52:23 +0200463class PyWarnTests(WarnTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000464 module = py_warnings
465
Nick Coghlanfce769e2009-04-11 14:30:59 +0000466 # As an early adopter, we sanity check the
467 # test.support.import_fresh_module utility function
468 def test_pure_python(self):
469 self.assertFalse(original_warnings is self.module)
470 self.assertTrue(hasattr(self.module.warn, '__code__'))
471
Christian Heimes33fe8092008-04-13 13:53:33 +0000472
Ezio Melotti2688e812013-01-10 06:52:23 +0200473class WCmdLineTests(BaseTest):
Christian Heimes33fe8092008-04-13 13:53:33 +0000474
475 def test_improper_input(self):
476 # Uses the private _setoption() function to test the parsing
477 # of command-line warning arguments
Brett Cannon1cd02472008-09-09 01:52:27 +0000478 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000479 self.assertRaises(self.module._OptionError,
480 self.module._setoption, '1:2:3:4:5:6')
481 self.assertRaises(self.module._OptionError,
482 self.module._setoption, 'bogus::Warning')
483 self.assertRaises(self.module._OptionError,
484 self.module._setoption, 'ignore:2::4:-5')
485 self.module._setoption('error::Warning::0')
486 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
487
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000488 def test_improper_option(self):
489 # Same as above, but check that the message is printed out when
490 # the interpreter is executed. This also checks that options are
491 # actually parsed at all.
492 rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")
493 self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)
494
495 def test_warnings_bootstrap(self):
496 # Check that the warnings module does get loaded when -W<some option>
497 # is used (see issue #10372 for an example of silent bootstrap failure).
498 rc, out, err = assert_python_ok("-Wi", "-c",
499 "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
500 # '-Wi' was observed
501 self.assertFalse(out.strip())
502 self.assertNotIn(b'RuntimeWarning', err)
503
Ezio Melotti2688e812013-01-10 06:52:23 +0200504class CWCmdLineTests(WCmdLineTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000505 module = c_warnings
506
Ezio Melotti2688e812013-01-10 06:52:23 +0200507class PyWCmdLineTests(WCmdLineTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000508 module = py_warnings
509
510
Ezio Melotti2688e812013-01-10 06:52:23 +0200511class _WarningsTests(BaseTest, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000512
513 """Tests specific to the _warnings module."""
514
515 module = c_warnings
516
517 def test_filter(self):
518 # Everything should function even if 'filters' is not in warnings.
Brett Cannon1cd02472008-09-09 01:52:27 +0000519 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000520 self.module.filterwarnings("error", "", Warning, "", 0)
521 self.assertRaises(UserWarning, self.module.warn,
522 'convert to error')
523 del self.module.filters
524 self.assertRaises(UserWarning, self.module.warn,
525 'convert to error')
526
527 def test_onceregistry(self):
528 # Replacing or removing the onceregistry should be okay.
529 global __warningregistry__
530 message = UserWarning('onceregistry test')
531 try:
532 original_registry = self.module.onceregistry
533 __warningregistry__ = {}
Brett Cannon1cd02472008-09-09 01:52:27 +0000534 with original_warnings.catch_warnings(record=True,
535 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000536 self.module.resetwarnings()
537 self.module.filterwarnings("once", category=UserWarning)
538 self.module.warn_explicit(message, UserWarning, "file", 42)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000539 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000540 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000541 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000542 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000543 # Test the resetting of onceregistry.
544 self.module.onceregistry = {}
545 __warningregistry__ = {}
546 self.module.warn('onceregistry test')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000547 self.assertEqual(w[-1].message.args, message.args)
Christian Heimes33fe8092008-04-13 13:53:33 +0000548 # Removal of onceregistry is okay.
Brett Cannon1cd02472008-09-09 01:52:27 +0000549 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000550 del self.module.onceregistry
551 __warningregistry__ = {}
552 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000553 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000554 finally:
555 self.module.onceregistry = original_registry
556
Brett Cannon0759dd62009-04-01 18:13:07 +0000557 def test_default_action(self):
558 # Replacing or removing defaultaction should be okay.
559 message = UserWarning("defaultaction test")
560 original = self.module.defaultaction
561 try:
562 with original_warnings.catch_warnings(record=True,
563 module=self.module) as w:
564 self.module.resetwarnings()
565 registry = {}
566 self.module.warn_explicit(message, UserWarning, "<test>", 42,
567 registry=registry)
568 self.assertEqual(w[-1].message, message)
569 self.assertEqual(len(w), 1)
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200570 # One actual registry key plus the "version" key
571 self.assertEqual(len(registry), 2)
572 self.assertIn("version", registry)
Brett Cannon0759dd62009-04-01 18:13:07 +0000573 del w[:]
574 # Test removal.
575 del self.module.defaultaction
576 __warningregistry__ = {}
577 registry = {}
578 self.module.warn_explicit(message, UserWarning, "<test>", 43,
579 registry=registry)
580 self.assertEqual(w[-1].message, message)
581 self.assertEqual(len(w), 1)
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200582 self.assertEqual(len(registry), 2)
Brett Cannon0759dd62009-04-01 18:13:07 +0000583 del w[:]
584 # Test setting.
585 self.module.defaultaction = "ignore"
586 __warningregistry__ = {}
587 registry = {}
588 self.module.warn_explicit(message, UserWarning, "<test>", 44,
589 registry=registry)
590 self.assertEqual(len(w), 0)
591 finally:
592 self.module.defaultaction = original
593
Christian Heimes33fe8092008-04-13 13:53:33 +0000594 def test_showwarning_missing(self):
595 # Test that showwarning() missing is okay.
596 text = 'del showwarning test'
Brett Cannon1cd02472008-09-09 01:52:27 +0000597 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000598 self.module.filterwarnings("always", category=UserWarning)
599 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000600 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000601 self.module.warn(text)
602 result = stream.getvalue()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000603 self.assertIn(text, result)
Christian Heimes33fe8092008-04-13 13:53:33 +0000604
Christian Heimes8dc226f2008-05-06 23:45:46 +0000605 def test_showwarning_not_callable(self):
Brett Cannonfcc05272009-04-01 20:27:29 +0000606 with original_warnings.catch_warnings(module=self.module):
607 self.module.filterwarnings("always", category=UserWarning)
Brett Cannon52a7d982011-07-17 19:17:55 -0700608 self.module.showwarning = print
609 with support.captured_output('stdout'):
610 self.module.warn('Warning!')
Brett Cannonfcc05272009-04-01 20:27:29 +0000611 self.module.showwarning = 23
Brett Cannon52a7d982011-07-17 19:17:55 -0700612 self.assertRaises(TypeError, self.module.warn, "Warning!")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000613
Christian Heimes33fe8092008-04-13 13:53:33 +0000614 def test_show_warning_output(self):
615 # With showarning() missing, make sure that output is okay.
616 text = 'test show_warning'
Brett Cannon1cd02472008-09-09 01:52:27 +0000617 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000618 self.module.filterwarnings("always", category=UserWarning)
619 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000620 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000621 warning_tests.inner(text)
622 result = stream.getvalue()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000623 self.assertEqual(result.count('\n'), 2,
Christian Heimes33fe8092008-04-13 13:53:33 +0000624 "Too many newlines in %r" % result)
625 first_line, second_line = result.split('\n', 1)
626 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Neal Norwitz32dde222008-04-15 06:43:13 +0000627 first_line_parts = first_line.rsplit(':', 3)
628 path, line, warning_class, message = first_line_parts
Christian Heimes33fe8092008-04-13 13:53:33 +0000629 line = int(line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000630 self.assertEqual(expected_file, path)
631 self.assertEqual(warning_class, ' ' + UserWarning.__name__)
632 self.assertEqual(message, ' ' + text)
Christian Heimes33fe8092008-04-13 13:53:33 +0000633 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
634 assert expected_line
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000635 self.assertEqual(second_line, expected_line)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000636
Victor Stinner8b0508e2011-07-04 02:43:09 +0200637 def test_filename_none(self):
638 # issue #12467: race condition if a warning is emitted at shutdown
639 globals_dict = globals()
640 oldfile = globals_dict['__file__']
641 try:
Brett Cannon52a7d982011-07-17 19:17:55 -0700642 catch = original_warnings.catch_warnings(record=True,
643 module=self.module)
644 with catch as w:
Victor Stinner8b0508e2011-07-04 02:43:09 +0200645 self.module.filterwarnings("always", category=UserWarning)
646 globals_dict['__file__'] = None
647 original_warnings.warn('test', UserWarning)
Brett Cannon52a7d982011-07-17 19:17:55 -0700648 self.assertTrue(len(w))
Victor Stinner8b0508e2011-07-04 02:43:09 +0200649 finally:
650 globals_dict['__file__'] = oldfile
651
Serhiy Storchaka60599522014-12-10 22:59:55 +0200652 def test_stderr_none(self):
653 rc, stdout, stderr = assert_python_ok("-c",
654 "import sys; sys.stderr = None; "
655 "import warnings; warnings.simplefilter('always'); "
656 "warnings.warn('Warning!')")
657 self.assertEqual(stdout, b'')
658 self.assertNotIn(b'Warning!', stderr)
659 self.assertNotIn(b'Error', stderr)
660
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000661
Ezio Melotti2688e812013-01-10 06:52:23 +0200662class WarningsDisplayTests(BaseTest):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000663
Christian Heimes33fe8092008-04-13 13:53:33 +0000664 """Test the displaying of warnings and the ability to overload functions
665 related to displaying warnings."""
666
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000667 def test_formatwarning(self):
668 message = "msg"
669 category = Warning
670 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
671 line_num = 3
672 file_line = linecache.getline(file_name, line_num).strip()
Christian Heimes33fe8092008-04-13 13:53:33 +0000673 format = "%s:%s: %s: %s\n %s\n"
674 expect = format % (file_name, line_num, category.__name__, message,
675 file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000676 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000677 category, file_name, line_num))
678 # Test the 'line' argument.
679 file_line += " for the win!"
680 expect = format % (file_name, line_num, category.__name__, message,
681 file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000682 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000683 category, file_name, line_num, file_line))
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000684
685 def test_showwarning(self):
686 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
687 line_num = 3
688 expected_file_line = linecache.getline(file_name, line_num).strip()
689 message = 'msg'
690 category = Warning
691 file_object = StringIO()
Christian Heimes33fe8092008-04-13 13:53:33 +0000692 expect = self.module.formatwarning(message, category, file_name,
693 line_num)
694 self.module.showwarning(message, category, file_name, line_num,
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000695 file_object)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000696 self.assertEqual(file_object.getvalue(), expect)
Christian Heimes33fe8092008-04-13 13:53:33 +0000697 # Test 'line' argument.
698 expected_file_line += "for the win!"
699 expect = self.module.formatwarning(message, category, file_name,
700 line_num, expected_file_line)
701 file_object = StringIO()
702 self.module.showwarning(message, category, file_name, line_num,
703 file_object, expected_file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000704 self.assertEqual(expect, file_object.getvalue())
Christian Heimes33fe8092008-04-13 13:53:33 +0000705
Ezio Melotti2688e812013-01-10 06:52:23 +0200706class CWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000707 module = c_warnings
708
Ezio Melotti2688e812013-01-10 06:52:23 +0200709class PyWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000710 module = py_warnings
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000711
Brett Cannon1cd02472008-09-09 01:52:27 +0000712
Brett Cannonec92e182008-09-02 02:46:59 +0000713class CatchWarningTests(BaseTest):
Nick Coghlanb1304932008-07-13 12:25:08 +0000714
Brett Cannonec92e182008-09-02 02:46:59 +0000715 """Test catch_warnings()."""
716
717 def test_catch_warnings_restore(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000718 wmod = self.module
719 orig_filters = wmod.filters
720 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000721 # Ensure both showwarning and filters are restored when recording
722 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlanb1304932008-07-13 12:25:08 +0000723 wmod.filters = wmod.showwarning = object()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000724 self.assertTrue(wmod.filters is orig_filters)
725 self.assertTrue(wmod.showwarning is orig_showwarning)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000726 # Same test, but with recording disabled
727 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlanb1304932008-07-13 12:25:08 +0000728 wmod.filters = wmod.showwarning = object()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000729 self.assertTrue(wmod.filters is orig_filters)
730 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000731
Brett Cannonec92e182008-09-02 02:46:59 +0000732 def test_catch_warnings_recording(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000733 wmod = self.module
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000734 # Ensure warnings are recorded when requested
735 with wmod.catch_warnings(module=wmod, record=True) as w:
Brett Cannonec92e182008-09-02 02:46:59 +0000736 self.assertEqual(w, [])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000737 self.assertTrue(type(w) is list)
Nick Coghlanb1304932008-07-13 12:25:08 +0000738 wmod.simplefilter("always")
739 wmod.warn("foo")
Brett Cannon1cd02472008-09-09 01:52:27 +0000740 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlanb1304932008-07-13 12:25:08 +0000741 wmod.warn("bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000742 self.assertEqual(str(w[-1].message), "bar")
Brett Cannonec92e182008-09-02 02:46:59 +0000743 self.assertEqual(str(w[0].message), "foo")
744 self.assertEqual(str(w[1].message), "bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000745 del w[:]
Brett Cannonec92e182008-09-02 02:46:59 +0000746 self.assertEqual(w, [])
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000747 # Ensure warnings are not recorded when not requested
Nick Coghlanb1304932008-07-13 12:25:08 +0000748 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000749 with wmod.catch_warnings(module=wmod, record=False) as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000750 self.assertTrue(w is None)
751 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000752
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000753 def test_catch_warnings_reentry_guard(self):
754 wmod = self.module
755 # Ensure catch_warnings is protected against incorrect usage
756 x = wmod.catch_warnings(module=wmod, record=True)
757 self.assertRaises(RuntimeError, x.__exit__)
758 with x:
759 self.assertRaises(RuntimeError, x.__enter__)
760 # Same test, but with recording disabled
761 x = wmod.catch_warnings(module=wmod, record=False)
762 self.assertRaises(RuntimeError, x.__exit__)
763 with x:
764 self.assertRaises(RuntimeError, x.__enter__)
765
766 def test_catch_warnings_defaults(self):
767 wmod = self.module
768 orig_filters = wmod.filters
769 orig_showwarning = wmod.showwarning
770 # Ensure default behaviour is not to record warnings
771 with wmod.catch_warnings(module=wmod) as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000772 self.assertTrue(w is None)
773 self.assertTrue(wmod.showwarning is orig_showwarning)
774 self.assertTrue(wmod.filters is not orig_filters)
775 self.assertTrue(wmod.filters is orig_filters)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000776 if wmod is sys.modules['warnings']:
777 # Ensure the default module is this one
778 with wmod.catch_warnings() as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000779 self.assertTrue(w is None)
780 self.assertTrue(wmod.showwarning is orig_showwarning)
781 self.assertTrue(wmod.filters is not orig_filters)
782 self.assertTrue(wmod.filters is orig_filters)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000783
784 def test_check_warnings(self):
785 # Explicit tests for the test.support convenience wrapper
786 wmod = self.module
Florent Xicluna53b506be2010-03-18 20:00:57 +0000787 if wmod is not sys.modules['warnings']:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600788 self.skipTest('module to test is not loaded warnings module')
Florent Xicluna53b506be2010-03-18 20:00:57 +0000789 with support.check_warnings(quiet=False) as w:
790 self.assertEqual(w.warnings, [])
791 wmod.simplefilter("always")
792 wmod.warn("foo")
793 self.assertEqual(str(w.message), "foo")
794 wmod.warn("bar")
795 self.assertEqual(str(w.message), "bar")
796 self.assertEqual(str(w.warnings[0].message), "foo")
797 self.assertEqual(str(w.warnings[1].message), "bar")
798 w.reset()
799 self.assertEqual(w.warnings, [])
800
801 with support.check_warnings():
802 # defaults to quiet=True without argument
803 pass
804 with support.check_warnings(('foo', UserWarning)):
805 wmod.warn("foo")
806
807 with self.assertRaises(AssertionError):
808 with support.check_warnings(('', RuntimeWarning)):
809 # defaults to quiet=False with argument
810 pass
811 with self.assertRaises(AssertionError):
812 with support.check_warnings(('foo', RuntimeWarning)):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000813 wmod.warn("foo")
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000814
Ezio Melotti2688e812013-01-10 06:52:23 +0200815class CCatchWarningTests(CatchWarningTests, unittest.TestCase):
Nick Coghlanb1304932008-07-13 12:25:08 +0000816 module = c_warnings
817
Ezio Melotti2688e812013-01-10 06:52:23 +0200818class PyCatchWarningTests(CatchWarningTests, unittest.TestCase):
Nick Coghlanb1304932008-07-13 12:25:08 +0000819 module = py_warnings
820
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000821
Philip Jenvey0805ca32010-04-07 04:04:10 +0000822class EnvironmentVariableTests(BaseTest):
823
824 def test_single_warning(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100825 rc, stdout, stderr = assert_python_ok("-c",
826 "import sys; sys.stdout.write(str(sys.warnoptions))",
827 PYTHONWARNINGS="ignore::DeprecationWarning")
828 self.assertEqual(stdout, b"['ignore::DeprecationWarning']")
Philip Jenvey0805ca32010-04-07 04:04:10 +0000829
830 def test_comma_separated_warnings(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100831 rc, stdout, stderr = assert_python_ok("-c",
832 "import sys; sys.stdout.write(str(sys.warnoptions))",
833 PYTHONWARNINGS="ignore::DeprecationWarning,ignore::UnicodeWarning")
834 self.assertEqual(stdout,
835 b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
Philip Jenvey0805ca32010-04-07 04:04:10 +0000836
837 def test_envvar_and_command_line(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100838 rc, stdout, stderr = assert_python_ok("-Wignore::UnicodeWarning", "-c",
839 "import sys; sys.stdout.write(str(sys.warnoptions))",
840 PYTHONWARNINGS="ignore::DeprecationWarning")
841 self.assertEqual(stdout,
842 b"['ignore::UnicodeWarning', 'ignore::DeprecationWarning']")
Philip Jenvey0805ca32010-04-07 04:04:10 +0000843
Philip Jenveye53de3d2010-04-14 03:01:39 +0000844 @unittest.skipUnless(sys.getfilesystemencoding() != 'ascii',
845 'requires non-ascii filesystemencoding')
846 def test_nonascii(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100847 rc, stdout, stderr = assert_python_ok("-c",
848 "import sys; sys.stdout.write(str(sys.warnoptions))",
849 PYTHONIOENCODING="utf-8",
850 PYTHONWARNINGS="ignore:DeprecaciónWarning")
851 self.assertEqual(stdout,
852 "['ignore:DeprecaciónWarning']".encode('utf-8'))
Philip Jenveye53de3d2010-04-14 03:01:39 +0000853
Ezio Melotti2688e812013-01-10 06:52:23 +0200854class CEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
Philip Jenvey0805ca32010-04-07 04:04:10 +0000855 module = c_warnings
856
Ezio Melotti2688e812013-01-10 06:52:23 +0200857class PyEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
Philip Jenvey0805ca32010-04-07 04:04:10 +0000858 module = py_warnings
859
860
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000861class BootstrapTest(unittest.TestCase):
862 def test_issue_8766(self):
863 # "import encodings" emits a warning whereas the warnings is not loaded
Ezio Melotti42da6632011-03-15 05:18:48 +0200864 # or not completely loaded (warnings imports indirectly encodings by
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000865 # importing linecache) yet
866 with support.temp_cwd() as cwd, support.temp_cwd('encodings'):
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000867 # encodings loaded by initfsencoding()
Antoine Pitroubb08b362014-01-29 23:44:05 +0100868 assert_python_ok('-c', 'pass', PYTHONPATH=cwd)
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000869
870 # Use -W to load warnings module at startup
Antoine Pitroubb08b362014-01-29 23:44:05 +0100871 assert_python_ok('-c', 'pass', '-W', 'always', PYTHONPATH=cwd)
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000872
Victor Stinnerd1b48992013-10-28 19:16:21 +0100873class FinalizationTest(unittest.TestCase):
874 def test_finalization(self):
875 # Issue #19421: warnings.warn() should not crash
876 # during Python finalization
877 code = """
878import warnings
879warn = warnings.warn
880
881class A:
882 def __del__(self):
883 warn("test")
884
885a=A()
886 """
887 rc, out, err = assert_python_ok("-c", code)
888 # note: "__main__" filename is not correct, it should be the name
889 # of the script
890 self.assertEqual(err, b'__main__:7: UserWarning: test')
891
Ezio Melotti2688e812013-01-10 06:52:23 +0200892
893def setUpModule():
Christian Heimesdae2a892008-04-19 00:55:37 +0000894 py_warnings.onceregistry.clear()
895 c_warnings.onceregistry.clear()
Christian Heimes33fe8092008-04-13 13:53:33 +0000896
Ezio Melotti2688e812013-01-10 06:52:23 +0200897tearDownModule = setUpModule
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000898
899if __name__ == "__main__":
Ezio Melotti2688e812013-01-10 06:52:23 +0200900 unittest.main()