blob: 303ca71e4b2ca45f20a1cd746e4ce23fcdc9cf28 [file] [log] [blame]
Christian Heimes33fe8092008-04-13 13:53:33 +00001from contextlib import contextmanager
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00002import linecache
Raymond Hettingerdc9dcf12003-07-13 06:15:11 +00003import os
Christian Heimes5fb7c2a2007-12-24 08:52:31 +00004from io import StringIO
Guido van Rossum61e21b52007-08-20 19:06:03 +00005import sys
Raymond Hettingerd6f6e502003-07-13 08:37:40 +00006import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00007from test import support
Antoine Pitrou69994412014-04-29 00:56:08 +02008from test.script_helper import assert_python_ok, assert_python_failure
Jeremy Hylton85014662003-07-11 15:37:59 +00009
Guido van Rossum805365e2007-05-07 22:24:25 +000010from test import warning_tests
Jeremy Hylton85014662003-07-11 15:37:59 +000011
Christian Heimes33fe8092008-04-13 13:53:33 +000012import warnings as original_warnings
Jeremy Hylton85014662003-07-11 15:37:59 +000013
Nick Coghlan47384702009-04-22 16:13:36 +000014py_warnings = support.import_fresh_module('warnings', blocked=['_warnings'])
15c_warnings = support.import_fresh_module('warnings', fresh=['_warnings'])
Christian Heimes33fe8092008-04-13 13:53:33 +000016
17@contextmanager
18def warnings_state(module):
19 """Use a specific warnings implementation in warning_tests."""
20 global __warningregistry__
21 for to_clear in (sys, warning_tests):
22 try:
23 to_clear.__warningregistry__.clear()
24 except AttributeError:
25 pass
26 try:
27 __warningregistry__.clear()
28 except NameError:
29 pass
30 original_warnings = warning_tests.warnings
Florent Xiclunafd1b0932010-03-28 00:25:02 +000031 original_filters = module.filters
Christian Heimes33fe8092008-04-13 13:53:33 +000032 try:
Florent Xiclunafd1b0932010-03-28 00:25:02 +000033 module.filters = original_filters[:]
34 module.simplefilter("once")
Christian Heimes33fe8092008-04-13 13:53:33 +000035 warning_tests.warnings = module
36 yield
37 finally:
38 warning_tests.warnings = original_warnings
Florent Xiclunafd1b0932010-03-28 00:25:02 +000039 module.filters = original_filters
Christian Heimes33fe8092008-04-13 13:53:33 +000040
41
Ezio Melotti2688e812013-01-10 06:52:23 +020042class BaseTest:
Christian Heimes33fe8092008-04-13 13:53:33 +000043
44 """Basic bookkeeping required for testing."""
45
46 def setUp(self):
47 # The __warningregistry__ needs to be in a pristine state for tests
48 # to work properly.
49 if '__warningregistry__' in globals():
50 del globals()['__warningregistry__']
51 if hasattr(warning_tests, '__warningregistry__'):
52 del warning_tests.__warningregistry__
53 if hasattr(sys, '__warningregistry__'):
54 del sys.__warningregistry__
55 # The 'warnings' module must be explicitly set so that the proper
56 # interaction between _warnings and 'warnings' can be controlled.
57 sys.modules['warnings'] = self.module
58 super(BaseTest, self).setUp()
59
60 def tearDown(self):
61 sys.modules['warnings'] = original_warnings
62 super(BaseTest, self).tearDown()
63
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
Ezio Melotti2688e812013-01-10 06:52:23 +0200250class CFilterTests(FilterTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000251 module = c_warnings
252
Ezio Melotti2688e812013-01-10 06:52:23 +0200253class PyFilterTests(FilterTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000254 module = py_warnings
255
256
Ezio Melotti2688e812013-01-10 06:52:23 +0200257class WarnTests(BaseTest):
Christian Heimes33fe8092008-04-13 13:53:33 +0000258
259 """Test warnings.warn() and warnings.warn_explicit()."""
260
261 def test_message(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000262 with original_warnings.catch_warnings(record=True,
263 module=self.module) as w:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000264 self.module.simplefilter("once")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000265 for i in range(4):
Christian Heimes33fe8092008-04-13 13:53:33 +0000266 text = 'multi %d' %i # Different text on each call.
267 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000268 self.assertEqual(str(w[-1].message), text)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000269 self.assertTrue(w[-1].category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000270
Brett Cannon54bd41d2008-09-02 04:01:42 +0000271 # Issue 3639
272 def test_warn_nonstandard_types(self):
273 # warn() should handle non-standard types without issue.
274 for ob in (Warning, None, 42):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000275 with original_warnings.catch_warnings(record=True,
276 module=self.module) as w:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000277 self.module.simplefilter("once")
Brett Cannon54bd41d2008-09-02 04:01:42 +0000278 self.module.warn(ob)
279 # Don't directly compare objects since
280 # ``Warning() != Warning()``.
Ezio Melottib3aedd42010-11-20 19:04:17 +0000281 self.assertEqual(str(w[-1].message), str(UserWarning(ob)))
Brett Cannon54bd41d2008-09-02 04:01:42 +0000282
Guido van Rossumd8faa362007-04-27 19:54:29 +0000283 def test_filename(self):
Christian Heimes33fe8092008-04-13 13:53:33 +0000284 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000285 with original_warnings.catch_warnings(record=True,
286 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000287 warning_tests.inner("spam1")
Brett Cannon1cd02472008-09-09 01:52:27 +0000288 self.assertEqual(os.path.basename(w[-1].filename),
289 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000290 warning_tests.outer("spam2")
Brett Cannon1cd02472008-09-09 01:52:27 +0000291 self.assertEqual(os.path.basename(w[-1].filename),
292 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000293
294 def test_stacklevel(self):
295 # Test stacklevel argument
296 # make sure all messages are different, so the warning won't be skipped
Christian Heimes33fe8092008-04-13 13:53:33 +0000297 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000298 with original_warnings.catch_warnings(record=True,
299 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000300 warning_tests.inner("spam3", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000301 self.assertEqual(os.path.basename(w[-1].filename),
302 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000303 warning_tests.outer("spam4", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000304 self.assertEqual(os.path.basename(w[-1].filename),
305 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000306
Christian Heimes33fe8092008-04-13 13:53:33 +0000307 warning_tests.inner("spam5", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000308 self.assertEqual(os.path.basename(w[-1].filename),
309 "test_warnings.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000310 warning_tests.outer("spam6", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000311 self.assertEqual(os.path.basename(w[-1].filename),
312 "warning_tests.py")
Christian Heimes5d8da202008-05-06 13:58:24 +0000313 warning_tests.outer("spam6.5", stacklevel=3)
Brett Cannon1cd02472008-09-09 01:52:27 +0000314 self.assertEqual(os.path.basename(w[-1].filename),
315 "test_warnings.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000316
Christian Heimes33fe8092008-04-13 13:53:33 +0000317 warning_tests.inner("spam7", stacklevel=9999)
Brett Cannon1cd02472008-09-09 01:52:27 +0000318 self.assertEqual(os.path.basename(w[-1].filename),
319 "sys")
Christian Heimes33fe8092008-04-13 13:53:33 +0000320
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000321 def test_missing_filename_not_main(self):
322 # If __file__ is not specified and __main__ is not the module name,
323 # then __file__ should be set to the module name.
324 filename = warning_tests.__file__
325 try:
326 del warning_tests.__file__
327 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000328 with original_warnings.catch_warnings(record=True,
329 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000330 warning_tests.inner("spam8", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000331 self.assertEqual(w[-1].filename, warning_tests.__name__)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000332 finally:
333 warning_tests.__file__ = filename
334
Serhiy Storchaka43767632013-11-03 21:31:38 +0200335 @unittest.skipUnless(hasattr(sys, 'argv'), 'test needs sys.argv')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000336 def test_missing_filename_main_with_argv(self):
337 # If __file__ is not specified and the caller is __main__ and sys.argv
338 # exists, then use sys.argv[0] as the file.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000339 filename = warning_tests.__file__
340 module_name = warning_tests.__name__
341 try:
342 del warning_tests.__file__
343 warning_tests.__name__ = '__main__'
344 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000345 with original_warnings.catch_warnings(record=True,
346 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000347 warning_tests.inner('spam9', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000348 self.assertEqual(w[-1].filename, sys.argv[0])
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000349 finally:
350 warning_tests.__file__ = filename
351 warning_tests.__name__ = module_name
352
353 def test_missing_filename_main_without_argv(self):
354 # If __file__ is not specified, the caller is __main__, and sys.argv
355 # is not set, then '__main__' is the file name.
356 filename = warning_tests.__file__
357 module_name = warning_tests.__name__
358 argv = sys.argv
359 try:
360 del warning_tests.__file__
361 warning_tests.__name__ = '__main__'
362 del sys.argv
363 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000364 with original_warnings.catch_warnings(record=True,
365 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000366 warning_tests.inner('spam10', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000367 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000368 finally:
369 warning_tests.__file__ = filename
370 warning_tests.__name__ = module_name
371 sys.argv = argv
372
Christian Heimesdaaf8ee2008-05-04 23:58:41 +0000373 def test_missing_filename_main_with_argv_empty_string(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000374 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
375 # is the empty string, then '__main__ is the file name.
376 # Tests issue 2743.
377 file_name = warning_tests.__file__
378 module_name = warning_tests.__name__
379 argv = sys.argv
380 try:
381 del warning_tests.__file__
382 warning_tests.__name__ = '__main__'
383 sys.argv = ['']
384 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000385 with original_warnings.catch_warnings(record=True,
386 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000387 warning_tests.inner('spam11', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000388 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000389 finally:
390 warning_tests.__file__ = file_name
391 warning_tests.__name__ = module_name
392 sys.argv = argv
393
Victor Stinnera4c704b2013-10-29 23:43:41 +0100394 def test_warn_explicit_non_ascii_filename(self):
395 with original_warnings.catch_warnings(record=True,
396 module=self.module) as w:
397 self.module.resetwarnings()
398 self.module.filterwarnings("always", category=UserWarning)
Victor Stinnerc0e07a32013-10-29 23:58:05 +0100399 for filename in ("nonascii\xe9\u20ac", "surrogate\udc80"):
400 try:
401 os.fsencode(filename)
402 except UnicodeEncodeError:
403 continue
404 self.module.warn_explicit("text", UserWarning, filename, 1)
405 self.assertEqual(w[-1].filename, filename)
Victor Stinnera4c704b2013-10-29 23:43:41 +0100406
Brett Cannondb734912008-06-27 00:52:15 +0000407 def test_warn_explicit_type_errors(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200408 # warn_explicit() should error out gracefully if it is given objects
Brett Cannondb734912008-06-27 00:52:15 +0000409 # of the wrong types.
410 # lineno is expected to be an integer.
411 self.assertRaises(TypeError, self.module.warn_explicit,
412 None, UserWarning, None, None)
413 # Either 'message' needs to be an instance of Warning or 'category'
414 # needs to be a subclass.
415 self.assertRaises(TypeError, self.module.warn_explicit,
416 None, None, None, 1)
417 # 'registry' must be a dict or None.
418 self.assertRaises((TypeError, AttributeError),
419 self.module.warn_explicit,
420 None, Warning, None, 1, registry=42)
421
Hirokazu Yamamoto1c0c0032009-07-17 06:55:42 +0000422 def test_bad_str(self):
423 # issue 6415
424 # Warnings instance with a bad format string for __str__ should not
425 # trigger a bus error.
426 class BadStrWarning(Warning):
427 """Warning with a bad format string for __str__."""
428 def __str__(self):
429 return ("A bad formatted string %(err)" %
430 {"err" : "there is no %(err)s"})
431
432 with self.assertRaises(ValueError):
433 self.module.warn(BadStrWarning())
434
Berker Peksagd8089e02014-07-11 19:50:25 +0300435 def test_warning_classes(self):
436 class MyWarningClass(Warning):
437 pass
438
439 class NonWarningSubclass:
440 pass
441
442 # passing a non-subclass of Warning should raise a TypeError
443 with self.assertRaises(TypeError) as cm:
444 self.module.warn('bad warning category', '')
445 self.assertIn('category must be a Warning subclass, not ',
446 str(cm.exception))
447
448 with self.assertRaises(TypeError) as cm:
449 self.module.warn('bad warning category', NonWarningSubclass)
450 self.assertIn('category must be a Warning subclass, not ',
451 str(cm.exception))
452
453 # check that warning instances also raise a TypeError
454 with self.assertRaises(TypeError) as cm:
455 self.module.warn('bad warning category', MyWarningClass())
456 self.assertIn('category must be a Warning subclass, not ',
457 str(cm.exception))
458
Berker Peksagb8e973f2015-04-08 17:38:39 +0300459 with original_warnings.catch_warnings(module=self.module):
460 self.module.resetwarnings()
461 self.module.filterwarnings('default')
462 with self.assertWarns(MyWarningClass) as cm:
463 self.module.warn('good warning category', MyWarningClass)
464 self.assertEqual('good warning category', str(cm.warning))
Berker Peksagd8089e02014-07-11 19:50:25 +0300465
Berker Peksagb8e973f2015-04-08 17:38:39 +0300466 with self.assertWarns(UserWarning) as cm:
467 self.module.warn('good warning category', None)
468 self.assertEqual('good warning category', str(cm.warning))
Berker Peksagd8089e02014-07-11 19:50:25 +0300469
Berker Peksagb8e973f2015-04-08 17:38:39 +0300470 with self.assertWarns(MyWarningClass) as cm:
471 self.module.warn('good warning category', MyWarningClass)
472 self.assertIsInstance(cm.warning, Warning)
Hirokazu Yamamoto1c0c0032009-07-17 06:55:42 +0000473
Ezio Melotti2688e812013-01-10 06:52:23 +0200474class CWarnTests(WarnTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000475 module = c_warnings
476
Nick Coghlanfce769e2009-04-11 14:30:59 +0000477 # As an early adopter, we sanity check the
478 # test.support.import_fresh_module utility function
479 def test_accelerated(self):
480 self.assertFalse(original_warnings is self.module)
481 self.assertFalse(hasattr(self.module.warn, '__code__'))
482
Ezio Melotti2688e812013-01-10 06:52:23 +0200483class PyWarnTests(WarnTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000484 module = py_warnings
485
Nick Coghlanfce769e2009-04-11 14:30:59 +0000486 # As an early adopter, we sanity check the
487 # test.support.import_fresh_module utility function
488 def test_pure_python(self):
489 self.assertFalse(original_warnings is self.module)
490 self.assertTrue(hasattr(self.module.warn, '__code__'))
491
Christian Heimes33fe8092008-04-13 13:53:33 +0000492
Ezio Melotti2688e812013-01-10 06:52:23 +0200493class WCmdLineTests(BaseTest):
Christian Heimes33fe8092008-04-13 13:53:33 +0000494
495 def test_improper_input(self):
496 # Uses the private _setoption() function to test the parsing
497 # of command-line warning arguments
Brett Cannon1cd02472008-09-09 01:52:27 +0000498 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000499 self.assertRaises(self.module._OptionError,
500 self.module._setoption, '1:2:3:4:5:6')
501 self.assertRaises(self.module._OptionError,
502 self.module._setoption, 'bogus::Warning')
503 self.assertRaises(self.module._OptionError,
504 self.module._setoption, 'ignore:2::4:-5')
505 self.module._setoption('error::Warning::0')
506 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
507
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000508 def test_improper_option(self):
509 # Same as above, but check that the message is printed out when
510 # the interpreter is executed. This also checks that options are
511 # actually parsed at all.
512 rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")
513 self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)
514
515 def test_warnings_bootstrap(self):
516 # Check that the warnings module does get loaded when -W<some option>
517 # is used (see issue #10372 for an example of silent bootstrap failure).
518 rc, out, err = assert_python_ok("-Wi", "-c",
519 "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
520 # '-Wi' was observed
521 self.assertFalse(out.strip())
522 self.assertNotIn(b'RuntimeWarning', err)
523
Ezio Melotti2688e812013-01-10 06:52:23 +0200524class CWCmdLineTests(WCmdLineTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000525 module = c_warnings
526
Ezio Melotti2688e812013-01-10 06:52:23 +0200527class PyWCmdLineTests(WCmdLineTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000528 module = py_warnings
529
530
Ezio Melotti2688e812013-01-10 06:52:23 +0200531class _WarningsTests(BaseTest, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000532
533 """Tests specific to the _warnings module."""
534
535 module = c_warnings
536
537 def test_filter(self):
538 # Everything should function even if 'filters' is not in warnings.
Brett Cannon1cd02472008-09-09 01:52:27 +0000539 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000540 self.module.filterwarnings("error", "", Warning, "", 0)
541 self.assertRaises(UserWarning, self.module.warn,
542 'convert to error')
543 del self.module.filters
544 self.assertRaises(UserWarning, self.module.warn,
545 'convert to error')
546
547 def test_onceregistry(self):
548 # Replacing or removing the onceregistry should be okay.
549 global __warningregistry__
550 message = UserWarning('onceregistry test')
551 try:
552 original_registry = self.module.onceregistry
553 __warningregistry__ = {}
Brett Cannon1cd02472008-09-09 01:52:27 +0000554 with original_warnings.catch_warnings(record=True,
555 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000556 self.module.resetwarnings()
557 self.module.filterwarnings("once", category=UserWarning)
558 self.module.warn_explicit(message, UserWarning, "file", 42)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000559 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000560 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000561 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000562 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000563 # Test the resetting of onceregistry.
564 self.module.onceregistry = {}
565 __warningregistry__ = {}
566 self.module.warn('onceregistry test')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000567 self.assertEqual(w[-1].message.args, message.args)
Christian Heimes33fe8092008-04-13 13:53:33 +0000568 # Removal of onceregistry is okay.
Brett Cannon1cd02472008-09-09 01:52:27 +0000569 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000570 del self.module.onceregistry
571 __warningregistry__ = {}
572 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000573 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000574 finally:
575 self.module.onceregistry = original_registry
576
Brett Cannon0759dd62009-04-01 18:13:07 +0000577 def test_default_action(self):
578 # Replacing or removing defaultaction should be okay.
579 message = UserWarning("defaultaction test")
580 original = self.module.defaultaction
581 try:
582 with original_warnings.catch_warnings(record=True,
583 module=self.module) as w:
584 self.module.resetwarnings()
585 registry = {}
586 self.module.warn_explicit(message, UserWarning, "<test>", 42,
587 registry=registry)
588 self.assertEqual(w[-1].message, message)
589 self.assertEqual(len(w), 1)
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200590 # One actual registry key plus the "version" key
591 self.assertEqual(len(registry), 2)
592 self.assertIn("version", registry)
Brett Cannon0759dd62009-04-01 18:13:07 +0000593 del w[:]
594 # Test removal.
595 del self.module.defaultaction
596 __warningregistry__ = {}
597 registry = {}
598 self.module.warn_explicit(message, UserWarning, "<test>", 43,
599 registry=registry)
600 self.assertEqual(w[-1].message, message)
601 self.assertEqual(len(w), 1)
Antoine Pitroucb0a0062014-09-18 02:40:46 +0200602 self.assertEqual(len(registry), 2)
Brett Cannon0759dd62009-04-01 18:13:07 +0000603 del w[:]
604 # Test setting.
605 self.module.defaultaction = "ignore"
606 __warningregistry__ = {}
607 registry = {}
608 self.module.warn_explicit(message, UserWarning, "<test>", 44,
609 registry=registry)
610 self.assertEqual(len(w), 0)
611 finally:
612 self.module.defaultaction = original
613
Christian Heimes33fe8092008-04-13 13:53:33 +0000614 def test_showwarning_missing(self):
615 # Test that showwarning() missing is okay.
616 text = 'del showwarning test'
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 self.module.warn(text)
622 result = stream.getvalue()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000623 self.assertIn(text, result)
Christian Heimes33fe8092008-04-13 13:53:33 +0000624
Christian Heimes8dc226f2008-05-06 23:45:46 +0000625 def test_showwarning_not_callable(self):
Brett Cannonfcc05272009-04-01 20:27:29 +0000626 with original_warnings.catch_warnings(module=self.module):
627 self.module.filterwarnings("always", category=UserWarning)
Brett Cannon52a7d982011-07-17 19:17:55 -0700628 self.module.showwarning = print
629 with support.captured_output('stdout'):
630 self.module.warn('Warning!')
Brett Cannonfcc05272009-04-01 20:27:29 +0000631 self.module.showwarning = 23
Brett Cannon52a7d982011-07-17 19:17:55 -0700632 self.assertRaises(TypeError, self.module.warn, "Warning!")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000633
Christian Heimes33fe8092008-04-13 13:53:33 +0000634 def test_show_warning_output(self):
635 # With showarning() missing, make sure that output is okay.
636 text = 'test show_warning'
Brett Cannon1cd02472008-09-09 01:52:27 +0000637 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000638 self.module.filterwarnings("always", category=UserWarning)
639 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000640 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000641 warning_tests.inner(text)
642 result = stream.getvalue()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000643 self.assertEqual(result.count('\n'), 2,
Christian Heimes33fe8092008-04-13 13:53:33 +0000644 "Too many newlines in %r" % result)
645 first_line, second_line = result.split('\n', 1)
646 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Neal Norwitz32dde222008-04-15 06:43:13 +0000647 first_line_parts = first_line.rsplit(':', 3)
648 path, line, warning_class, message = first_line_parts
Christian Heimes33fe8092008-04-13 13:53:33 +0000649 line = int(line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000650 self.assertEqual(expected_file, path)
651 self.assertEqual(warning_class, ' ' + UserWarning.__name__)
652 self.assertEqual(message, ' ' + text)
Christian Heimes33fe8092008-04-13 13:53:33 +0000653 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
654 assert expected_line
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000655 self.assertEqual(second_line, expected_line)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000656
Victor Stinner8b0508e2011-07-04 02:43:09 +0200657 def test_filename_none(self):
658 # issue #12467: race condition if a warning is emitted at shutdown
659 globals_dict = globals()
660 oldfile = globals_dict['__file__']
661 try:
Brett Cannon52a7d982011-07-17 19:17:55 -0700662 catch = original_warnings.catch_warnings(record=True,
663 module=self.module)
664 with catch as w:
Victor Stinner8b0508e2011-07-04 02:43:09 +0200665 self.module.filterwarnings("always", category=UserWarning)
666 globals_dict['__file__'] = None
667 original_warnings.warn('test', UserWarning)
Brett Cannon52a7d982011-07-17 19:17:55 -0700668 self.assertTrue(len(w))
Victor Stinner8b0508e2011-07-04 02:43:09 +0200669 finally:
670 globals_dict['__file__'] = oldfile
671
Serhiy Storchaka60599522014-12-10 22:59:55 +0200672 def test_stderr_none(self):
673 rc, stdout, stderr = assert_python_ok("-c",
674 "import sys; sys.stderr = None; "
675 "import warnings; warnings.simplefilter('always'); "
676 "warnings.warn('Warning!')")
677 self.assertEqual(stdout, b'')
678 self.assertNotIn(b'Warning!', stderr)
679 self.assertNotIn(b'Error', stderr)
680
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000681
Ezio Melotti2688e812013-01-10 06:52:23 +0200682class WarningsDisplayTests(BaseTest):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000683
Christian Heimes33fe8092008-04-13 13:53:33 +0000684 """Test the displaying of warnings and the ability to overload functions
685 related to displaying warnings."""
686
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000687 def test_formatwarning(self):
688 message = "msg"
689 category = Warning
690 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
691 line_num = 3
692 file_line = linecache.getline(file_name, line_num).strip()
Christian Heimes33fe8092008-04-13 13:53:33 +0000693 format = "%s:%s: %s: %s\n %s\n"
694 expect = format % (file_name, line_num, category.__name__, message,
695 file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000696 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000697 category, file_name, line_num))
698 # Test the 'line' argument.
699 file_line += " for the win!"
700 expect = format % (file_name, line_num, category.__name__, message,
701 file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000702 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000703 category, file_name, line_num, file_line))
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000704
705 def test_showwarning(self):
706 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
707 line_num = 3
708 expected_file_line = linecache.getline(file_name, line_num).strip()
709 message = 'msg'
710 category = Warning
711 file_object = StringIO()
Christian Heimes33fe8092008-04-13 13:53:33 +0000712 expect = self.module.formatwarning(message, category, file_name,
713 line_num)
714 self.module.showwarning(message, category, file_name, line_num,
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000715 file_object)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000716 self.assertEqual(file_object.getvalue(), expect)
Christian Heimes33fe8092008-04-13 13:53:33 +0000717 # Test 'line' argument.
718 expected_file_line += "for the win!"
719 expect = self.module.formatwarning(message, category, file_name,
720 line_num, expected_file_line)
721 file_object = StringIO()
722 self.module.showwarning(message, category, file_name, line_num,
723 file_object, expected_file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000724 self.assertEqual(expect, file_object.getvalue())
Christian Heimes33fe8092008-04-13 13:53:33 +0000725
Ezio Melotti2688e812013-01-10 06:52:23 +0200726class CWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000727 module = c_warnings
728
Ezio Melotti2688e812013-01-10 06:52:23 +0200729class PyWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000730 module = py_warnings
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000731
Brett Cannon1cd02472008-09-09 01:52:27 +0000732
Brett Cannonec92e182008-09-02 02:46:59 +0000733class CatchWarningTests(BaseTest):
Nick Coghlanb1304932008-07-13 12:25:08 +0000734
Brett Cannonec92e182008-09-02 02:46:59 +0000735 """Test catch_warnings()."""
736
737 def test_catch_warnings_restore(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000738 wmod = self.module
739 orig_filters = wmod.filters
740 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000741 # Ensure both showwarning and filters are restored when recording
742 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlanb1304932008-07-13 12:25:08 +0000743 wmod.filters = wmod.showwarning = object()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000744 self.assertTrue(wmod.filters is orig_filters)
745 self.assertTrue(wmod.showwarning is orig_showwarning)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000746 # Same test, but with recording disabled
747 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlanb1304932008-07-13 12:25:08 +0000748 wmod.filters = wmod.showwarning = object()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000749 self.assertTrue(wmod.filters is orig_filters)
750 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000751
Brett Cannonec92e182008-09-02 02:46:59 +0000752 def test_catch_warnings_recording(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000753 wmod = self.module
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000754 # Ensure warnings are recorded when requested
755 with wmod.catch_warnings(module=wmod, record=True) as w:
Brett Cannonec92e182008-09-02 02:46:59 +0000756 self.assertEqual(w, [])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000757 self.assertTrue(type(w) is list)
Nick Coghlanb1304932008-07-13 12:25:08 +0000758 wmod.simplefilter("always")
759 wmod.warn("foo")
Brett Cannon1cd02472008-09-09 01:52:27 +0000760 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlanb1304932008-07-13 12:25:08 +0000761 wmod.warn("bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000762 self.assertEqual(str(w[-1].message), "bar")
Brett Cannonec92e182008-09-02 02:46:59 +0000763 self.assertEqual(str(w[0].message), "foo")
764 self.assertEqual(str(w[1].message), "bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000765 del w[:]
Brett Cannonec92e182008-09-02 02:46:59 +0000766 self.assertEqual(w, [])
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000767 # Ensure warnings are not recorded when not requested
Nick Coghlanb1304932008-07-13 12:25:08 +0000768 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000769 with wmod.catch_warnings(module=wmod, record=False) as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000770 self.assertTrue(w is None)
771 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000772
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000773 def test_catch_warnings_reentry_guard(self):
774 wmod = self.module
775 # Ensure catch_warnings is protected against incorrect usage
776 x = wmod.catch_warnings(module=wmod, record=True)
777 self.assertRaises(RuntimeError, x.__exit__)
778 with x:
779 self.assertRaises(RuntimeError, x.__enter__)
780 # Same test, but with recording disabled
781 x = wmod.catch_warnings(module=wmod, record=False)
782 self.assertRaises(RuntimeError, x.__exit__)
783 with x:
784 self.assertRaises(RuntimeError, x.__enter__)
785
786 def test_catch_warnings_defaults(self):
787 wmod = self.module
788 orig_filters = wmod.filters
789 orig_showwarning = wmod.showwarning
790 # Ensure default behaviour is not to record warnings
791 with wmod.catch_warnings(module=wmod) as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000792 self.assertTrue(w is None)
793 self.assertTrue(wmod.showwarning is orig_showwarning)
794 self.assertTrue(wmod.filters is not orig_filters)
795 self.assertTrue(wmod.filters is orig_filters)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000796 if wmod is sys.modules['warnings']:
797 # Ensure the default module is this one
798 with wmod.catch_warnings() as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000799 self.assertTrue(w is None)
800 self.assertTrue(wmod.showwarning is orig_showwarning)
801 self.assertTrue(wmod.filters is not orig_filters)
802 self.assertTrue(wmod.filters is orig_filters)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000803
804 def test_check_warnings(self):
805 # Explicit tests for the test.support convenience wrapper
806 wmod = self.module
Florent Xicluna53b506be2010-03-18 20:00:57 +0000807 if wmod is not sys.modules['warnings']:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600808 self.skipTest('module to test is not loaded warnings module')
Florent Xicluna53b506be2010-03-18 20:00:57 +0000809 with support.check_warnings(quiet=False) as w:
810 self.assertEqual(w.warnings, [])
811 wmod.simplefilter("always")
812 wmod.warn("foo")
813 self.assertEqual(str(w.message), "foo")
814 wmod.warn("bar")
815 self.assertEqual(str(w.message), "bar")
816 self.assertEqual(str(w.warnings[0].message), "foo")
817 self.assertEqual(str(w.warnings[1].message), "bar")
818 w.reset()
819 self.assertEqual(w.warnings, [])
820
821 with support.check_warnings():
822 # defaults to quiet=True without argument
823 pass
824 with support.check_warnings(('foo', UserWarning)):
825 wmod.warn("foo")
826
827 with self.assertRaises(AssertionError):
828 with support.check_warnings(('', RuntimeWarning)):
829 # defaults to quiet=False with argument
830 pass
831 with self.assertRaises(AssertionError):
832 with support.check_warnings(('foo', RuntimeWarning)):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000833 wmod.warn("foo")
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000834
Ezio Melotti2688e812013-01-10 06:52:23 +0200835class CCatchWarningTests(CatchWarningTests, unittest.TestCase):
Nick Coghlanb1304932008-07-13 12:25:08 +0000836 module = c_warnings
837
Ezio Melotti2688e812013-01-10 06:52:23 +0200838class PyCatchWarningTests(CatchWarningTests, unittest.TestCase):
Nick Coghlanb1304932008-07-13 12:25:08 +0000839 module = py_warnings
840
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000841
Philip Jenvey0805ca32010-04-07 04:04:10 +0000842class EnvironmentVariableTests(BaseTest):
843
844 def test_single_warning(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100845 rc, stdout, stderr = assert_python_ok("-c",
846 "import sys; sys.stdout.write(str(sys.warnoptions))",
847 PYTHONWARNINGS="ignore::DeprecationWarning")
848 self.assertEqual(stdout, b"['ignore::DeprecationWarning']")
Philip Jenvey0805ca32010-04-07 04:04:10 +0000849
850 def test_comma_separated_warnings(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100851 rc, stdout, stderr = assert_python_ok("-c",
852 "import sys; sys.stdout.write(str(sys.warnoptions))",
853 PYTHONWARNINGS="ignore::DeprecationWarning,ignore::UnicodeWarning")
854 self.assertEqual(stdout,
855 b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
Philip Jenvey0805ca32010-04-07 04:04:10 +0000856
857 def test_envvar_and_command_line(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100858 rc, stdout, stderr = assert_python_ok("-Wignore::UnicodeWarning", "-c",
859 "import sys; sys.stdout.write(str(sys.warnoptions))",
860 PYTHONWARNINGS="ignore::DeprecationWarning")
861 self.assertEqual(stdout,
Antoine Pitrou69994412014-04-29 00:56:08 +0200862 b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
863
864 def test_conflicting_envvar_and_command_line(self):
865 rc, stdout, stderr = assert_python_failure("-Werror::DeprecationWarning", "-c",
866 "import sys, warnings; sys.stdout.write(str(sys.warnoptions)); "
867 "warnings.warn('Message', DeprecationWarning)",
868 PYTHONWARNINGS="default::DeprecationWarning")
869 self.assertEqual(stdout,
870 b"['default::DeprecationWarning', 'error::DeprecationWarning']")
871 self.assertEqual(stderr.splitlines(),
872 [b"Traceback (most recent call last):",
873 b" File \"<string>\", line 1, in <module>",
874 b"DeprecationWarning: Message"])
Philip Jenvey0805ca32010-04-07 04:04:10 +0000875
Philip Jenveye53de3d2010-04-14 03:01:39 +0000876 @unittest.skipUnless(sys.getfilesystemencoding() != 'ascii',
877 'requires non-ascii filesystemencoding')
878 def test_nonascii(self):
Antoine Pitroubb08b362014-01-29 23:44:05 +0100879 rc, stdout, stderr = assert_python_ok("-c",
880 "import sys; sys.stdout.write(str(sys.warnoptions))",
881 PYTHONIOENCODING="utf-8",
882 PYTHONWARNINGS="ignore:DeprecaciónWarning")
883 self.assertEqual(stdout,
884 "['ignore:DeprecaciónWarning']".encode('utf-8'))
Philip Jenveye53de3d2010-04-14 03:01:39 +0000885
Ezio Melotti2688e812013-01-10 06:52:23 +0200886class CEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
Philip Jenvey0805ca32010-04-07 04:04:10 +0000887 module = c_warnings
888
Ezio Melotti2688e812013-01-10 06:52:23 +0200889class PyEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
Philip Jenvey0805ca32010-04-07 04:04:10 +0000890 module = py_warnings
891
892
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000893class BootstrapTest(unittest.TestCase):
894 def test_issue_8766(self):
895 # "import encodings" emits a warning whereas the warnings is not loaded
Ezio Melotti42da6632011-03-15 05:18:48 +0200896 # or not completely loaded (warnings imports indirectly encodings by
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000897 # importing linecache) yet
898 with support.temp_cwd() as cwd, support.temp_cwd('encodings'):
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000899 # encodings loaded by initfsencoding()
Antoine Pitroubb08b362014-01-29 23:44:05 +0100900 assert_python_ok('-c', 'pass', PYTHONPATH=cwd)
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000901
902 # Use -W to load warnings module at startup
Antoine Pitroubb08b362014-01-29 23:44:05 +0100903 assert_python_ok('-c', 'pass', '-W', 'always', PYTHONPATH=cwd)
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000904
Victor Stinnerd1b48992013-10-28 19:16:21 +0100905class FinalizationTest(unittest.TestCase):
906 def test_finalization(self):
907 # Issue #19421: warnings.warn() should not crash
908 # during Python finalization
909 code = """
910import warnings
911warn = warnings.warn
912
913class A:
914 def __del__(self):
915 warn("test")
916
917a=A()
918 """
919 rc, out, err = assert_python_ok("-c", code)
920 # note: "__main__" filename is not correct, it should be the name
921 # of the script
922 self.assertEqual(err, b'__main__:7: UserWarning: test')
923
Ezio Melotti2688e812013-01-10 06:52:23 +0200924
925def setUpModule():
Christian Heimesdae2a892008-04-19 00:55:37 +0000926 py_warnings.onceregistry.clear()
927 c_warnings.onceregistry.clear()
Christian Heimes33fe8092008-04-13 13:53:33 +0000928
Ezio Melotti2688e812013-01-10 06:52:23 +0200929tearDownModule = setUpModule
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000930
931if __name__ == "__main__":
Ezio Melotti2688e812013-01-10 06:52:23 +0200932 unittest.main()