blob: ae081eeee3f75a857afbdbe9e19ba7366831a258 [file] [log] [blame]
Brett Cannone9746892008-04-12 23:44:07 +00001from contextlib import contextmanager
Brett Cannon905c31c2007-12-20 10:09:52 +00002import linecache
Raymond Hettingerdc9dcf12003-07-13 06:15:11 +00003import os
Brett Cannon905c31c2007-12-20 10:09:52 +00004import StringIO
Brett Cannon855da6c2007-08-17 20:16:15 +00005import sys
Raymond Hettingerd6f6e502003-07-13 08:37:40 +00006import unittest
Philip Jenveyaebbaeb2010-04-06 23:24:45 +00007import subprocess
Raymond Hettingerd6f6e502003-07-13 08:37:40 +00008from test import test_support
Antoine Pitrou9c9e1b92010-11-10 14:03:31 +00009from test.script_helper import assert_python_ok
Jeremy Hylton85014662003-07-11 15:37:59 +000010
Walter Dörwalde1a9b422007-04-03 16:53:43 +000011import warning_tests
12
Brett Cannon667bb4f2008-04-13 02:42:36 +000013import warnings as original_warnings
14
Nick Coghlan5533ff62009-04-22 15:26:04 +000015py_warnings = test_support.import_fresh_module('warnings', blocked=['_warnings'])
16c_warnings = test_support.import_fresh_module('warnings', fresh=['_warnings'])
Brett Cannon667bb4f2008-04-13 02:42:36 +000017
Brett Cannone9746892008-04-12 23:44:07 +000018@contextmanager
19def warnings_state(module):
20 """Use a specific warnings implementation in warning_tests."""
21 global __warningregistry__
22 for to_clear in (sys, warning_tests):
23 try:
24 to_clear.__warningregistry__.clear()
25 except AttributeError:
26 pass
27 try:
28 __warningregistry__.clear()
29 except NameError:
30 pass
31 original_warnings = warning_tests.warnings
Florent Xiclunafd37dd42010-03-25 20:39:10 +000032 original_filters = module.filters
Brett Cannone9746892008-04-12 23:44:07 +000033 try:
Florent Xiclunafd37dd42010-03-25 20:39:10 +000034 module.filters = original_filters[:]
35 module.simplefilter("once")
Brett Cannone9746892008-04-12 23:44:07 +000036 warning_tests.warnings = module
37 yield
38 finally:
39 warning_tests.warnings = original_warnings
Florent Xiclunafd37dd42010-03-25 20:39:10 +000040 module.filters = original_filters
Brett Cannone9746892008-04-12 23:44:07 +000041
42
Brett Cannon667bb4f2008-04-13 02:42:36 +000043class BaseTest(unittest.TestCase):
Brett Cannone9746892008-04-12 23:44:07 +000044
Brett Cannon667bb4f2008-04-13 02:42:36 +000045 """Basic bookkeeping required for testing."""
Brett Cannone9746892008-04-12 23:44:07 +000046
47 def setUp(self):
Brett Cannon667bb4f2008-04-13 02:42:36 +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
59 super(BaseTest, self).setUp()
60
61 def tearDown(self):
62 sys.modules['warnings'] = original_warnings
63 super(BaseTest, self).tearDown()
64
Brett Cannon01408452014-08-22 10:50:47 -040065class PublicAPITests(BaseTest):
66
67 """Ensures that the correct values are exposed in the
68 public API.
69 """
70
71 def test_module_all_attribute(self):
72 self.assertTrue(hasattr(self.module, '__all__'))
73 target_api = ["warn", "warn_explicit", "showwarning",
74 "formatwarning", "filterwarnings", "simplefilter",
75 "resetwarnings", "catch_warnings"]
76 self.assertSetEqual(set(self.module.__all__),
77 set(target_api))
78
79class CPublicAPITests(PublicAPITests, unittest.TestCase):
80 module = c_warnings
81
82class PyPublicAPITests(PublicAPITests, unittest.TestCase):
83 module = py_warnings
Brett Cannon667bb4f2008-04-13 02:42:36 +000084
85class FilterTests(object):
86
87 """Testing the filtering functionality."""
Brett Cannone9746892008-04-12 23:44:07 +000088
89 def test_error(self):
Brett Cannon672237d2008-09-09 00:49:16 +000090 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +000091 self.module.resetwarnings()
92 self.module.filterwarnings("error", category=UserWarning)
93 self.assertRaises(UserWarning, self.module.warn,
94 "FilterTests.test_error")
95
96 def test_ignore(self):
Brett Cannon672237d2008-09-09 00:49:16 +000097 with original_warnings.catch_warnings(record=True,
98 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +000099 self.module.resetwarnings()
100 self.module.filterwarnings("ignore", category=UserWarning)
101 self.module.warn("FilterTests.test_ignore", UserWarning)
Ezio Melotti2623a372010-11-21 13:34:58 +0000102 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000103
104 def test_always(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000105 with original_warnings.catch_warnings(record=True,
106 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000107 self.module.resetwarnings()
108 self.module.filterwarnings("always", category=UserWarning)
109 message = "FilterTests.test_always"
110 self.module.warn(message, UserWarning)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000111 self.assertTrue(message, w[-1].message)
Brett Cannone9746892008-04-12 23:44:07 +0000112 self.module.warn(message, UserWarning)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000113 self.assertTrue(w[-1].message, message)
Brett Cannone9746892008-04-12 23:44:07 +0000114
115 def test_default(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000116 with original_warnings.catch_warnings(record=True,
117 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000118 self.module.resetwarnings()
119 self.module.filterwarnings("default", category=UserWarning)
120 message = UserWarning("FilterTests.test_default")
121 for x in xrange(2):
122 self.module.warn(message, UserWarning)
123 if x == 0:
Ezio Melotti2623a372010-11-21 13:34:58 +0000124 self.assertEqual(w[-1].message, message)
Brett Cannon672237d2008-09-09 00:49:16 +0000125 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000126 elif x == 1:
Ezio Melotti2623a372010-11-21 13:34:58 +0000127 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000128 else:
129 raise ValueError("loop variant unhandled")
130
131 def test_module(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000132 with original_warnings.catch_warnings(record=True,
133 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000134 self.module.resetwarnings()
135 self.module.filterwarnings("module", category=UserWarning)
136 message = UserWarning("FilterTests.test_module")
137 self.module.warn(message, UserWarning)
Ezio Melotti2623a372010-11-21 13:34:58 +0000138 self.assertEqual(w[-1].message, message)
Brett Cannon672237d2008-09-09 00:49:16 +0000139 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000140 self.module.warn(message, UserWarning)
Ezio Melotti2623a372010-11-21 13:34:58 +0000141 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000142
143 def test_once(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000144 with original_warnings.catch_warnings(record=True,
145 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000146 self.module.resetwarnings()
147 self.module.filterwarnings("once", category=UserWarning)
148 message = UserWarning("FilterTests.test_once")
149 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
150 42)
Ezio Melotti2623a372010-11-21 13:34:58 +0000151 self.assertEqual(w[-1].message, message)
Brett Cannon672237d2008-09-09 00:49:16 +0000152 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000153 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
154 13)
Ezio Melotti2623a372010-11-21 13:34:58 +0000155 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000156 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
157 42)
Ezio Melotti2623a372010-11-21 13:34:58 +0000158 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000159
160 def test_inheritance(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000161 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000162 self.module.resetwarnings()
163 self.module.filterwarnings("error", category=Warning)
164 self.assertRaises(UserWarning, self.module.warn,
165 "FilterTests.test_inheritance", UserWarning)
166
167 def test_ordering(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000168 with original_warnings.catch_warnings(record=True,
169 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000170 self.module.resetwarnings()
171 self.module.filterwarnings("ignore", category=UserWarning)
172 self.module.filterwarnings("error", category=UserWarning,
173 append=True)
Brett Cannon672237d2008-09-09 00:49:16 +0000174 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000175 try:
176 self.module.warn("FilterTests.test_ordering", UserWarning)
177 except UserWarning:
178 self.fail("order handling for actions failed")
Ezio Melotti2623a372010-11-21 13:34:58 +0000179 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000180
181 def test_filterwarnings(self):
182 # Test filterwarnings().
183 # Implicitly also tests resetwarnings().
Brett Cannon672237d2008-09-09 00:49:16 +0000184 with original_warnings.catch_warnings(record=True,
185 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000186 self.module.filterwarnings("error", "", Warning, "", 0)
187 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
188
189 self.module.resetwarnings()
190 text = 'handle normally'
191 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000192 self.assertEqual(str(w[-1].message), text)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000193 self.assertTrue(w[-1].category is UserWarning)
Brett Cannone9746892008-04-12 23:44:07 +0000194
195 self.module.filterwarnings("ignore", "", Warning, "", 0)
196 text = 'filtered out'
197 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000198 self.assertNotEqual(str(w[-1].message), text)
Brett Cannone9746892008-04-12 23:44:07 +0000199
200 self.module.resetwarnings()
201 self.module.filterwarnings("error", "hex*", Warning, "", 0)
202 self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
203 text = 'nonmatching text'
204 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000205 self.assertEqual(str(w[-1].message), text)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000206 self.assertTrue(w[-1].category is UserWarning)
Brett Cannone9746892008-04-12 23:44:07 +0000207
Martin Pantercdb8be42016-07-19 02:26:38 +0000208 def test_message_matching(self):
209 with original_warnings.catch_warnings(record=True,
210 module=self.module) as w:
211 self.module.simplefilter("ignore", UserWarning)
212 self.module.filterwarnings("error", "match", UserWarning)
213 self.assertRaises(UserWarning, self.module.warn, "match")
214 self.assertRaises(UserWarning, self.module.warn, "match prefix")
215 self.module.warn("suffix match")
216 self.assertEqual(w, [])
217 self.module.warn("something completely different")
218 self.assertEqual(w, [])
219
Brett Cannon667bb4f2008-04-13 02:42:36 +0000220class CFilterTests(BaseTest, FilterTests):
Brett Cannone9746892008-04-12 23:44:07 +0000221 module = c_warnings
222
Brett Cannon667bb4f2008-04-13 02:42:36 +0000223class PyFilterTests(BaseTest, FilterTests):
Brett Cannone9746892008-04-12 23:44:07 +0000224 module = py_warnings
225
226
227class WarnTests(unittest.TestCase):
228
229 """Test warnings.warn() and warnings.warn_explicit()."""
230
231 def test_message(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000232 with original_warnings.catch_warnings(record=True,
233 module=self.module) as w:
Florent Xiclunafd37dd42010-03-25 20:39:10 +0000234 self.module.simplefilter("once")
Walter Dörwalde6dae6c2007-04-03 18:33:29 +0000235 for i in range(4):
Brett Cannone9746892008-04-12 23:44:07 +0000236 text = 'multi %d' %i # Different text on each call.
237 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000238 self.assertEqual(str(w[-1].message), text)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000239 self.assertTrue(w[-1].category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000240
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000241 def test_filename(self):
Brett Cannone9746892008-04-12 23:44:07 +0000242 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000243 with original_warnings.catch_warnings(record=True,
244 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000245 warning_tests.inner("spam1")
Brett Cannon672237d2008-09-09 00:49:16 +0000246 self.assertEqual(os.path.basename(w[-1].filename),
247 "warning_tests.py")
Brett Cannone9746892008-04-12 23:44:07 +0000248 warning_tests.outer("spam2")
Brett Cannon672237d2008-09-09 00:49:16 +0000249 self.assertEqual(os.path.basename(w[-1].filename),
250 "warning_tests.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000251
252 def test_stacklevel(self):
253 # Test stacklevel argument
254 # make sure all messages are different, so the warning won't be skipped
Brett Cannone9746892008-04-12 23:44:07 +0000255 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000256 with original_warnings.catch_warnings(record=True,
257 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000258 warning_tests.inner("spam3", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000259 self.assertEqual(os.path.basename(w[-1].filename),
260 "warning_tests.py")
Brett Cannone9746892008-04-12 23:44:07 +0000261 warning_tests.outer("spam4", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000262 self.assertEqual(os.path.basename(w[-1].filename),
263 "warning_tests.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000264
Brett Cannone9746892008-04-12 23:44:07 +0000265 warning_tests.inner("spam5", stacklevel=2)
Brett Cannon672237d2008-09-09 00:49:16 +0000266 self.assertEqual(os.path.basename(w[-1].filename),
267 "test_warnings.py")
Brett Cannone9746892008-04-12 23:44:07 +0000268 warning_tests.outer("spam6", stacklevel=2)
Brett Cannon672237d2008-09-09 00:49:16 +0000269 self.assertEqual(os.path.basename(w[-1].filename),
270 "warning_tests.py")
Brett Cannone3dcb012008-05-06 04:37:31 +0000271 warning_tests.outer("spam6.5", stacklevel=3)
Brett Cannon672237d2008-09-09 00:49:16 +0000272 self.assertEqual(os.path.basename(w[-1].filename),
273 "test_warnings.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000274
Brett Cannone9746892008-04-12 23:44:07 +0000275 warning_tests.inner("spam7", stacklevel=9999)
Brett Cannon672237d2008-09-09 00:49:16 +0000276 self.assertEqual(os.path.basename(w[-1].filename),
277 "sys")
Brett Cannone9746892008-04-12 23:44:07 +0000278
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000279 def test_missing_filename_not_main(self):
280 # If __file__ is not specified and __main__ is not the module name,
281 # then __file__ should be set to the module name.
282 filename = warning_tests.__file__
283 try:
284 del warning_tests.__file__
285 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000286 with original_warnings.catch_warnings(record=True,
287 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000288 warning_tests.inner("spam8", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000289 self.assertEqual(w[-1].filename, warning_tests.__name__)
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000290 finally:
291 warning_tests.__file__ = filename
292
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200293 @unittest.skipUnless(hasattr(sys, 'argv'), 'test needs sys.argv')
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000294 def test_missing_filename_main_with_argv(self):
295 # If __file__ is not specified and the caller is __main__ and sys.argv
296 # exists, then use sys.argv[0] as the file.
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000297 filename = warning_tests.__file__
298 module_name = warning_tests.__name__
299 try:
300 del warning_tests.__file__
301 warning_tests.__name__ = '__main__'
302 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000303 with original_warnings.catch_warnings(record=True,
304 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000305 warning_tests.inner('spam9', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000306 self.assertEqual(w[-1].filename, sys.argv[0])
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000307 finally:
308 warning_tests.__file__ = filename
309 warning_tests.__name__ = module_name
310
311 def test_missing_filename_main_without_argv(self):
312 # If __file__ is not specified, the caller is __main__, and sys.argv
313 # is not set, then '__main__' is the file name.
314 filename = warning_tests.__file__
315 module_name = warning_tests.__name__
316 argv = sys.argv
317 try:
318 del warning_tests.__file__
319 warning_tests.__name__ = '__main__'
320 del sys.argv
321 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000322 with original_warnings.catch_warnings(record=True,
323 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000324 warning_tests.inner('spam10', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000325 self.assertEqual(w[-1].filename, '__main__')
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000326 finally:
327 warning_tests.__file__ = filename
328 warning_tests.__name__ = module_name
329 sys.argv = argv
330
331 def test_missing_filename_main_with_argv_empty_string(self):
332 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
333 # is the empty string, then '__main__ is the file name.
334 # Tests issue 2743.
335 file_name = warning_tests.__file__
336 module_name = warning_tests.__name__
337 argv = sys.argv
338 try:
339 del warning_tests.__file__
340 warning_tests.__name__ = '__main__'
341 sys.argv = ['']
342 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000343 with original_warnings.catch_warnings(record=True,
344 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000345 warning_tests.inner('spam11', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000346 self.assertEqual(w[-1].filename, '__main__')
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000347 finally:
348 warning_tests.__file__ = file_name
349 warning_tests.__name__ = module_name
350 sys.argv = argv
351
Brett Cannondea1b562008-06-27 00:31:13 +0000352 def test_warn_explicit_type_errors(self):
Ezio Melottic2077b02011-03-16 12:34:31 +0200353 # warn_explicit() should error out gracefully if it is given objects
Brett Cannondea1b562008-06-27 00:31:13 +0000354 # of the wrong types.
355 # lineno is expected to be an integer.
356 self.assertRaises(TypeError, self.module.warn_explicit,
357 None, UserWarning, None, None)
358 # Either 'message' needs to be an instance of Warning or 'category'
359 # needs to be a subclass.
360 self.assertRaises(TypeError, self.module.warn_explicit,
361 None, None, None, 1)
362 # 'registry' must be a dict or None.
363 self.assertRaises((TypeError, AttributeError),
364 self.module.warn_explicit,
365 None, Warning, None, 1, registry=42)
366
Hirokazu Yamamotoe78e5d22009-07-17 06:20:46 +0000367 def test_bad_str(self):
368 # issue 6415
369 # Warnings instance with a bad format string for __str__ should not
370 # trigger a bus error.
371 class BadStrWarning(Warning):
372 """Warning with a bad format string for __str__."""
373 def __str__(self):
374 return ("A bad formatted string %(err)" %
375 {"err" : "there is no %(err)s"})
376
377 with self.assertRaises(ValueError):
378 self.module.warn(BadStrWarning())
379
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000380
Brett Cannon667bb4f2008-04-13 02:42:36 +0000381class CWarnTests(BaseTest, WarnTests):
Brett Cannone9746892008-04-12 23:44:07 +0000382 module = c_warnings
383
Nick Coghlancd2e7042009-04-11 13:31:31 +0000384 # As an early adopter, we sanity check the
385 # test_support.import_fresh_module utility function
386 def test_accelerated(self):
387 self.assertFalse(original_warnings is self.module)
388 self.assertFalse(hasattr(self.module.warn, 'func_code'))
389
Brett Cannon667bb4f2008-04-13 02:42:36 +0000390class PyWarnTests(BaseTest, WarnTests):
Brett Cannone9746892008-04-12 23:44:07 +0000391 module = py_warnings
392
Nick Coghlancd2e7042009-04-11 13:31:31 +0000393 # As an early adopter, we sanity check the
394 # test_support.import_fresh_module utility function
395 def test_pure_python(self):
396 self.assertFalse(original_warnings is self.module)
397 self.assertTrue(hasattr(self.module.warn, 'func_code'))
398
Brett Cannone9746892008-04-12 23:44:07 +0000399
400class WCmdLineTests(unittest.TestCase):
401
402 def test_improper_input(self):
403 # Uses the private _setoption() function to test the parsing
404 # of command-line warning arguments
Brett Cannon672237d2008-09-09 00:49:16 +0000405 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000406 self.assertRaises(self.module._OptionError,
407 self.module._setoption, '1:2:3:4:5:6')
408 self.assertRaises(self.module._OptionError,
409 self.module._setoption, 'bogus::Warning')
410 self.assertRaises(self.module._OptionError,
411 self.module._setoption, 'ignore:2::4:-5')
412 self.module._setoption('error::Warning::0')
413 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
414
Antoine Pitrou9c9e1b92010-11-10 14:03:31 +0000415 def test_improper_option(self):
416 # Same as above, but check that the message is printed out when
417 # the interpreter is executed. This also checks that options are
418 # actually parsed at all.
419 rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")
420 self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)
421
422 def test_warnings_bootstrap(self):
423 # Check that the warnings module does get loaded when -W<some option>
424 # is used (see issue #10372 for an example of silent bootstrap failure).
425 rc, out, err = assert_python_ok("-Wi", "-c",
426 "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
427 # '-Wi' was observed
428 self.assertFalse(out.strip())
429 self.assertNotIn(b'RuntimeWarning', err)
430
Brett Cannon667bb4f2008-04-13 02:42:36 +0000431class CWCmdLineTests(BaseTest, WCmdLineTests):
Brett Cannone9746892008-04-12 23:44:07 +0000432 module = c_warnings
433
Brett Cannon667bb4f2008-04-13 02:42:36 +0000434class PyWCmdLineTests(BaseTest, WCmdLineTests):
Brett Cannone9746892008-04-12 23:44:07 +0000435 module = py_warnings
436
437
Brett Cannon667bb4f2008-04-13 02:42:36 +0000438class _WarningsTests(BaseTest):
Brett Cannone9746892008-04-12 23:44:07 +0000439
440 """Tests specific to the _warnings module."""
441
442 module = c_warnings
443
444 def test_filter(self):
445 # Everything should function even if 'filters' is not in warnings.
Brett Cannon672237d2008-09-09 00:49:16 +0000446 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000447 self.module.filterwarnings("error", "", Warning, "", 0)
448 self.assertRaises(UserWarning, self.module.warn,
449 'convert to error')
450 del self.module.filters
451 self.assertRaises(UserWarning, self.module.warn,
452 'convert to error')
453
454 def test_onceregistry(self):
455 # Replacing or removing the onceregistry should be okay.
456 global __warningregistry__
457 message = UserWarning('onceregistry test')
458 try:
459 original_registry = self.module.onceregistry
460 __warningregistry__ = {}
Brett Cannon672237d2008-09-09 00:49:16 +0000461 with original_warnings.catch_warnings(record=True,
462 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000463 self.module.resetwarnings()
464 self.module.filterwarnings("once", category=UserWarning)
465 self.module.warn_explicit(message, UserWarning, "file", 42)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000466 self.assertEqual(w[-1].message, message)
Brett Cannon672237d2008-09-09 00:49:16 +0000467 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000468 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melotti2623a372010-11-21 13:34:58 +0000469 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000470 # Test the resetting of onceregistry.
471 self.module.onceregistry = {}
472 __warningregistry__ = {}
473 self.module.warn('onceregistry test')
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000474 self.assertEqual(w[-1].message.args, message.args)
Brett Cannone9746892008-04-12 23:44:07 +0000475 # Removal of onceregistry is okay.
Brett Cannon672237d2008-09-09 00:49:16 +0000476 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000477 del self.module.onceregistry
478 __warningregistry__ = {}
479 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melotti2623a372010-11-21 13:34:58 +0000480 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000481 finally:
482 self.module.onceregistry = original_registry
483
Brett Cannon15ba4da2009-04-01 18:03:59 +0000484 def test_default_action(self):
485 # Replacing or removing defaultaction should be okay.
486 message = UserWarning("defaultaction test")
487 original = self.module.defaultaction
488 try:
489 with original_warnings.catch_warnings(record=True,
490 module=self.module) as w:
491 self.module.resetwarnings()
492 registry = {}
493 self.module.warn_explicit(message, UserWarning, "<test>", 42,
494 registry=registry)
495 self.assertEqual(w[-1].message, message)
496 self.assertEqual(len(w), 1)
497 self.assertEqual(len(registry), 1)
498 del w[:]
499 # Test removal.
500 del self.module.defaultaction
501 __warningregistry__ = {}
502 registry = {}
503 self.module.warn_explicit(message, UserWarning, "<test>", 43,
504 registry=registry)
505 self.assertEqual(w[-1].message, message)
506 self.assertEqual(len(w), 1)
507 self.assertEqual(len(registry), 1)
508 del w[:]
509 # Test setting.
510 self.module.defaultaction = "ignore"
511 __warningregistry__ = {}
512 registry = {}
513 self.module.warn_explicit(message, UserWarning, "<test>", 44,
514 registry=registry)
515 self.assertEqual(len(w), 0)
516 finally:
517 self.module.defaultaction = original
518
Brett Cannone9746892008-04-12 23:44:07 +0000519 def test_showwarning_missing(self):
520 # Test that showwarning() missing is okay.
521 text = 'del showwarning test'
Brett Cannon672237d2008-09-09 00:49:16 +0000522 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000523 self.module.filterwarnings("always", category=UserWarning)
524 del self.module.showwarning
525 with test_support.captured_output('stderr') as stream:
526 self.module.warn(text)
527 result = stream.getvalue()
Ezio Melottiaa980582010-01-23 23:04:36 +0000528 self.assertIn(text, result)
Brett Cannone9746892008-04-12 23:44:07 +0000529
Benjamin Petersond2950322008-05-06 22:18:11 +0000530 def test_showwarning_not_callable(self):
Brett Cannonce3d2212009-04-01 20:25:48 +0000531 with original_warnings.catch_warnings(module=self.module):
532 self.module.filterwarnings("always", category=UserWarning)
533 old_showwarning = self.module.showwarning
534 self.module.showwarning = 23
535 try:
536 self.assertRaises(TypeError, self.module.warn, "Warning!")
537 finally:
538 self.module.showwarning = old_showwarning
Benjamin Petersond2950322008-05-06 22:18:11 +0000539
Brett Cannone9746892008-04-12 23:44:07 +0000540 def test_show_warning_output(self):
541 # With showarning() missing, make sure that output is okay.
542 text = 'test show_warning'
Brett Cannon672237d2008-09-09 00:49:16 +0000543 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000544 self.module.filterwarnings("always", category=UserWarning)
545 del self.module.showwarning
546 with test_support.captured_output('stderr') as stream:
547 warning_tests.inner(text)
548 result = stream.getvalue()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000549 self.assertEqual(result.count('\n'), 2,
Brett Cannone9746892008-04-12 23:44:07 +0000550 "Too many newlines in %r" % result)
551 first_line, second_line = result.split('\n', 1)
552 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Brett Cannonc4774272008-04-13 17:41:31 +0000553 first_line_parts = first_line.rsplit(':', 3)
Brett Cannon25bb8182008-04-13 17:09:43 +0000554 path, line, warning_class, message = first_line_parts
Brett Cannone9746892008-04-12 23:44:07 +0000555 line = int(line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000556 self.assertEqual(expected_file, path)
557 self.assertEqual(warning_class, ' ' + UserWarning.__name__)
558 self.assertEqual(message, ' ' + text)
Brett Cannone9746892008-04-12 23:44:07 +0000559 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
560 assert expected_line
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000561 self.assertEqual(second_line, expected_line)
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000562
Victor Stinner65c15352011-07-04 03:05:37 +0200563 def test_filename_none(self):
564 # issue #12467: race condition if a warning is emitted at shutdown
565 globals_dict = globals()
566 oldfile = globals_dict['__file__']
567 try:
Berker Peksagccff2bb2016-04-16 22:16:05 +0300568 with original_warnings.catch_warnings(module=self.module, record=True) as w:
Victor Stinner65c15352011-07-04 03:05:37 +0200569 self.module.filterwarnings("always", category=UserWarning)
570 globals_dict['__file__'] = None
571 self.module.warn('test', UserWarning)
Berker Peksagccff2bb2016-04-16 22:16:05 +0300572 self.assertEqual(len(w), 1)
573 self.assertEqual(w[0].category, UserWarning)
574 self.assertEqual(str(w[0].message), 'test')
Victor Stinner65c15352011-07-04 03:05:37 +0200575 finally:
576 globals_dict['__file__'] = oldfile
577
Serhiy Storchakae6b42432014-12-10 23:05:33 +0200578 def test_stderr_none(self):
579 rc, stdout, stderr = assert_python_ok("-c",
580 "import sys; sys.stderr = None; "
581 "import warnings; warnings.simplefilter('always'); "
582 "warnings.warn('Warning!')")
583 self.assertEqual(stdout, b'')
584 self.assertNotIn(b'Warning!', stderr)
585 self.assertNotIn(b'Error', stderr)
586
Oren Milman40d736b2017-09-30 17:06:55 +0300587 def test_issue31285(self):
588 # warn_explicit() shouldn't raise a SystemError in case the return
589 # value of get_source() has a bad splitlines() method.
590 class BadLoader:
591 def get_source(self, fullname):
592 class BadSource(str):
593 def splitlines(self):
594 return 42
595 return BadSource('spam')
596
597 wmod = self.module
598 with original_warnings.catch_warnings(module=wmod):
599 wmod.filterwarnings('default', category=UserWarning)
600
601 with test_support.captured_stderr() as stderr:
602 wmod.warn_explicit(
603 'foo', UserWarning, 'bar', 1,
604 module_globals={'__loader__': BadLoader(),
605 '__name__': 'foobar'})
606 self.assertIn('UserWarning: foo', stderr.getvalue())
607
Serhiy Storchaka004547f2017-09-11 10:01:31 +0300608 @test_support.cpython_only
609 def test_issue31411(self):
610 # warn_explicit() shouldn't raise a SystemError in case
611 # warnings.onceregistry isn't a dictionary.
612 wmod = self.module
613 with original_warnings.catch_warnings(module=wmod):
614 wmod.filterwarnings('once')
615 with test_support.swap_attr(wmod, 'onceregistry', None):
616 with self.assertRaises(TypeError):
617 wmod.warn_explicit('foo', Warning, 'bar', 1, registry=None)
618
Brett Cannon53ab5b72006-06-22 16:49:14 +0000619
Brett Cannon905c31c2007-12-20 10:09:52 +0000620class WarningsDisplayTests(unittest.TestCase):
621
Brett Cannone9746892008-04-12 23:44:07 +0000622 """Test the displaying of warnings and the ability to overload functions
623 related to displaying warnings."""
624
Brett Cannon905c31c2007-12-20 10:09:52 +0000625 def test_formatwarning(self):
626 message = "msg"
627 category = Warning
628 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
629 line_num = 3
630 file_line = linecache.getline(file_name, line_num).strip()
Brett Cannone9746892008-04-12 23:44:07 +0000631 format = "%s:%s: %s: %s\n %s\n"
632 expect = format % (file_name, line_num, category.__name__, message,
633 file_line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000634 self.assertEqual(expect, self.module.formatwarning(message,
Brett Cannone9746892008-04-12 23:44:07 +0000635 category, file_name, line_num))
636 # Test the 'line' argument.
637 file_line += " for the win!"
638 expect = format % (file_name, line_num, category.__name__, message,
639 file_line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000640 self.assertEqual(expect, self.module.formatwarning(message,
Brett Cannone9746892008-04-12 23:44:07 +0000641 category, file_name, line_num, file_line))
Brett Cannon905c31c2007-12-20 10:09:52 +0000642
Serhiy Storchakaf40fcb32015-05-16 16:42:18 +0300643 @test_support.requires_unicode
644 def test_formatwarning_unicode_msg(self):
645 message = u"msg"
646 category = Warning
647 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
648 line_num = 3
649 file_line = linecache.getline(file_name, line_num).strip()
650 format = "%s:%s: %s: %s\n %s\n"
651 expect = format % (file_name, line_num, category.__name__, message,
652 file_line)
653 self.assertEqual(expect, self.module.formatwarning(message,
654 category, file_name, line_num))
655 # Test the 'line' argument.
656 file_line += " for the win!"
657 expect = format % (file_name, line_num, category.__name__, message,
658 file_line)
659 self.assertEqual(expect, self.module.formatwarning(message,
660 category, file_name, line_num, file_line))
661
662 @test_support.requires_unicode
663 @unittest.skipUnless(test_support.FS_NONASCII, 'need test_support.FS_NONASCII')
664 def test_formatwarning_unicode_msg_nonascii_filename(self):
665 message = u"msg"
666 category = Warning
667 unicode_file_name = test_support.FS_NONASCII + u'.py'
668 file_name = unicode_file_name.encode(sys.getfilesystemencoding())
669 line_num = 3
670 file_line = 'spam'
671 format = "%s:%s: %s: %s\n %s\n"
672 expect = format % (file_name, line_num, category.__name__, str(message),
673 file_line)
674 self.assertEqual(expect, self.module.formatwarning(message,
675 category, file_name, line_num, file_line))
676 message = u"\xb5sg"
677 expect = format % (unicode_file_name, line_num, category.__name__, message,
678 file_line)
679 self.assertEqual(expect, self.module.formatwarning(message,
680 category, file_name, line_num, file_line))
681
682 @test_support.requires_unicode
683 def test_formatwarning_unicode_msg_nonascii_fileline(self):
684 message = u"msg"
685 category = Warning
686 file_name = 'file.py'
687 line_num = 3
688 file_line = 'sp\xe4m'
689 format = "%s:%s: %s: %s\n %s\n"
690 expect = format % (file_name, line_num, category.__name__, str(message),
691 file_line)
692 self.assertEqual(expect, self.module.formatwarning(message,
693 category, file_name, line_num, file_line))
694 message = u"\xb5sg"
695 expect = format % (file_name, line_num, category.__name__, message,
696 unicode(file_line, 'latin1'))
697 self.assertEqual(expect, self.module.formatwarning(message,
698 category, file_name, line_num, file_line))
699
Brett Cannon905c31c2007-12-20 10:09:52 +0000700 def test_showwarning(self):
701 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
702 line_num = 3
703 expected_file_line = linecache.getline(file_name, line_num).strip()
704 message = 'msg'
705 category = Warning
706 file_object = StringIO.StringIO()
Brett Cannone9746892008-04-12 23:44:07 +0000707 expect = self.module.formatwarning(message, category, file_name,
708 line_num)
709 self.module.showwarning(message, category, file_name, line_num,
Brett Cannon905c31c2007-12-20 10:09:52 +0000710 file_object)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000711 self.assertEqual(file_object.getvalue(), expect)
Brett Cannone9746892008-04-12 23:44:07 +0000712 # Test 'line' argument.
713 expected_file_line += "for the win!"
714 expect = self.module.formatwarning(message, category, file_name,
715 line_num, expected_file_line)
716 file_object = StringIO.StringIO()
717 self.module.showwarning(message, category, file_name, line_num,
718 file_object, expected_file_line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000719 self.assertEqual(expect, file_object.getvalue())
Brett Cannone9746892008-04-12 23:44:07 +0000720
Brett Cannon667bb4f2008-04-13 02:42:36 +0000721class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
Brett Cannone9746892008-04-12 23:44:07 +0000722 module = c_warnings
723
Brett Cannon667bb4f2008-04-13 02:42:36 +0000724class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
Brett Cannone9746892008-04-12 23:44:07 +0000725 module = py_warnings
Brett Cannon905c31c2007-12-20 10:09:52 +0000726
727
Brett Cannon1eaf0742008-09-02 01:25:16 +0000728class CatchWarningTests(BaseTest):
Nick Coghlan38469e22008-07-13 12:23:47 +0000729
Brett Cannon1eaf0742008-09-02 01:25:16 +0000730 """Test catch_warnings()."""
731
732 def test_catch_warnings_restore(self):
Nick Coghlan38469e22008-07-13 12:23:47 +0000733 wmod = self.module
734 orig_filters = wmod.filters
735 orig_showwarning = wmod.showwarning
Nick Coghland2e09382008-09-11 12:11:06 +0000736 # Ensure both showwarning and filters are restored when recording
737 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlan38469e22008-07-13 12:23:47 +0000738 wmod.filters = wmod.showwarning = object()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000739 self.assertTrue(wmod.filters is orig_filters)
740 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghland2e09382008-09-11 12:11:06 +0000741 # Same test, but with recording disabled
Brett Cannon1eaf0742008-09-02 01:25:16 +0000742 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlan38469e22008-07-13 12:23:47 +0000743 wmod.filters = wmod.showwarning = object()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000744 self.assertTrue(wmod.filters is orig_filters)
745 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlan38469e22008-07-13 12:23:47 +0000746
Brett Cannon1eaf0742008-09-02 01:25:16 +0000747 def test_catch_warnings_recording(self):
Nick Coghlan38469e22008-07-13 12:23:47 +0000748 wmod = self.module
Nick Coghland2e09382008-09-11 12:11:06 +0000749 # Ensure warnings are recorded when requested
Brett Cannon1eaf0742008-09-02 01:25:16 +0000750 with wmod.catch_warnings(module=wmod, record=True) as w:
751 self.assertEqual(w, [])
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000752 self.assertTrue(type(w) is list)
Nick Coghlan38469e22008-07-13 12:23:47 +0000753 wmod.simplefilter("always")
754 wmod.warn("foo")
Brett Cannon672237d2008-09-09 00:49:16 +0000755 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlan38469e22008-07-13 12:23:47 +0000756 wmod.warn("bar")
Brett Cannon672237d2008-09-09 00:49:16 +0000757 self.assertEqual(str(w[-1].message), "bar")
Brett Cannon1eaf0742008-09-02 01:25:16 +0000758 self.assertEqual(str(w[0].message), "foo")
759 self.assertEqual(str(w[1].message), "bar")
Brett Cannon672237d2008-09-09 00:49:16 +0000760 del w[:]
Brett Cannon1eaf0742008-09-02 01:25:16 +0000761 self.assertEqual(w, [])
Nick Coghland2e09382008-09-11 12:11:06 +0000762 # Ensure warnings are not recorded when not requested
Nick Coghlan38469e22008-07-13 12:23:47 +0000763 orig_showwarning = wmod.showwarning
Brett Cannon1eaf0742008-09-02 01:25:16 +0000764 with wmod.catch_warnings(module=wmod, record=False) as w:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000765 self.assertTrue(w is None)
766 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlan38469e22008-07-13 12:23:47 +0000767
Nick Coghland2e09382008-09-11 12:11:06 +0000768 def test_catch_warnings_reentry_guard(self):
769 wmod = self.module
770 # Ensure catch_warnings is protected against incorrect usage
771 x = wmod.catch_warnings(module=wmod, record=True)
772 self.assertRaises(RuntimeError, x.__exit__)
773 with x:
774 self.assertRaises(RuntimeError, x.__enter__)
775 # Same test, but with recording disabled
776 x = wmod.catch_warnings(module=wmod, record=False)
777 self.assertRaises(RuntimeError, x.__exit__)
778 with x:
779 self.assertRaises(RuntimeError, x.__enter__)
780
781 def test_catch_warnings_defaults(self):
782 wmod = self.module
783 orig_filters = wmod.filters
784 orig_showwarning = wmod.showwarning
785 # Ensure default behaviour is not to record warnings
786 with wmod.catch_warnings(module=wmod) as w:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000787 self.assertTrue(w is None)
788 self.assertTrue(wmod.showwarning is orig_showwarning)
789 self.assertTrue(wmod.filters is not orig_filters)
790 self.assertTrue(wmod.filters is orig_filters)
Nick Coghland2e09382008-09-11 12:11:06 +0000791 if wmod is sys.modules['warnings']:
792 # Ensure the default module is this one
793 with wmod.catch_warnings() as w:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000794 self.assertTrue(w is None)
795 self.assertTrue(wmod.showwarning is orig_showwarning)
796 self.assertTrue(wmod.filters is not orig_filters)
797 self.assertTrue(wmod.filters is orig_filters)
Nick Coghland2e09382008-09-11 12:11:06 +0000798
799 def test_check_warnings(self):
800 # Explicit tests for the test_support convenience wrapper
801 wmod = self.module
Florent Xicluna73588542010-03-18 19:51:47 +0000802 if wmod is not sys.modules['warnings']:
Zachary Ware1f702212013-12-10 14:09:20 -0600803 self.skipTest('module to test is not loaded warnings module')
Florent Xicluna73588542010-03-18 19:51:47 +0000804 with test_support.check_warnings(quiet=False) as w:
805 self.assertEqual(w.warnings, [])
806 wmod.simplefilter("always")
807 wmod.warn("foo")
808 self.assertEqual(str(w.message), "foo")
809 wmod.warn("bar")
810 self.assertEqual(str(w.message), "bar")
811 self.assertEqual(str(w.warnings[0].message), "foo")
812 self.assertEqual(str(w.warnings[1].message), "bar")
813 w.reset()
814 self.assertEqual(w.warnings, [])
Nick Coghland2e09382008-09-11 12:11:06 +0000815
Florent Xicluna73588542010-03-18 19:51:47 +0000816 with test_support.check_warnings():
817 # defaults to quiet=True without argument
818 pass
819 with test_support.check_warnings(('foo', UserWarning)):
820 wmod.warn("foo")
821
822 with self.assertRaises(AssertionError):
823 with test_support.check_warnings(('', RuntimeWarning)):
824 # defaults to quiet=False with argument
825 pass
826 with self.assertRaises(AssertionError):
827 with test_support.check_warnings(('foo', RuntimeWarning)):
828 wmod.warn("foo")
Nick Coghland2e09382008-09-11 12:11:06 +0000829
830
Brett Cannon1eaf0742008-09-02 01:25:16 +0000831class CCatchWarningTests(CatchWarningTests):
Nick Coghlan38469e22008-07-13 12:23:47 +0000832 module = c_warnings
833
Brett Cannon1eaf0742008-09-02 01:25:16 +0000834class PyCatchWarningTests(CatchWarningTests):
Nick Coghlan38469e22008-07-13 12:23:47 +0000835 module = py_warnings
836
837
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000838class EnvironmentVariableTests(BaseTest):
839
840 def test_single_warning(self):
841 newenv = os.environ.copy()
842 newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
843 p = subprocess.Popen([sys.executable,
844 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
845 stdout=subprocess.PIPE, env=newenv)
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000846 self.assertEqual(p.communicate()[0], "['ignore::DeprecationWarning']")
847 self.assertEqual(p.wait(), 0)
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000848
849 def test_comma_separated_warnings(self):
850 newenv = os.environ.copy()
851 newenv["PYTHONWARNINGS"] = ("ignore::DeprecationWarning,"
852 "ignore::UnicodeWarning")
853 p = subprocess.Popen([sys.executable,
854 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
855 stdout=subprocess.PIPE, env=newenv)
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000856 self.assertEqual(p.communicate()[0],
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000857 "['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000858 self.assertEqual(p.wait(), 0)
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000859
860 def test_envvar_and_command_line(self):
861 newenv = os.environ.copy()
862 newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
863 p = subprocess.Popen([sys.executable, "-W" "ignore::UnicodeWarning",
864 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
865 stdout=subprocess.PIPE, env=newenv)
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000866 self.assertEqual(p.communicate()[0],
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000867 "['ignore::UnicodeWarning', 'ignore::DeprecationWarning']")
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000868 self.assertEqual(p.wait(), 0)
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000869
870class CEnvironmentVariableTests(EnvironmentVariableTests):
871 module = c_warnings
872
873class PyEnvironmentVariableTests(EnvironmentVariableTests):
874 module = py_warnings
875
876
Brett Cannone9746892008-04-12 23:44:07 +0000877def test_main():
Amaury Forgeot d'Arc607bff12008-04-18 23:31:33 +0000878 py_warnings.onceregistry.clear()
879 c_warnings.onceregistry.clear()
Brett Cannon1eaf0742008-09-02 01:25:16 +0000880 test_support.run_unittest(CFilterTests, PyFilterTests,
881 CWarnTests, PyWarnTests,
Brett Cannone9746892008-04-12 23:44:07 +0000882 CWCmdLineTests, PyWCmdLineTests,
883 _WarningsTests,
884 CWarningsDisplayTests, PyWarningsDisplayTests,
Brett Cannon1eaf0742008-09-02 01:25:16 +0000885 CCatchWarningTests, PyCatchWarningTests,
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000886 CEnvironmentVariableTests,
887 PyEnvironmentVariableTests
Brett Cannone9746892008-04-12 23:44:07 +0000888 )
889
890
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000891if __name__ == "__main__":
Brett Cannone9746892008-04-12 23:44:07 +0000892 test_main()