blob: a9568f64c55bda9f5bc1546438261e630378196d [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"
Serhiy Storchaka789f95a2018-07-09 20:00:53 +0300110 def f():
111 self.module.warn(message, UserWarning)
112 f()
113 self.assertEqual(len(w), 1)
114 self.assertEqual(w[-1].message.args[0], message)
115 f()
116 self.assertEqual(len(w), 2)
117 self.assertEqual(w[-1].message.args[0], message)
Brett Cannone9746892008-04-12 23:44:07 +0000118
119 def test_default(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000120 with original_warnings.catch_warnings(record=True,
121 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000122 self.module.resetwarnings()
123 self.module.filterwarnings("default", category=UserWarning)
124 message = UserWarning("FilterTests.test_default")
125 for x in xrange(2):
126 self.module.warn(message, UserWarning)
127 if x == 0:
Ezio Melotti2623a372010-11-21 13:34:58 +0000128 self.assertEqual(w[-1].message, message)
Brett Cannon672237d2008-09-09 00:49:16 +0000129 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000130 elif x == 1:
Ezio Melotti2623a372010-11-21 13:34:58 +0000131 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000132 else:
133 raise ValueError("loop variant unhandled")
134
135 def test_module(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000136 with original_warnings.catch_warnings(record=True,
137 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000138 self.module.resetwarnings()
139 self.module.filterwarnings("module", category=UserWarning)
140 message = UserWarning("FilterTests.test_module")
141 self.module.warn(message, UserWarning)
Ezio Melotti2623a372010-11-21 13:34:58 +0000142 self.assertEqual(w[-1].message, message)
Brett Cannon672237d2008-09-09 00:49:16 +0000143 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000144 self.module.warn(message, UserWarning)
Ezio Melotti2623a372010-11-21 13:34:58 +0000145 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000146
147 def test_once(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000148 with original_warnings.catch_warnings(record=True,
149 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000150 self.module.resetwarnings()
151 self.module.filterwarnings("once", category=UserWarning)
152 message = UserWarning("FilterTests.test_once")
153 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
154 42)
Ezio Melotti2623a372010-11-21 13:34:58 +0000155 self.assertEqual(w[-1].message, message)
Brett Cannon672237d2008-09-09 00:49:16 +0000156 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000157 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
158 13)
Ezio Melotti2623a372010-11-21 13:34:58 +0000159 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000160 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
161 42)
Ezio Melotti2623a372010-11-21 13:34:58 +0000162 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000163
164 def test_inheritance(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000165 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000166 self.module.resetwarnings()
167 self.module.filterwarnings("error", category=Warning)
168 self.assertRaises(UserWarning, self.module.warn,
169 "FilterTests.test_inheritance", UserWarning)
170
171 def test_ordering(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000172 with original_warnings.catch_warnings(record=True,
173 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000174 self.module.resetwarnings()
175 self.module.filterwarnings("ignore", category=UserWarning)
176 self.module.filterwarnings("error", category=UserWarning,
177 append=True)
Brett Cannon672237d2008-09-09 00:49:16 +0000178 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000179 try:
180 self.module.warn("FilterTests.test_ordering", UserWarning)
181 except UserWarning:
182 self.fail("order handling for actions failed")
Ezio Melotti2623a372010-11-21 13:34:58 +0000183 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000184
185 def test_filterwarnings(self):
186 # Test filterwarnings().
187 # Implicitly also tests resetwarnings().
Brett Cannon672237d2008-09-09 00:49:16 +0000188 with original_warnings.catch_warnings(record=True,
189 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000190 self.module.filterwarnings("error", "", Warning, "", 0)
191 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
192
193 self.module.resetwarnings()
194 text = 'handle normally'
195 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000196 self.assertEqual(str(w[-1].message), text)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000197 self.assertTrue(w[-1].category is UserWarning)
Brett Cannone9746892008-04-12 23:44:07 +0000198
199 self.module.filterwarnings("ignore", "", Warning, "", 0)
200 text = 'filtered out'
201 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000202 self.assertNotEqual(str(w[-1].message), text)
Brett Cannone9746892008-04-12 23:44:07 +0000203
204 self.module.resetwarnings()
205 self.module.filterwarnings("error", "hex*", Warning, "", 0)
206 self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
207 text = 'nonmatching text'
208 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000209 self.assertEqual(str(w[-1].message), text)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000210 self.assertTrue(w[-1].category is UserWarning)
Brett Cannone9746892008-04-12 23:44:07 +0000211
Martin Pantercdb8be42016-07-19 02:26:38 +0000212 def test_message_matching(self):
213 with original_warnings.catch_warnings(record=True,
214 module=self.module) as w:
215 self.module.simplefilter("ignore", UserWarning)
216 self.module.filterwarnings("error", "match", UserWarning)
217 self.assertRaises(UserWarning, self.module.warn, "match")
218 self.assertRaises(UserWarning, self.module.warn, "match prefix")
219 self.module.warn("suffix match")
220 self.assertEqual(w, [])
221 self.module.warn("something completely different")
222 self.assertEqual(w, [])
223
Brett Cannon667bb4f2008-04-13 02:42:36 +0000224class CFilterTests(BaseTest, FilterTests):
Brett Cannone9746892008-04-12 23:44:07 +0000225 module = c_warnings
226
Brett Cannon667bb4f2008-04-13 02:42:36 +0000227class PyFilterTests(BaseTest, FilterTests):
Brett Cannone9746892008-04-12 23:44:07 +0000228 module = py_warnings
229
230
231class WarnTests(unittest.TestCase):
232
233 """Test warnings.warn() and warnings.warn_explicit()."""
234
235 def test_message(self):
Brett Cannon672237d2008-09-09 00:49:16 +0000236 with original_warnings.catch_warnings(record=True,
237 module=self.module) as w:
Florent Xiclunafd37dd42010-03-25 20:39:10 +0000238 self.module.simplefilter("once")
Walter Dörwalde6dae6c2007-04-03 18:33:29 +0000239 for i in range(4):
Brett Cannone9746892008-04-12 23:44:07 +0000240 text = 'multi %d' %i # Different text on each call.
241 self.module.warn(text)
Brett Cannon672237d2008-09-09 00:49:16 +0000242 self.assertEqual(str(w[-1].message), text)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000243 self.assertTrue(w[-1].category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000244
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000245 def test_filename(self):
Brett Cannone9746892008-04-12 23:44:07 +0000246 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000247 with original_warnings.catch_warnings(record=True,
248 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000249 warning_tests.inner("spam1")
Brett Cannon672237d2008-09-09 00:49:16 +0000250 self.assertEqual(os.path.basename(w[-1].filename),
251 "warning_tests.py")
Brett Cannone9746892008-04-12 23:44:07 +0000252 warning_tests.outer("spam2")
Brett Cannon672237d2008-09-09 00:49:16 +0000253 self.assertEqual(os.path.basename(w[-1].filename),
254 "warning_tests.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000255
256 def test_stacklevel(self):
257 # Test stacklevel argument
258 # make sure all messages are different, so the warning won't be skipped
Brett Cannone9746892008-04-12 23:44:07 +0000259 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000260 with original_warnings.catch_warnings(record=True,
261 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000262 warning_tests.inner("spam3", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000263 self.assertEqual(os.path.basename(w[-1].filename),
264 "warning_tests.py")
Brett Cannone9746892008-04-12 23:44:07 +0000265 warning_tests.outer("spam4", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000266 self.assertEqual(os.path.basename(w[-1].filename),
267 "warning_tests.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000268
Brett Cannone9746892008-04-12 23:44:07 +0000269 warning_tests.inner("spam5", stacklevel=2)
Brett Cannon672237d2008-09-09 00:49:16 +0000270 self.assertEqual(os.path.basename(w[-1].filename),
271 "test_warnings.py")
Brett Cannone9746892008-04-12 23:44:07 +0000272 warning_tests.outer("spam6", stacklevel=2)
Brett Cannon672237d2008-09-09 00:49:16 +0000273 self.assertEqual(os.path.basename(w[-1].filename),
274 "warning_tests.py")
Brett Cannone3dcb012008-05-06 04:37:31 +0000275 warning_tests.outer("spam6.5", stacklevel=3)
Brett Cannon672237d2008-09-09 00:49:16 +0000276 self.assertEqual(os.path.basename(w[-1].filename),
277 "test_warnings.py")
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000278
Brett Cannone9746892008-04-12 23:44:07 +0000279 warning_tests.inner("spam7", stacklevel=9999)
Brett Cannon672237d2008-09-09 00:49:16 +0000280 self.assertEqual(os.path.basename(w[-1].filename),
281 "sys")
Brett Cannone9746892008-04-12 23:44:07 +0000282
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000283 def test_missing_filename_not_main(self):
284 # If __file__ is not specified and __main__ is not the module name,
285 # then __file__ should be set to the module name.
286 filename = warning_tests.__file__
287 try:
288 del warning_tests.__file__
289 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000290 with original_warnings.catch_warnings(record=True,
291 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000292 warning_tests.inner("spam8", stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000293 self.assertEqual(w[-1].filename, warning_tests.__name__)
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000294 finally:
295 warning_tests.__file__ = filename
296
Serhiy Storchaka32e23e72013-11-03 23:15:46 +0200297 @unittest.skipUnless(hasattr(sys, 'argv'), 'test needs sys.argv')
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000298 def test_missing_filename_main_with_argv(self):
299 # If __file__ is not specified and the caller is __main__ and sys.argv
300 # exists, then use sys.argv[0] as the file.
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000301 filename = warning_tests.__file__
302 module_name = warning_tests.__name__
303 try:
304 del warning_tests.__file__
305 warning_tests.__name__ = '__main__'
306 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000307 with original_warnings.catch_warnings(record=True,
308 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000309 warning_tests.inner('spam9', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000310 self.assertEqual(w[-1].filename, sys.argv[0])
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000311 finally:
312 warning_tests.__file__ = filename
313 warning_tests.__name__ = module_name
314
315 def test_missing_filename_main_without_argv(self):
316 # If __file__ is not specified, the caller is __main__, and sys.argv
317 # is not set, then '__main__' is the file name.
318 filename = warning_tests.__file__
319 module_name = warning_tests.__name__
320 argv = sys.argv
321 try:
322 del warning_tests.__file__
323 warning_tests.__name__ = '__main__'
324 del sys.argv
325 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000326 with original_warnings.catch_warnings(record=True,
327 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000328 warning_tests.inner('spam10', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000329 self.assertEqual(w[-1].filename, '__main__')
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000330 finally:
331 warning_tests.__file__ = filename
332 warning_tests.__name__ = module_name
333 sys.argv = argv
334
335 def test_missing_filename_main_with_argv_empty_string(self):
336 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
337 # is the empty string, then '__main__ is the file name.
338 # Tests issue 2743.
339 file_name = warning_tests.__file__
340 module_name = warning_tests.__name__
341 argv = sys.argv
342 try:
343 del warning_tests.__file__
344 warning_tests.__name__ = '__main__'
345 sys.argv = ['']
346 with warnings_state(self.module):
Brett Cannon672237d2008-09-09 00:49:16 +0000347 with original_warnings.catch_warnings(record=True,
348 module=self.module) as w:
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000349 warning_tests.inner('spam11', stacklevel=1)
Brett Cannon672237d2008-09-09 00:49:16 +0000350 self.assertEqual(w[-1].filename, '__main__')
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000351 finally:
352 warning_tests.__file__ = file_name
353 warning_tests.__name__ = module_name
354 sys.argv = argv
355
Brett Cannondea1b562008-06-27 00:31:13 +0000356 def test_warn_explicit_type_errors(self):
Ezio Melottic2077b02011-03-16 12:34:31 +0200357 # warn_explicit() should error out gracefully if it is given objects
Brett Cannondea1b562008-06-27 00:31:13 +0000358 # of the wrong types.
359 # lineno is expected to be an integer.
360 self.assertRaises(TypeError, self.module.warn_explicit,
361 None, UserWarning, None, None)
362 # Either 'message' needs to be an instance of Warning or 'category'
363 # needs to be a subclass.
364 self.assertRaises(TypeError, self.module.warn_explicit,
365 None, None, None, 1)
366 # 'registry' must be a dict or None.
367 self.assertRaises((TypeError, AttributeError),
368 self.module.warn_explicit,
369 None, Warning, None, 1, registry=42)
370
Hirokazu Yamamotoe78e5d22009-07-17 06:20:46 +0000371 def test_bad_str(self):
372 # issue 6415
373 # Warnings instance with a bad format string for __str__ should not
374 # trigger a bus error.
375 class BadStrWarning(Warning):
376 """Warning with a bad format string for __str__."""
377 def __str__(self):
378 return ("A bad formatted string %(err)" %
379 {"err" : "there is no %(err)s"})
380
381 with self.assertRaises(ValueError):
382 self.module.warn(BadStrWarning())
383
Brett Cannon64a4bbe2008-05-03 03:19:39 +0000384
Brett Cannon667bb4f2008-04-13 02:42:36 +0000385class CWarnTests(BaseTest, WarnTests):
Brett Cannone9746892008-04-12 23:44:07 +0000386 module = c_warnings
387
Nick Coghlancd2e7042009-04-11 13:31:31 +0000388 # As an early adopter, we sanity check the
389 # test_support.import_fresh_module utility function
390 def test_accelerated(self):
391 self.assertFalse(original_warnings is self.module)
392 self.assertFalse(hasattr(self.module.warn, 'func_code'))
393
Brett Cannon667bb4f2008-04-13 02:42:36 +0000394class PyWarnTests(BaseTest, WarnTests):
Brett Cannone9746892008-04-12 23:44:07 +0000395 module = py_warnings
396
Nick Coghlancd2e7042009-04-11 13:31:31 +0000397 # As an early adopter, we sanity check the
398 # test_support.import_fresh_module utility function
399 def test_pure_python(self):
400 self.assertFalse(original_warnings is self.module)
401 self.assertTrue(hasattr(self.module.warn, 'func_code'))
402
Brett Cannone9746892008-04-12 23:44:07 +0000403
404class WCmdLineTests(unittest.TestCase):
405
406 def test_improper_input(self):
407 # Uses the private _setoption() function to test the parsing
408 # of command-line warning arguments
Brett Cannon672237d2008-09-09 00:49:16 +0000409 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000410 self.assertRaises(self.module._OptionError,
411 self.module._setoption, '1:2:3:4:5:6')
412 self.assertRaises(self.module._OptionError,
413 self.module._setoption, 'bogus::Warning')
414 self.assertRaises(self.module._OptionError,
415 self.module._setoption, 'ignore:2::4:-5')
416 self.module._setoption('error::Warning::0')
417 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
418
Antoine Pitrou9c9e1b92010-11-10 14:03:31 +0000419 def test_improper_option(self):
420 # Same as above, but check that the message is printed out when
421 # the interpreter is executed. This also checks that options are
422 # actually parsed at all.
423 rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")
424 self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)
425
426 def test_warnings_bootstrap(self):
427 # Check that the warnings module does get loaded when -W<some option>
428 # is used (see issue #10372 for an example of silent bootstrap failure).
429 rc, out, err = assert_python_ok("-Wi", "-c",
430 "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
431 # '-Wi' was observed
432 self.assertFalse(out.strip())
433 self.assertNotIn(b'RuntimeWarning', err)
434
Brett Cannon667bb4f2008-04-13 02:42:36 +0000435class CWCmdLineTests(BaseTest, WCmdLineTests):
Brett Cannone9746892008-04-12 23:44:07 +0000436 module = c_warnings
437
Brett Cannon667bb4f2008-04-13 02:42:36 +0000438class PyWCmdLineTests(BaseTest, WCmdLineTests):
Brett Cannone9746892008-04-12 23:44:07 +0000439 module = py_warnings
440
441
Brett Cannon667bb4f2008-04-13 02:42:36 +0000442class _WarningsTests(BaseTest):
Brett Cannone9746892008-04-12 23:44:07 +0000443
444 """Tests specific to the _warnings module."""
445
446 module = c_warnings
447
448 def test_filter(self):
449 # Everything should function even if 'filters' is not in warnings.
Brett Cannon672237d2008-09-09 00:49:16 +0000450 with original_warnings.catch_warnings(module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000451 self.module.filterwarnings("error", "", Warning, "", 0)
452 self.assertRaises(UserWarning, self.module.warn,
453 'convert to error')
454 del self.module.filters
455 self.assertRaises(UserWarning, self.module.warn,
456 'convert to error')
457
458 def test_onceregistry(self):
459 # Replacing or removing the onceregistry should be okay.
460 global __warningregistry__
461 message = UserWarning('onceregistry test')
462 try:
463 original_registry = self.module.onceregistry
464 __warningregistry__ = {}
Brett Cannon672237d2008-09-09 00:49:16 +0000465 with original_warnings.catch_warnings(record=True,
466 module=self.module) as w:
Brett Cannone9746892008-04-12 23:44:07 +0000467 self.module.resetwarnings()
468 self.module.filterwarnings("once", category=UserWarning)
469 self.module.warn_explicit(message, UserWarning, "file", 42)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000470 self.assertEqual(w[-1].message, message)
Brett Cannon672237d2008-09-09 00:49:16 +0000471 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000472 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melotti2623a372010-11-21 13:34:58 +0000473 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000474 # Test the resetting of onceregistry.
475 self.module.onceregistry = {}
476 __warningregistry__ = {}
477 self.module.warn('onceregistry test')
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000478 self.assertEqual(w[-1].message.args, message.args)
Brett Cannone9746892008-04-12 23:44:07 +0000479 # Removal of onceregistry is okay.
Brett Cannon672237d2008-09-09 00:49:16 +0000480 del w[:]
Brett Cannone9746892008-04-12 23:44:07 +0000481 del self.module.onceregistry
482 __warningregistry__ = {}
483 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melotti2623a372010-11-21 13:34:58 +0000484 self.assertEqual(len(w), 0)
Brett Cannone9746892008-04-12 23:44:07 +0000485 finally:
486 self.module.onceregistry = original_registry
487
Brett Cannon15ba4da2009-04-01 18:03:59 +0000488 def test_default_action(self):
489 # Replacing or removing defaultaction should be okay.
490 message = UserWarning("defaultaction test")
491 original = self.module.defaultaction
492 try:
493 with original_warnings.catch_warnings(record=True,
494 module=self.module) as w:
495 self.module.resetwarnings()
496 registry = {}
497 self.module.warn_explicit(message, UserWarning, "<test>", 42,
498 registry=registry)
499 self.assertEqual(w[-1].message, message)
500 self.assertEqual(len(w), 1)
501 self.assertEqual(len(registry), 1)
502 del w[:]
503 # Test removal.
504 del self.module.defaultaction
505 __warningregistry__ = {}
506 registry = {}
507 self.module.warn_explicit(message, UserWarning, "<test>", 43,
508 registry=registry)
509 self.assertEqual(w[-1].message, message)
510 self.assertEqual(len(w), 1)
511 self.assertEqual(len(registry), 1)
512 del w[:]
513 # Test setting.
514 self.module.defaultaction = "ignore"
515 __warningregistry__ = {}
516 registry = {}
517 self.module.warn_explicit(message, UserWarning, "<test>", 44,
518 registry=registry)
519 self.assertEqual(len(w), 0)
520 finally:
521 self.module.defaultaction = original
522
Brett Cannone9746892008-04-12 23:44:07 +0000523 def test_showwarning_missing(self):
524 # Test that showwarning() missing is okay.
525 text = 'del showwarning test'
Brett Cannon672237d2008-09-09 00:49:16 +0000526 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000527 self.module.filterwarnings("always", category=UserWarning)
528 del self.module.showwarning
529 with test_support.captured_output('stderr') as stream:
530 self.module.warn(text)
531 result = stream.getvalue()
Ezio Melottiaa980582010-01-23 23:04:36 +0000532 self.assertIn(text, result)
Brett Cannone9746892008-04-12 23:44:07 +0000533
Benjamin Petersond2950322008-05-06 22:18:11 +0000534 def test_showwarning_not_callable(self):
Brett Cannonce3d2212009-04-01 20:25:48 +0000535 with original_warnings.catch_warnings(module=self.module):
536 self.module.filterwarnings("always", category=UserWarning)
537 old_showwarning = self.module.showwarning
538 self.module.showwarning = 23
539 try:
540 self.assertRaises(TypeError, self.module.warn, "Warning!")
541 finally:
542 self.module.showwarning = old_showwarning
Benjamin Petersond2950322008-05-06 22:18:11 +0000543
Brett Cannone9746892008-04-12 23:44:07 +0000544 def test_show_warning_output(self):
545 # With showarning() missing, make sure that output is okay.
546 text = 'test show_warning'
Brett Cannon672237d2008-09-09 00:49:16 +0000547 with original_warnings.catch_warnings(module=self.module):
Brett Cannone9746892008-04-12 23:44:07 +0000548 self.module.filterwarnings("always", category=UserWarning)
549 del self.module.showwarning
550 with test_support.captured_output('stderr') as stream:
551 warning_tests.inner(text)
552 result = stream.getvalue()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000553 self.assertEqual(result.count('\n'), 2,
Brett Cannone9746892008-04-12 23:44:07 +0000554 "Too many newlines in %r" % result)
555 first_line, second_line = result.split('\n', 1)
556 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Brett Cannonc4774272008-04-13 17:41:31 +0000557 first_line_parts = first_line.rsplit(':', 3)
Brett Cannon25bb8182008-04-13 17:09:43 +0000558 path, line, warning_class, message = first_line_parts
Brett Cannone9746892008-04-12 23:44:07 +0000559 line = int(line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000560 self.assertEqual(expected_file, path)
561 self.assertEqual(warning_class, ' ' + UserWarning.__name__)
562 self.assertEqual(message, ' ' + text)
Brett Cannone9746892008-04-12 23:44:07 +0000563 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
564 assert expected_line
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000565 self.assertEqual(second_line, expected_line)
Walter Dörwalde1a9b422007-04-03 16:53:43 +0000566
Victor Stinner65c15352011-07-04 03:05:37 +0200567 def test_filename_none(self):
568 # issue #12467: race condition if a warning is emitted at shutdown
569 globals_dict = globals()
570 oldfile = globals_dict['__file__']
571 try:
Berker Peksagccff2bb2016-04-16 22:16:05 +0300572 with original_warnings.catch_warnings(module=self.module, record=True) as w:
Victor Stinner65c15352011-07-04 03:05:37 +0200573 self.module.filterwarnings("always", category=UserWarning)
574 globals_dict['__file__'] = None
575 self.module.warn('test', UserWarning)
Berker Peksagccff2bb2016-04-16 22:16:05 +0300576 self.assertEqual(len(w), 1)
577 self.assertEqual(w[0].category, UserWarning)
578 self.assertEqual(str(w[0].message), 'test')
Victor Stinner65c15352011-07-04 03:05:37 +0200579 finally:
580 globals_dict['__file__'] = oldfile
581
Serhiy Storchakae6b42432014-12-10 23:05:33 +0200582 def test_stderr_none(self):
583 rc, stdout, stderr = assert_python_ok("-c",
584 "import sys; sys.stderr = None; "
585 "import warnings; warnings.simplefilter('always'); "
586 "warnings.warn('Warning!')")
587 self.assertEqual(stdout, b'')
588 self.assertNotIn(b'Warning!', stderr)
589 self.assertNotIn(b'Error', stderr)
590
Oren Milman40d736b2017-09-30 17:06:55 +0300591 def test_issue31285(self):
592 # warn_explicit() shouldn't raise a SystemError in case the return
593 # value of get_source() has a bad splitlines() method.
594 class BadLoader:
595 def get_source(self, fullname):
596 class BadSource(str):
597 def splitlines(self):
598 return 42
599 return BadSource('spam')
600
601 wmod = self.module
602 with original_warnings.catch_warnings(module=wmod):
603 wmod.filterwarnings('default', category=UserWarning)
604
605 with test_support.captured_stderr() as stderr:
606 wmod.warn_explicit(
607 'foo', UserWarning, 'bar', 1,
608 module_globals={'__loader__': BadLoader(),
609 '__name__': 'foobar'})
610 self.assertIn('UserWarning: foo', stderr.getvalue())
611
Serhiy Storchaka004547f2017-09-11 10:01:31 +0300612 @test_support.cpython_only
613 def test_issue31411(self):
614 # warn_explicit() shouldn't raise a SystemError in case
615 # warnings.onceregistry isn't a dictionary.
616 wmod = self.module
617 with original_warnings.catch_warnings(module=wmod):
618 wmod.filterwarnings('once')
619 with test_support.swap_attr(wmod, 'onceregistry', None):
620 with self.assertRaises(TypeError):
621 wmod.warn_explicit('foo', Warning, 'bar', 1, registry=None)
622
Brett Cannon53ab5b72006-06-22 16:49:14 +0000623
Brett Cannon905c31c2007-12-20 10:09:52 +0000624class WarningsDisplayTests(unittest.TestCase):
625
Brett Cannone9746892008-04-12 23:44:07 +0000626 """Test the displaying of warnings and the ability to overload functions
627 related to displaying warnings."""
628
Brett Cannon905c31c2007-12-20 10:09:52 +0000629 def test_formatwarning(self):
630 message = "msg"
631 category = Warning
632 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
633 line_num = 3
634 file_line = linecache.getline(file_name, line_num).strip()
Brett Cannone9746892008-04-12 23:44:07 +0000635 format = "%s:%s: %s: %s\n %s\n"
636 expect = format % (file_name, line_num, category.__name__, message,
637 file_line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000638 self.assertEqual(expect, self.module.formatwarning(message,
Brett Cannone9746892008-04-12 23:44:07 +0000639 category, file_name, line_num))
640 # Test the 'line' argument.
641 file_line += " for the win!"
642 expect = format % (file_name, line_num, category.__name__, message,
643 file_line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000644 self.assertEqual(expect, self.module.formatwarning(message,
Brett Cannone9746892008-04-12 23:44:07 +0000645 category, file_name, line_num, file_line))
Brett Cannon905c31c2007-12-20 10:09:52 +0000646
Serhiy Storchakaf40fcb32015-05-16 16:42:18 +0300647 @test_support.requires_unicode
648 def test_formatwarning_unicode_msg(self):
649 message = u"msg"
650 category = Warning
651 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
652 line_num = 3
653 file_line = linecache.getline(file_name, line_num).strip()
654 format = "%s:%s: %s: %s\n %s\n"
655 expect = format % (file_name, line_num, category.__name__, message,
656 file_line)
657 self.assertEqual(expect, self.module.formatwarning(message,
658 category, file_name, line_num))
659 # Test the 'line' argument.
660 file_line += " for the win!"
661 expect = format % (file_name, line_num, category.__name__, message,
662 file_line)
663 self.assertEqual(expect, self.module.formatwarning(message,
664 category, file_name, line_num, file_line))
665
666 @test_support.requires_unicode
667 @unittest.skipUnless(test_support.FS_NONASCII, 'need test_support.FS_NONASCII')
668 def test_formatwarning_unicode_msg_nonascii_filename(self):
669 message = u"msg"
670 category = Warning
671 unicode_file_name = test_support.FS_NONASCII + u'.py'
672 file_name = unicode_file_name.encode(sys.getfilesystemencoding())
673 line_num = 3
674 file_line = 'spam'
675 format = "%s:%s: %s: %s\n %s\n"
676 expect = format % (file_name, line_num, category.__name__, str(message),
677 file_line)
678 self.assertEqual(expect, self.module.formatwarning(message,
679 category, file_name, line_num, file_line))
680 message = u"\xb5sg"
681 expect = format % (unicode_file_name, line_num, category.__name__, message,
682 file_line)
683 self.assertEqual(expect, self.module.formatwarning(message,
684 category, file_name, line_num, file_line))
685
686 @test_support.requires_unicode
687 def test_formatwarning_unicode_msg_nonascii_fileline(self):
688 message = u"msg"
689 category = Warning
690 file_name = 'file.py'
691 line_num = 3
692 file_line = 'sp\xe4m'
693 format = "%s:%s: %s: %s\n %s\n"
694 expect = format % (file_name, line_num, category.__name__, str(message),
695 file_line)
696 self.assertEqual(expect, self.module.formatwarning(message,
697 category, file_name, line_num, file_line))
698 message = u"\xb5sg"
699 expect = format % (file_name, line_num, category.__name__, message,
700 unicode(file_line, 'latin1'))
701 self.assertEqual(expect, self.module.formatwarning(message,
702 category, file_name, line_num, file_line))
703
Brett Cannon905c31c2007-12-20 10:09:52 +0000704 def test_showwarning(self):
705 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
706 line_num = 3
707 expected_file_line = linecache.getline(file_name, line_num).strip()
708 message = 'msg'
709 category = Warning
710 file_object = StringIO.StringIO()
Brett Cannone9746892008-04-12 23:44:07 +0000711 expect = self.module.formatwarning(message, category, file_name,
712 line_num)
713 self.module.showwarning(message, category, file_name, line_num,
Brett Cannon905c31c2007-12-20 10:09:52 +0000714 file_object)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000715 self.assertEqual(file_object.getvalue(), expect)
Brett Cannone9746892008-04-12 23:44:07 +0000716 # Test 'line' argument.
717 expected_file_line += "for the win!"
718 expect = self.module.formatwarning(message, category, file_name,
719 line_num, expected_file_line)
720 file_object = StringIO.StringIO()
721 self.module.showwarning(message, category, file_name, line_num,
722 file_object, expected_file_line)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000723 self.assertEqual(expect, file_object.getvalue())
Brett Cannone9746892008-04-12 23:44:07 +0000724
Brett Cannon667bb4f2008-04-13 02:42:36 +0000725class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
Brett Cannone9746892008-04-12 23:44:07 +0000726 module = c_warnings
727
Brett Cannon667bb4f2008-04-13 02:42:36 +0000728class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
Brett Cannone9746892008-04-12 23:44:07 +0000729 module = py_warnings
Brett Cannon905c31c2007-12-20 10:09:52 +0000730
731
Brett Cannon1eaf0742008-09-02 01:25:16 +0000732class CatchWarningTests(BaseTest):
Nick Coghlan38469e22008-07-13 12:23:47 +0000733
Brett Cannon1eaf0742008-09-02 01:25:16 +0000734 """Test catch_warnings()."""
735
736 def test_catch_warnings_restore(self):
Nick Coghlan38469e22008-07-13 12:23:47 +0000737 wmod = self.module
738 orig_filters = wmod.filters
739 orig_showwarning = wmod.showwarning
Nick Coghland2e09382008-09-11 12:11:06 +0000740 # Ensure both showwarning and filters are restored when recording
741 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlan38469e22008-07-13 12:23:47 +0000742 wmod.filters = wmod.showwarning = object()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000743 self.assertTrue(wmod.filters is orig_filters)
744 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghland2e09382008-09-11 12:11:06 +0000745 # Same test, but with recording disabled
Brett Cannon1eaf0742008-09-02 01:25:16 +0000746 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlan38469e22008-07-13 12:23:47 +0000747 wmod.filters = wmod.showwarning = object()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000748 self.assertTrue(wmod.filters is orig_filters)
749 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlan38469e22008-07-13 12:23:47 +0000750
Brett Cannon1eaf0742008-09-02 01:25:16 +0000751 def test_catch_warnings_recording(self):
Nick Coghlan38469e22008-07-13 12:23:47 +0000752 wmod = self.module
Nick Coghland2e09382008-09-11 12:11:06 +0000753 # Ensure warnings are recorded when requested
Brett Cannon1eaf0742008-09-02 01:25:16 +0000754 with wmod.catch_warnings(module=wmod, record=True) as w:
755 self.assertEqual(w, [])
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000756 self.assertTrue(type(w) is list)
Nick Coghlan38469e22008-07-13 12:23:47 +0000757 wmod.simplefilter("always")
758 wmod.warn("foo")
Brett Cannon672237d2008-09-09 00:49:16 +0000759 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlan38469e22008-07-13 12:23:47 +0000760 wmod.warn("bar")
Brett Cannon672237d2008-09-09 00:49:16 +0000761 self.assertEqual(str(w[-1].message), "bar")
Brett Cannon1eaf0742008-09-02 01:25:16 +0000762 self.assertEqual(str(w[0].message), "foo")
763 self.assertEqual(str(w[1].message), "bar")
Brett Cannon672237d2008-09-09 00:49:16 +0000764 del w[:]
Brett Cannon1eaf0742008-09-02 01:25:16 +0000765 self.assertEqual(w, [])
Nick Coghland2e09382008-09-11 12:11:06 +0000766 # Ensure warnings are not recorded when not requested
Nick Coghlan38469e22008-07-13 12:23:47 +0000767 orig_showwarning = wmod.showwarning
Brett Cannon1eaf0742008-09-02 01:25:16 +0000768 with wmod.catch_warnings(module=wmod, record=False) as w:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000769 self.assertTrue(w is None)
770 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlan38469e22008-07-13 12:23:47 +0000771
Nick Coghland2e09382008-09-11 12:11:06 +0000772 def test_catch_warnings_reentry_guard(self):
773 wmod = self.module
774 # Ensure catch_warnings is protected against incorrect usage
775 x = wmod.catch_warnings(module=wmod, record=True)
776 self.assertRaises(RuntimeError, x.__exit__)
777 with x:
778 self.assertRaises(RuntimeError, x.__enter__)
779 # Same test, but with recording disabled
780 x = wmod.catch_warnings(module=wmod, record=False)
781 self.assertRaises(RuntimeError, x.__exit__)
782 with x:
783 self.assertRaises(RuntimeError, x.__enter__)
784
785 def test_catch_warnings_defaults(self):
786 wmod = self.module
787 orig_filters = wmod.filters
788 orig_showwarning = wmod.showwarning
789 # Ensure default behaviour is not to record warnings
790 with wmod.catch_warnings(module=wmod) as w:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000791 self.assertTrue(w is None)
792 self.assertTrue(wmod.showwarning is orig_showwarning)
793 self.assertTrue(wmod.filters is not orig_filters)
794 self.assertTrue(wmod.filters is orig_filters)
Nick Coghland2e09382008-09-11 12:11:06 +0000795 if wmod is sys.modules['warnings']:
796 # Ensure the default module is this one
797 with wmod.catch_warnings() as w:
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000798 self.assertTrue(w is None)
799 self.assertTrue(wmod.showwarning is orig_showwarning)
800 self.assertTrue(wmod.filters is not orig_filters)
801 self.assertTrue(wmod.filters is orig_filters)
Nick Coghland2e09382008-09-11 12:11:06 +0000802
803 def test_check_warnings(self):
804 # Explicit tests for the test_support convenience wrapper
805 wmod = self.module
Florent Xicluna73588542010-03-18 19:51:47 +0000806 if wmod is not sys.modules['warnings']:
Zachary Ware1f702212013-12-10 14:09:20 -0600807 self.skipTest('module to test is not loaded warnings module')
Florent Xicluna73588542010-03-18 19:51:47 +0000808 with test_support.check_warnings(quiet=False) as w:
809 self.assertEqual(w.warnings, [])
810 wmod.simplefilter("always")
811 wmod.warn("foo")
812 self.assertEqual(str(w.message), "foo")
813 wmod.warn("bar")
814 self.assertEqual(str(w.message), "bar")
815 self.assertEqual(str(w.warnings[0].message), "foo")
816 self.assertEqual(str(w.warnings[1].message), "bar")
817 w.reset()
818 self.assertEqual(w.warnings, [])
Nick Coghland2e09382008-09-11 12:11:06 +0000819
Florent Xicluna73588542010-03-18 19:51:47 +0000820 with test_support.check_warnings():
821 # defaults to quiet=True without argument
822 pass
823 with test_support.check_warnings(('foo', UserWarning)):
824 wmod.warn("foo")
825
826 with self.assertRaises(AssertionError):
827 with test_support.check_warnings(('', RuntimeWarning)):
828 # defaults to quiet=False with argument
829 pass
830 with self.assertRaises(AssertionError):
831 with test_support.check_warnings(('foo', RuntimeWarning)):
832 wmod.warn("foo")
Nick Coghland2e09382008-09-11 12:11:06 +0000833
834
Brett Cannon1eaf0742008-09-02 01:25:16 +0000835class CCatchWarningTests(CatchWarningTests):
Nick Coghlan38469e22008-07-13 12:23:47 +0000836 module = c_warnings
837
Brett Cannon1eaf0742008-09-02 01:25:16 +0000838class PyCatchWarningTests(CatchWarningTests):
Nick Coghlan38469e22008-07-13 12:23:47 +0000839 module = py_warnings
840
841
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000842class EnvironmentVariableTests(BaseTest):
843
844 def test_single_warning(self):
845 newenv = os.environ.copy()
846 newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
847 p = subprocess.Popen([sys.executable,
848 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
849 stdout=subprocess.PIPE, env=newenv)
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000850 self.assertEqual(p.communicate()[0], "['ignore::DeprecationWarning']")
851 self.assertEqual(p.wait(), 0)
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000852
853 def test_comma_separated_warnings(self):
854 newenv = os.environ.copy()
855 newenv["PYTHONWARNINGS"] = ("ignore::DeprecationWarning,"
856 "ignore::UnicodeWarning")
857 p = subprocess.Popen([sys.executable,
858 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
859 stdout=subprocess.PIPE, env=newenv)
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000860 self.assertEqual(p.communicate()[0],
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000861 "['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000862 self.assertEqual(p.wait(), 0)
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000863
864 def test_envvar_and_command_line(self):
865 newenv = os.environ.copy()
866 newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
867 p = subprocess.Popen([sys.executable, "-W" "ignore::UnicodeWarning",
868 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
869 stdout=subprocess.PIPE, env=newenv)
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000870 self.assertEqual(p.communicate()[0],
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000871 "['ignore::UnicodeWarning', 'ignore::DeprecationWarning']")
Philip Jenveycdd98fb2010-04-10 20:27:15 +0000872 self.assertEqual(p.wait(), 0)
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000873
874class CEnvironmentVariableTests(EnvironmentVariableTests):
875 module = c_warnings
876
877class PyEnvironmentVariableTests(EnvironmentVariableTests):
878 module = py_warnings
879
880
Brett Cannone9746892008-04-12 23:44:07 +0000881def test_main():
Amaury Forgeot d'Arc607bff12008-04-18 23:31:33 +0000882 py_warnings.onceregistry.clear()
883 c_warnings.onceregistry.clear()
Brett Cannon1eaf0742008-09-02 01:25:16 +0000884 test_support.run_unittest(CFilterTests, PyFilterTests,
885 CWarnTests, PyWarnTests,
Brett Cannone9746892008-04-12 23:44:07 +0000886 CWCmdLineTests, PyWCmdLineTests,
887 _WarningsTests,
888 CWarningsDisplayTests, PyWarningsDisplayTests,
Brett Cannon1eaf0742008-09-02 01:25:16 +0000889 CCatchWarningTests, PyCatchWarningTests,
Philip Jenveyaebbaeb2010-04-06 23:24:45 +0000890 CEnvironmentVariableTests,
891 PyEnvironmentVariableTests
Brett Cannone9746892008-04-12 23:44:07 +0000892 )
893
894
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000895if __name__ == "__main__":
Brett Cannone9746892008-04-12 23:44:07 +0000896 test_main()