blob: 6ce0b23474b7c9561585365d7103457a24c6c0c4 [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
Philip Jenvey0805ca32010-04-07 04:04:10 +00007import subprocess
Benjamin Petersonee8712c2008-05-20 21:35:26 +00008from test import support
Antoine Pitroucf9f9802010-11-10 13:55:25 +00009from test.script_helper import assert_python_ok
Jeremy Hylton85014662003-07-11 15:37:59 +000010
Guido van Rossum805365e2007-05-07 22:24:25 +000011from test import warning_tests
Jeremy Hylton85014662003-07-11 15:37:59 +000012
Christian Heimes33fe8092008-04-13 13:53:33 +000013import warnings as original_warnings
Jeremy Hylton85014662003-07-11 15:37:59 +000014
Nick Coghlan47384702009-04-22 16:13:36 +000015py_warnings = support.import_fresh_module('warnings', blocked=['_warnings'])
16c_warnings = support.import_fresh_module('warnings', fresh=['_warnings'])
Christian Heimes33fe8092008-04-13 13:53:33 +000017
18@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 Xiclunafd1b0932010-03-28 00:25:02 +000032 original_filters = module.filters
Christian Heimes33fe8092008-04-13 13:53:33 +000033 try:
Florent Xiclunafd1b0932010-03-28 00:25:02 +000034 module.filters = original_filters[:]
35 module.simplefilter("once")
Christian Heimes33fe8092008-04-13 13:53:33 +000036 warning_tests.warnings = module
37 yield
38 finally:
39 warning_tests.warnings = original_warnings
Florent Xiclunafd1b0932010-03-28 00:25:02 +000040 module.filters = original_filters
Christian Heimes33fe8092008-04-13 13:53:33 +000041
42
Ezio Melotti2688e812013-01-10 06:52:23 +020043class BaseTest:
Christian Heimes33fe8092008-04-13 13:53:33 +000044
45 """Basic bookkeeping required for testing."""
46
47 def setUp(self):
48 # 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
65
Ezio Melotti2688e812013-01-10 06:52:23 +020066class FilterTests(BaseTest):
Christian Heimes33fe8092008-04-13 13:53:33 +000067
68 """Testing the filtering functionality."""
69
70 def test_error(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000071 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000072 self.module.resetwarnings()
73 self.module.filterwarnings("error", category=UserWarning)
74 self.assertRaises(UserWarning, self.module.warn,
75 "FilterTests.test_error")
76
77 def test_ignore(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000078 with original_warnings.catch_warnings(record=True,
79 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000080 self.module.resetwarnings()
81 self.module.filterwarnings("ignore", category=UserWarning)
82 self.module.warn("FilterTests.test_ignore", UserWarning)
Ezio Melottib3aedd42010-11-20 19:04:17 +000083 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +000084
85 def test_always(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000086 with original_warnings.catch_warnings(record=True,
87 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000088 self.module.resetwarnings()
89 self.module.filterwarnings("always", category=UserWarning)
90 message = "FilterTests.test_always"
91 self.module.warn(message, UserWarning)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000092 self.assertTrue(message, w[-1].message)
Christian Heimes33fe8092008-04-13 13:53:33 +000093 self.module.warn(message, UserWarning)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000094 self.assertTrue(w[-1].message, message)
Christian Heimes33fe8092008-04-13 13:53:33 +000095
96 def test_default(self):
Brett Cannon1cd02472008-09-09 01:52:27 +000097 with original_warnings.catch_warnings(record=True,
98 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +000099 self.module.resetwarnings()
100 self.module.filterwarnings("default", category=UserWarning)
101 message = UserWarning("FilterTests.test_default")
102 for x in range(2):
103 self.module.warn(message, UserWarning)
104 if x == 0:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000105 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000106 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000107 elif x == 1:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000108 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000109 else:
110 raise ValueError("loop variant unhandled")
111
112 def test_module(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000113 with original_warnings.catch_warnings(record=True,
114 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000115 self.module.resetwarnings()
116 self.module.filterwarnings("module", category=UserWarning)
117 message = UserWarning("FilterTests.test_module")
118 self.module.warn(message, UserWarning)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000119 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000120 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000121 self.module.warn(message, UserWarning)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000122 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000123
124 def test_once(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000125 with original_warnings.catch_warnings(record=True,
126 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000127 self.module.resetwarnings()
128 self.module.filterwarnings("once", category=UserWarning)
129 message = UserWarning("FilterTests.test_once")
130 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
131 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000132 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000133 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000134 self.module.warn_explicit(message, UserWarning, "test_warnings.py",
135 13)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000136 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000137 self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
138 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000139 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000140
141 def test_inheritance(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000142 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000143 self.module.resetwarnings()
144 self.module.filterwarnings("error", category=Warning)
145 self.assertRaises(UserWarning, self.module.warn,
146 "FilterTests.test_inheritance", UserWarning)
147
148 def test_ordering(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000149 with original_warnings.catch_warnings(record=True,
150 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000151 self.module.resetwarnings()
152 self.module.filterwarnings("ignore", category=UserWarning)
153 self.module.filterwarnings("error", category=UserWarning,
154 append=True)
Brett Cannon1cd02472008-09-09 01:52:27 +0000155 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000156 try:
157 self.module.warn("FilterTests.test_ordering", UserWarning)
158 except UserWarning:
159 self.fail("order handling for actions failed")
Ezio Melottib3aedd42010-11-20 19:04:17 +0000160 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000161
162 def test_filterwarnings(self):
163 # Test filterwarnings().
164 # Implicitly also tests resetwarnings().
Brett Cannon1cd02472008-09-09 01:52:27 +0000165 with original_warnings.catch_warnings(record=True,
166 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000167 self.module.filterwarnings("error", "", Warning, "", 0)
168 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
169
170 self.module.resetwarnings()
171 text = 'handle normally'
172 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000173 self.assertEqual(str(w[-1].message), text)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000174 self.assertTrue(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000175
176 self.module.filterwarnings("ignore", "", Warning, "", 0)
177 text = 'filtered out'
178 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000179 self.assertNotEqual(str(w[-1].message), text)
Christian Heimes33fe8092008-04-13 13:53:33 +0000180
181 self.module.resetwarnings()
182 self.module.filterwarnings("error", "hex*", Warning, "", 0)
183 self.assertRaises(UserWarning, self.module.warn, 'hex/oct')
184 text = 'nonmatching text'
185 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000186 self.assertEqual(str(w[-1].message), text)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000187 self.assertTrue(w[-1].category is UserWarning)
Christian Heimes33fe8092008-04-13 13:53:33 +0000188
Ezio Melotti2688e812013-01-10 06:52:23 +0200189class CFilterTests(FilterTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000190 module = c_warnings
191
Ezio Melotti2688e812013-01-10 06:52:23 +0200192class PyFilterTests(FilterTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000193 module = py_warnings
194
195
Ezio Melotti2688e812013-01-10 06:52:23 +0200196class WarnTests(BaseTest):
Christian Heimes33fe8092008-04-13 13:53:33 +0000197
198 """Test warnings.warn() and warnings.warn_explicit()."""
199
200 def test_message(self):
Brett Cannon1cd02472008-09-09 01:52:27 +0000201 with original_warnings.catch_warnings(record=True,
202 module=self.module) as w:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000203 self.module.simplefilter("once")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000204 for i in range(4):
Christian Heimes33fe8092008-04-13 13:53:33 +0000205 text = 'multi %d' %i # Different text on each call.
206 self.module.warn(text)
Brett Cannon1cd02472008-09-09 01:52:27 +0000207 self.assertEqual(str(w[-1].message), text)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000208 self.assertTrue(w[-1].category is UserWarning)
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000209
Brett Cannon54bd41d2008-09-02 04:01:42 +0000210 # Issue 3639
211 def test_warn_nonstandard_types(self):
212 # warn() should handle non-standard types without issue.
213 for ob in (Warning, None, 42):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000214 with original_warnings.catch_warnings(record=True,
215 module=self.module) as w:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000216 self.module.simplefilter("once")
Brett Cannon54bd41d2008-09-02 04:01:42 +0000217 self.module.warn(ob)
218 # Don't directly compare objects since
219 # ``Warning() != Warning()``.
Ezio Melottib3aedd42010-11-20 19:04:17 +0000220 self.assertEqual(str(w[-1].message), str(UserWarning(ob)))
Brett Cannon54bd41d2008-09-02 04:01:42 +0000221
Guido van Rossumd8faa362007-04-27 19:54:29 +0000222 def test_filename(self):
Christian Heimes33fe8092008-04-13 13:53:33 +0000223 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000224 with original_warnings.catch_warnings(record=True,
225 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000226 warning_tests.inner("spam1")
Brett Cannon1cd02472008-09-09 01:52:27 +0000227 self.assertEqual(os.path.basename(w[-1].filename),
228 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000229 warning_tests.outer("spam2")
Brett Cannon1cd02472008-09-09 01:52:27 +0000230 self.assertEqual(os.path.basename(w[-1].filename),
231 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000232
233 def test_stacklevel(self):
234 # Test stacklevel argument
235 # make sure all messages are different, so the warning won't be skipped
Christian Heimes33fe8092008-04-13 13:53:33 +0000236 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000237 with original_warnings.catch_warnings(record=True,
238 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000239 warning_tests.inner("spam3", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000240 self.assertEqual(os.path.basename(w[-1].filename),
241 "warning_tests.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000242 warning_tests.outer("spam4", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000243 self.assertEqual(os.path.basename(w[-1].filename),
244 "warning_tests.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000245
Christian Heimes33fe8092008-04-13 13:53:33 +0000246 warning_tests.inner("spam5", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000247 self.assertEqual(os.path.basename(w[-1].filename),
248 "test_warnings.py")
Christian Heimes33fe8092008-04-13 13:53:33 +0000249 warning_tests.outer("spam6", stacklevel=2)
Brett Cannon1cd02472008-09-09 01:52:27 +0000250 self.assertEqual(os.path.basename(w[-1].filename),
251 "warning_tests.py")
Christian Heimes5d8da202008-05-06 13:58:24 +0000252 warning_tests.outer("spam6.5", stacklevel=3)
Brett Cannon1cd02472008-09-09 01:52:27 +0000253 self.assertEqual(os.path.basename(w[-1].filename),
254 "test_warnings.py")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000255
Christian Heimes33fe8092008-04-13 13:53:33 +0000256 warning_tests.inner("spam7", stacklevel=9999)
Brett Cannon1cd02472008-09-09 01:52:27 +0000257 self.assertEqual(os.path.basename(w[-1].filename),
258 "sys")
Christian Heimes33fe8092008-04-13 13:53:33 +0000259
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000260 def test_missing_filename_not_main(self):
261 # If __file__ is not specified and __main__ is not the module name,
262 # then __file__ should be set to the module name.
263 filename = warning_tests.__file__
264 try:
265 del warning_tests.__file__
266 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000267 with original_warnings.catch_warnings(record=True,
268 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000269 warning_tests.inner("spam8", stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000270 self.assertEqual(w[-1].filename, warning_tests.__name__)
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000271 finally:
272 warning_tests.__file__ = filename
273
Serhiy Storchaka79080682013-11-03 21:31:18 +0200274 @unittest.skipUnless(hasattr(sys, 'argv'), 'test needs sys.argv')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000275 def test_missing_filename_main_with_argv(self):
276 # If __file__ is not specified and the caller is __main__ and sys.argv
277 # exists, then use sys.argv[0] as the file.
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000278 filename = warning_tests.__file__
279 module_name = warning_tests.__name__
280 try:
281 del warning_tests.__file__
282 warning_tests.__name__ = '__main__'
283 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000284 with original_warnings.catch_warnings(record=True,
285 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000286 warning_tests.inner('spam9', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000287 self.assertEqual(w[-1].filename, sys.argv[0])
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000288 finally:
289 warning_tests.__file__ = filename
290 warning_tests.__name__ = module_name
291
292 def test_missing_filename_main_without_argv(self):
293 # If __file__ is not specified, the caller is __main__, and sys.argv
294 # is not set, then '__main__' is the file name.
295 filename = warning_tests.__file__
296 module_name = warning_tests.__name__
297 argv = sys.argv
298 try:
299 del warning_tests.__file__
300 warning_tests.__name__ = '__main__'
301 del sys.argv
302 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000303 with original_warnings.catch_warnings(record=True,
304 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000305 warning_tests.inner('spam10', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000306 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000307 finally:
308 warning_tests.__file__ = filename
309 warning_tests.__name__ = module_name
310 sys.argv = argv
311
Christian Heimesdaaf8ee2008-05-04 23:58:41 +0000312 def test_missing_filename_main_with_argv_empty_string(self):
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000313 # If __file__ is not specified, the caller is __main__, and sys.argv[0]
314 # is the empty string, then '__main__ is the file name.
315 # Tests issue 2743.
316 file_name = warning_tests.__file__
317 module_name = warning_tests.__name__
318 argv = sys.argv
319 try:
320 del warning_tests.__file__
321 warning_tests.__name__ = '__main__'
322 sys.argv = ['']
323 with warnings_state(self.module):
Brett Cannon1cd02472008-09-09 01:52:27 +0000324 with original_warnings.catch_warnings(record=True,
325 module=self.module) as w:
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000326 warning_tests.inner('spam11', stacklevel=1)
Brett Cannon1cd02472008-09-09 01:52:27 +0000327 self.assertEqual(w[-1].filename, '__main__')
Christian Heimes81ee3ef2008-05-04 22:42:01 +0000328 finally:
329 warning_tests.__file__ = file_name
330 warning_tests.__name__ = module_name
331 sys.argv = argv
332
Brett Cannondb734912008-06-27 00:52:15 +0000333 def test_warn_explicit_type_errors(self):
Ezio Melotti13925002011-03-16 11:05:33 +0200334 # warn_explicit() should error out gracefully if it is given objects
Brett Cannondb734912008-06-27 00:52:15 +0000335 # of the wrong types.
336 # lineno is expected to be an integer.
337 self.assertRaises(TypeError, self.module.warn_explicit,
338 None, UserWarning, None, None)
339 # Either 'message' needs to be an instance of Warning or 'category'
340 # needs to be a subclass.
341 self.assertRaises(TypeError, self.module.warn_explicit,
342 None, None, None, 1)
343 # 'registry' must be a dict or None.
344 self.assertRaises((TypeError, AttributeError),
345 self.module.warn_explicit,
346 None, Warning, None, 1, registry=42)
347
Hirokazu Yamamoto1c0c0032009-07-17 06:55:42 +0000348 def test_bad_str(self):
349 # issue 6415
350 # Warnings instance with a bad format string for __str__ should not
351 # trigger a bus error.
352 class BadStrWarning(Warning):
353 """Warning with a bad format string for __str__."""
354 def __str__(self):
355 return ("A bad formatted string %(err)" %
356 {"err" : "there is no %(err)s"})
357
358 with self.assertRaises(ValueError):
359 self.module.warn(BadStrWarning())
360
361
Ezio Melotti2688e812013-01-10 06:52:23 +0200362class CWarnTests(WarnTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000363 module = c_warnings
364
Nick Coghlanfce769e2009-04-11 14:30:59 +0000365 # As an early adopter, we sanity check the
366 # test.support.import_fresh_module utility function
367 def test_accelerated(self):
368 self.assertFalse(original_warnings is self.module)
369 self.assertFalse(hasattr(self.module.warn, '__code__'))
370
Ezio Melotti2688e812013-01-10 06:52:23 +0200371class PyWarnTests(WarnTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000372 module = py_warnings
373
Nick Coghlanfce769e2009-04-11 14:30:59 +0000374 # As an early adopter, we sanity check the
375 # test.support.import_fresh_module utility function
376 def test_pure_python(self):
377 self.assertFalse(original_warnings is self.module)
378 self.assertTrue(hasattr(self.module.warn, '__code__'))
379
Christian Heimes33fe8092008-04-13 13:53:33 +0000380
Ezio Melotti2688e812013-01-10 06:52:23 +0200381class WCmdLineTests(BaseTest):
Christian Heimes33fe8092008-04-13 13:53:33 +0000382
383 def test_improper_input(self):
384 # Uses the private _setoption() function to test the parsing
385 # of command-line warning arguments
Brett Cannon1cd02472008-09-09 01:52:27 +0000386 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000387 self.assertRaises(self.module._OptionError,
388 self.module._setoption, '1:2:3:4:5:6')
389 self.assertRaises(self.module._OptionError,
390 self.module._setoption, 'bogus::Warning')
391 self.assertRaises(self.module._OptionError,
392 self.module._setoption, 'ignore:2::4:-5')
393 self.module._setoption('error::Warning::0')
394 self.assertRaises(UserWarning, self.module.warn, 'convert to error')
395
Antoine Pitroucf9f9802010-11-10 13:55:25 +0000396 def test_improper_option(self):
397 # Same as above, but check that the message is printed out when
398 # the interpreter is executed. This also checks that options are
399 # actually parsed at all.
400 rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")
401 self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)
402
403 def test_warnings_bootstrap(self):
404 # Check that the warnings module does get loaded when -W<some option>
405 # is used (see issue #10372 for an example of silent bootstrap failure).
406 rc, out, err = assert_python_ok("-Wi", "-c",
407 "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
408 # '-Wi' was observed
409 self.assertFalse(out.strip())
410 self.assertNotIn(b'RuntimeWarning', err)
411
Ezio Melotti2688e812013-01-10 06:52:23 +0200412class CWCmdLineTests(WCmdLineTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000413 module = c_warnings
414
Ezio Melotti2688e812013-01-10 06:52:23 +0200415class PyWCmdLineTests(WCmdLineTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000416 module = py_warnings
417
418
Ezio Melotti2688e812013-01-10 06:52:23 +0200419class _WarningsTests(BaseTest, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000420
421 """Tests specific to the _warnings module."""
422
423 module = c_warnings
424
425 def test_filter(self):
426 # Everything should function even if 'filters' is not in warnings.
Brett Cannon1cd02472008-09-09 01:52:27 +0000427 with original_warnings.catch_warnings(module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000428 self.module.filterwarnings("error", "", Warning, "", 0)
429 self.assertRaises(UserWarning, self.module.warn,
430 'convert to error')
431 del self.module.filters
432 self.assertRaises(UserWarning, self.module.warn,
433 'convert to error')
434
435 def test_onceregistry(self):
436 # Replacing or removing the onceregistry should be okay.
437 global __warningregistry__
438 message = UserWarning('onceregistry test')
439 try:
440 original_registry = self.module.onceregistry
441 __warningregistry__ = {}
Brett Cannon1cd02472008-09-09 01:52:27 +0000442 with original_warnings.catch_warnings(record=True,
443 module=self.module) as w:
Christian Heimes33fe8092008-04-13 13:53:33 +0000444 self.module.resetwarnings()
445 self.module.filterwarnings("once", category=UserWarning)
446 self.module.warn_explicit(message, UserWarning, "file", 42)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000447 self.assertEqual(w[-1].message, message)
Brett Cannon1cd02472008-09-09 01:52:27 +0000448 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000449 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000450 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000451 # Test the resetting of onceregistry.
452 self.module.onceregistry = {}
453 __warningregistry__ = {}
454 self.module.warn('onceregistry test')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000455 self.assertEqual(w[-1].message.args, message.args)
Christian Heimes33fe8092008-04-13 13:53:33 +0000456 # Removal of onceregistry is okay.
Brett Cannon1cd02472008-09-09 01:52:27 +0000457 del w[:]
Christian Heimes33fe8092008-04-13 13:53:33 +0000458 del self.module.onceregistry
459 __warningregistry__ = {}
460 self.module.warn_explicit(message, UserWarning, "file", 42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000461 self.assertEqual(len(w), 0)
Christian Heimes33fe8092008-04-13 13:53:33 +0000462 finally:
463 self.module.onceregistry = original_registry
464
Brett Cannon0759dd62009-04-01 18:13:07 +0000465 def test_default_action(self):
466 # Replacing or removing defaultaction should be okay.
467 message = UserWarning("defaultaction test")
468 original = self.module.defaultaction
469 try:
470 with original_warnings.catch_warnings(record=True,
471 module=self.module) as w:
472 self.module.resetwarnings()
473 registry = {}
474 self.module.warn_explicit(message, UserWarning, "<test>", 42,
475 registry=registry)
476 self.assertEqual(w[-1].message, message)
477 self.assertEqual(len(w), 1)
478 self.assertEqual(len(registry), 1)
479 del w[:]
480 # Test removal.
481 del self.module.defaultaction
482 __warningregistry__ = {}
483 registry = {}
484 self.module.warn_explicit(message, UserWarning, "<test>", 43,
485 registry=registry)
486 self.assertEqual(w[-1].message, message)
487 self.assertEqual(len(w), 1)
488 self.assertEqual(len(registry), 1)
489 del w[:]
490 # Test setting.
491 self.module.defaultaction = "ignore"
492 __warningregistry__ = {}
493 registry = {}
494 self.module.warn_explicit(message, UserWarning, "<test>", 44,
495 registry=registry)
496 self.assertEqual(len(w), 0)
497 finally:
498 self.module.defaultaction = original
499
Christian Heimes33fe8092008-04-13 13:53:33 +0000500 def test_showwarning_missing(self):
501 # Test that showwarning() missing is okay.
502 text = 'del showwarning test'
Brett Cannon1cd02472008-09-09 01:52:27 +0000503 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000504 self.module.filterwarnings("always", category=UserWarning)
505 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000506 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000507 self.module.warn(text)
508 result = stream.getvalue()
Benjamin Peterson577473f2010-01-19 00:09:57 +0000509 self.assertIn(text, result)
Christian Heimes33fe8092008-04-13 13:53:33 +0000510
Christian Heimes8dc226f2008-05-06 23:45:46 +0000511 def test_showwarning_not_callable(self):
Brett Cannonfcc05272009-04-01 20:27:29 +0000512 with original_warnings.catch_warnings(module=self.module):
513 self.module.filterwarnings("always", category=UserWarning)
Brett Cannon52a7d982011-07-17 19:17:55 -0700514 self.module.showwarning = print
515 with support.captured_output('stdout'):
516 self.module.warn('Warning!')
Brett Cannonfcc05272009-04-01 20:27:29 +0000517 self.module.showwarning = 23
Brett Cannon52a7d982011-07-17 19:17:55 -0700518 self.assertRaises(TypeError, self.module.warn, "Warning!")
Christian Heimes8dc226f2008-05-06 23:45:46 +0000519
Christian Heimes33fe8092008-04-13 13:53:33 +0000520 def test_show_warning_output(self):
521 # With showarning() missing, make sure that output is okay.
522 text = 'test show_warning'
Brett Cannon1cd02472008-09-09 01:52:27 +0000523 with original_warnings.catch_warnings(module=self.module):
Christian Heimes33fe8092008-04-13 13:53:33 +0000524 self.module.filterwarnings("always", category=UserWarning)
525 del self.module.showwarning
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000526 with support.captured_output('stderr') as stream:
Christian Heimes33fe8092008-04-13 13:53:33 +0000527 warning_tests.inner(text)
528 result = stream.getvalue()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000529 self.assertEqual(result.count('\n'), 2,
Christian Heimes33fe8092008-04-13 13:53:33 +0000530 "Too many newlines in %r" % result)
531 first_line, second_line = result.split('\n', 1)
532 expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
Neal Norwitz32dde222008-04-15 06:43:13 +0000533 first_line_parts = first_line.rsplit(':', 3)
534 path, line, warning_class, message = first_line_parts
Christian Heimes33fe8092008-04-13 13:53:33 +0000535 line = int(line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000536 self.assertEqual(expected_file, path)
537 self.assertEqual(warning_class, ' ' + UserWarning.__name__)
538 self.assertEqual(message, ' ' + text)
Christian Heimes33fe8092008-04-13 13:53:33 +0000539 expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
540 assert expected_line
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000541 self.assertEqual(second_line, expected_line)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000542
Victor Stinner8b0508e2011-07-04 02:43:09 +0200543 def test_filename_none(self):
544 # issue #12467: race condition if a warning is emitted at shutdown
545 globals_dict = globals()
546 oldfile = globals_dict['__file__']
547 try:
Brett Cannon52a7d982011-07-17 19:17:55 -0700548 catch = original_warnings.catch_warnings(record=True,
549 module=self.module)
550 with catch as w:
Victor Stinner8b0508e2011-07-04 02:43:09 +0200551 self.module.filterwarnings("always", category=UserWarning)
552 globals_dict['__file__'] = None
553 original_warnings.warn('test', UserWarning)
Brett Cannon52a7d982011-07-17 19:17:55 -0700554 self.assertTrue(len(w))
Victor Stinner8b0508e2011-07-04 02:43:09 +0200555 finally:
556 globals_dict['__file__'] = oldfile
557
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000558
Ezio Melotti2688e812013-01-10 06:52:23 +0200559class WarningsDisplayTests(BaseTest):
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000560
Christian Heimes33fe8092008-04-13 13:53:33 +0000561 """Test the displaying of warnings and the ability to overload functions
562 related to displaying warnings."""
563
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000564 def test_formatwarning(self):
565 message = "msg"
566 category = Warning
567 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
568 line_num = 3
569 file_line = linecache.getline(file_name, line_num).strip()
Christian Heimes33fe8092008-04-13 13:53:33 +0000570 format = "%s:%s: %s: %s\n %s\n"
571 expect = format % (file_name, line_num, category.__name__, message,
572 file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000573 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000574 category, file_name, line_num))
575 # Test the 'line' argument.
576 file_line += " for the win!"
577 expect = format % (file_name, line_num, category.__name__, message,
578 file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000579 self.assertEqual(expect, self.module.formatwarning(message,
Christian Heimes33fe8092008-04-13 13:53:33 +0000580 category, file_name, line_num, file_line))
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000581
582 def test_showwarning(self):
583 file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
584 line_num = 3
585 expected_file_line = linecache.getline(file_name, line_num).strip()
586 message = 'msg'
587 category = Warning
588 file_object = StringIO()
Christian Heimes33fe8092008-04-13 13:53:33 +0000589 expect = self.module.formatwarning(message, category, file_name,
590 line_num)
591 self.module.showwarning(message, category, file_name, line_num,
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000592 file_object)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000593 self.assertEqual(file_object.getvalue(), expect)
Christian Heimes33fe8092008-04-13 13:53:33 +0000594 # Test 'line' argument.
595 expected_file_line += "for the win!"
596 expect = self.module.formatwarning(message, category, file_name,
597 line_num, expected_file_line)
598 file_object = StringIO()
599 self.module.showwarning(message, category, file_name, line_num,
600 file_object, expected_file_line)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000601 self.assertEqual(expect, file_object.getvalue())
Christian Heimes33fe8092008-04-13 13:53:33 +0000602
Ezio Melotti2688e812013-01-10 06:52:23 +0200603class CWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000604 module = c_warnings
605
Ezio Melotti2688e812013-01-10 06:52:23 +0200606class PyWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase):
Christian Heimes33fe8092008-04-13 13:53:33 +0000607 module = py_warnings
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000608
Brett Cannon1cd02472008-09-09 01:52:27 +0000609
Brett Cannonec92e182008-09-02 02:46:59 +0000610class CatchWarningTests(BaseTest):
Nick Coghlanb1304932008-07-13 12:25:08 +0000611
Brett Cannonec92e182008-09-02 02:46:59 +0000612 """Test catch_warnings()."""
613
614 def test_catch_warnings_restore(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000615 wmod = self.module
616 orig_filters = wmod.filters
617 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000618 # Ensure both showwarning and filters are restored when recording
619 with wmod.catch_warnings(module=wmod, record=True):
Nick Coghlanb1304932008-07-13 12:25:08 +0000620 wmod.filters = wmod.showwarning = object()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000621 self.assertTrue(wmod.filters is orig_filters)
622 self.assertTrue(wmod.showwarning is orig_showwarning)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000623 # Same test, but with recording disabled
624 with wmod.catch_warnings(module=wmod, record=False):
Nick Coghlanb1304932008-07-13 12:25:08 +0000625 wmod.filters = wmod.showwarning = object()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000626 self.assertTrue(wmod.filters is orig_filters)
627 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000628
Brett Cannonec92e182008-09-02 02:46:59 +0000629 def test_catch_warnings_recording(self):
Nick Coghlanb1304932008-07-13 12:25:08 +0000630 wmod = self.module
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000631 # Ensure warnings are recorded when requested
632 with wmod.catch_warnings(module=wmod, record=True) as w:
Brett Cannonec92e182008-09-02 02:46:59 +0000633 self.assertEqual(w, [])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000634 self.assertTrue(type(w) is list)
Nick Coghlanb1304932008-07-13 12:25:08 +0000635 wmod.simplefilter("always")
636 wmod.warn("foo")
Brett Cannon1cd02472008-09-09 01:52:27 +0000637 self.assertEqual(str(w[-1].message), "foo")
Nick Coghlanb1304932008-07-13 12:25:08 +0000638 wmod.warn("bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000639 self.assertEqual(str(w[-1].message), "bar")
Brett Cannonec92e182008-09-02 02:46:59 +0000640 self.assertEqual(str(w[0].message), "foo")
641 self.assertEqual(str(w[1].message), "bar")
Brett Cannon1cd02472008-09-09 01:52:27 +0000642 del w[:]
Brett Cannonec92e182008-09-02 02:46:59 +0000643 self.assertEqual(w, [])
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000644 # Ensure warnings are not recorded when not requested
Nick Coghlanb1304932008-07-13 12:25:08 +0000645 orig_showwarning = wmod.showwarning
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000646 with wmod.catch_warnings(module=wmod, record=False) as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000647 self.assertTrue(w is None)
648 self.assertTrue(wmod.showwarning is orig_showwarning)
Nick Coghlanb1304932008-07-13 12:25:08 +0000649
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000650 def test_catch_warnings_reentry_guard(self):
651 wmod = self.module
652 # Ensure catch_warnings is protected against incorrect usage
653 x = wmod.catch_warnings(module=wmod, record=True)
654 self.assertRaises(RuntimeError, x.__exit__)
655 with x:
656 self.assertRaises(RuntimeError, x.__enter__)
657 # Same test, but with recording disabled
658 x = wmod.catch_warnings(module=wmod, record=False)
659 self.assertRaises(RuntimeError, x.__exit__)
660 with x:
661 self.assertRaises(RuntimeError, x.__enter__)
662
663 def test_catch_warnings_defaults(self):
664 wmod = self.module
665 orig_filters = wmod.filters
666 orig_showwarning = wmod.showwarning
667 # Ensure default behaviour is not to record warnings
668 with wmod.catch_warnings(module=wmod) as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000669 self.assertTrue(w is None)
670 self.assertTrue(wmod.showwarning is orig_showwarning)
671 self.assertTrue(wmod.filters is not orig_filters)
672 self.assertTrue(wmod.filters is orig_filters)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000673 if wmod is sys.modules['warnings']:
674 # Ensure the default module is this one
675 with wmod.catch_warnings() as w:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000676 self.assertTrue(w is None)
677 self.assertTrue(wmod.showwarning is orig_showwarning)
678 self.assertTrue(wmod.filters is not orig_filters)
679 self.assertTrue(wmod.filters is orig_filters)
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000680
681 def test_check_warnings(self):
682 # Explicit tests for the test.support convenience wrapper
683 wmod = self.module
Florent Xicluna53b506be2010-03-18 20:00:57 +0000684 if wmod is not sys.modules['warnings']:
Zachary Ware9fe6d862013-12-08 00:20:35 -0600685 self.skipTest('module to test is not loaded warnings module')
Florent Xicluna53b506be2010-03-18 20:00:57 +0000686 with support.check_warnings(quiet=False) as w:
687 self.assertEqual(w.warnings, [])
688 wmod.simplefilter("always")
689 wmod.warn("foo")
690 self.assertEqual(str(w.message), "foo")
691 wmod.warn("bar")
692 self.assertEqual(str(w.message), "bar")
693 self.assertEqual(str(w.warnings[0].message), "foo")
694 self.assertEqual(str(w.warnings[1].message), "bar")
695 w.reset()
696 self.assertEqual(w.warnings, [])
697
698 with support.check_warnings():
699 # defaults to quiet=True without argument
700 pass
701 with support.check_warnings(('foo', UserWarning)):
702 wmod.warn("foo")
703
704 with self.assertRaises(AssertionError):
705 with support.check_warnings(('', RuntimeWarning)):
706 # defaults to quiet=False with argument
707 pass
708 with self.assertRaises(AssertionError):
709 with support.check_warnings(('foo', RuntimeWarning)):
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000710 wmod.warn("foo")
Benjamin Petersonfcf5d632008-10-16 23:24:44 +0000711
Ezio Melotti2688e812013-01-10 06:52:23 +0200712class CCatchWarningTests(CatchWarningTests, unittest.TestCase):
Nick Coghlanb1304932008-07-13 12:25:08 +0000713 module = c_warnings
714
Ezio Melotti2688e812013-01-10 06:52:23 +0200715class PyCatchWarningTests(CatchWarningTests, unittest.TestCase):
Nick Coghlanb1304932008-07-13 12:25:08 +0000716 module = py_warnings
717
Christian Heimes5fb7c2a2007-12-24 08:52:31 +0000718
Philip Jenvey0805ca32010-04-07 04:04:10 +0000719class EnvironmentVariableTests(BaseTest):
720
721 def test_single_warning(self):
722 newenv = os.environ.copy()
723 newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
724 p = subprocess.Popen([sys.executable,
725 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
726 stdout=subprocess.PIPE, env=newenv)
Benjamin Petersonad6139a2010-04-11 21:16:33 +0000727 self.assertEqual(p.communicate()[0], b"['ignore::DeprecationWarning']")
728 self.assertEqual(p.wait(), 0)
Philip Jenvey0805ca32010-04-07 04:04:10 +0000729
730 def test_comma_separated_warnings(self):
731 newenv = os.environ.copy()
732 newenv["PYTHONWARNINGS"] = ("ignore::DeprecationWarning,"
733 "ignore::UnicodeWarning")
734 p = subprocess.Popen([sys.executable,
735 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
736 stdout=subprocess.PIPE, env=newenv)
Benjamin Petersonad6139a2010-04-11 21:16:33 +0000737 self.assertEqual(p.communicate()[0],
Philip Jenvey0805ca32010-04-07 04:04:10 +0000738 b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
Benjamin Petersonad6139a2010-04-11 21:16:33 +0000739 self.assertEqual(p.wait(), 0)
Philip Jenvey0805ca32010-04-07 04:04:10 +0000740
741 def test_envvar_and_command_line(self):
742 newenv = os.environ.copy()
743 newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
744 p = subprocess.Popen([sys.executable, "-W" "ignore::UnicodeWarning",
745 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
746 stdout=subprocess.PIPE, env=newenv)
Benjamin Petersonad6139a2010-04-11 21:16:33 +0000747 self.assertEqual(p.communicate()[0],
Philip Jenvey0805ca32010-04-07 04:04:10 +0000748 b"['ignore::UnicodeWarning', 'ignore::DeprecationWarning']")
Benjamin Petersonad6139a2010-04-11 21:16:33 +0000749 self.assertEqual(p.wait(), 0)
Philip Jenvey0805ca32010-04-07 04:04:10 +0000750
Philip Jenveye53de3d2010-04-14 03:01:39 +0000751 @unittest.skipUnless(sys.getfilesystemencoding() != 'ascii',
752 'requires non-ascii filesystemencoding')
753 def test_nonascii(self):
754 newenv = os.environ.copy()
755 newenv["PYTHONWARNINGS"] = "ignore:DeprecaciónWarning"
756 newenv["PYTHONIOENCODING"] = "utf-8"
757 p = subprocess.Popen([sys.executable,
758 "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
759 stdout=subprocess.PIPE, env=newenv)
760 self.assertEqual(p.communicate()[0],
761 "['ignore:DeprecaciónWarning']".encode('utf-8'))
762 self.assertEqual(p.wait(), 0)
763
Ezio Melotti2688e812013-01-10 06:52:23 +0200764class CEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
Philip Jenvey0805ca32010-04-07 04:04:10 +0000765 module = c_warnings
766
Ezio Melotti2688e812013-01-10 06:52:23 +0200767class PyEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase):
Philip Jenvey0805ca32010-04-07 04:04:10 +0000768 module = py_warnings
769
770
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000771class BootstrapTest(unittest.TestCase):
772 def test_issue_8766(self):
773 # "import encodings" emits a warning whereas the warnings is not loaded
Ezio Melotti42da6632011-03-15 05:18:48 +0200774 # or not completely loaded (warnings imports indirectly encodings by
Victor Stinner7d79b8b2010-05-19 20:40:50 +0000775 # importing linecache) yet
776 with support.temp_cwd() as cwd, support.temp_cwd('encodings'):
777 env = os.environ.copy()
778 env['PYTHONPATH'] = cwd
779
780 # encodings loaded by initfsencoding()
781 retcode = subprocess.call([sys.executable, '-c', 'pass'], env=env)
782 self.assertEqual(retcode, 0)
783
784 # Use -W to load warnings module at startup
785 retcode = subprocess.call(
786 [sys.executable, '-c', 'pass', '-W', 'always'],
787 env=env)
788 self.assertEqual(retcode, 0)
789
Ezio Melotti2688e812013-01-10 06:52:23 +0200790
791def setUpModule():
Christian Heimesdae2a892008-04-19 00:55:37 +0000792 py_warnings.onceregistry.clear()
793 c_warnings.onceregistry.clear()
Christian Heimes33fe8092008-04-13 13:53:33 +0000794
Ezio Melotti2688e812013-01-10 06:52:23 +0200795tearDownModule = setUpModule
Raymond Hettingerd6f6e502003-07-13 08:37:40 +0000796
797if __name__ == "__main__":
Ezio Melotti2688e812013-01-10 06:52:23 +0200798 unittest.main()