]>
Commit | Line | Data |
---|---|---|
4710c53d | 1 | from contextlib import contextmanager\r |
2 | import linecache\r | |
3 | import os\r | |
4 | import StringIO\r | |
5 | import sys\r | |
6 | import unittest\r | |
7 | import subprocess\r | |
8 | from test import test_support\r | |
9 | from test.script_helper import assert_python_ok\r | |
10 | \r | |
11 | import warning_tests\r | |
12 | \r | |
13 | import warnings as original_warnings\r | |
14 | \r | |
15 | py_warnings = test_support.import_fresh_module('warnings', blocked=['_warnings'])\r | |
16 | c_warnings = test_support.import_fresh_module('warnings', fresh=['_warnings'])\r | |
17 | \r | |
18 | @contextmanager\r | |
19 | def warnings_state(module):\r | |
20 | """Use a specific warnings implementation in warning_tests."""\r | |
21 | global __warningregistry__\r | |
22 | for to_clear in (sys, warning_tests):\r | |
23 | try:\r | |
24 | to_clear.__warningregistry__.clear()\r | |
25 | except AttributeError:\r | |
26 | pass\r | |
27 | try:\r | |
28 | __warningregistry__.clear()\r | |
29 | except NameError:\r | |
30 | pass\r | |
31 | original_warnings = warning_tests.warnings\r | |
32 | original_filters = module.filters\r | |
33 | try:\r | |
34 | module.filters = original_filters[:]\r | |
35 | module.simplefilter("once")\r | |
36 | warning_tests.warnings = module\r | |
37 | yield\r | |
38 | finally:\r | |
39 | warning_tests.warnings = original_warnings\r | |
40 | module.filters = original_filters\r | |
41 | \r | |
42 | \r | |
43 | class BaseTest(unittest.TestCase):\r | |
44 | \r | |
45 | """Basic bookkeeping required for testing."""\r | |
46 | \r | |
47 | def setUp(self):\r | |
48 | # The __warningregistry__ needs to be in a pristine state for tests\r | |
49 | # to work properly.\r | |
50 | if '__warningregistry__' in globals():\r | |
51 | del globals()['__warningregistry__']\r | |
52 | if hasattr(warning_tests, '__warningregistry__'):\r | |
53 | del warning_tests.__warningregistry__\r | |
54 | if hasattr(sys, '__warningregistry__'):\r | |
55 | del sys.__warningregistry__\r | |
56 | # The 'warnings' module must be explicitly set so that the proper\r | |
57 | # interaction between _warnings and 'warnings' can be controlled.\r | |
58 | sys.modules['warnings'] = self.module\r | |
59 | super(BaseTest, self).setUp()\r | |
60 | \r | |
61 | def tearDown(self):\r | |
62 | sys.modules['warnings'] = original_warnings\r | |
63 | super(BaseTest, self).tearDown()\r | |
64 | \r | |
65 | \r | |
66 | class FilterTests(object):\r | |
67 | \r | |
68 | """Testing the filtering functionality."""\r | |
69 | \r | |
70 | def test_error(self):\r | |
71 | with original_warnings.catch_warnings(module=self.module) as w:\r | |
72 | self.module.resetwarnings()\r | |
73 | self.module.filterwarnings("error", category=UserWarning)\r | |
74 | self.assertRaises(UserWarning, self.module.warn,\r | |
75 | "FilterTests.test_error")\r | |
76 | \r | |
77 | def test_ignore(self):\r | |
78 | with original_warnings.catch_warnings(record=True,\r | |
79 | module=self.module) as w:\r | |
80 | self.module.resetwarnings()\r | |
81 | self.module.filterwarnings("ignore", category=UserWarning)\r | |
82 | self.module.warn("FilterTests.test_ignore", UserWarning)\r | |
83 | self.assertEqual(len(w), 0)\r | |
84 | \r | |
85 | def test_always(self):\r | |
86 | with original_warnings.catch_warnings(record=True,\r | |
87 | module=self.module) as w:\r | |
88 | self.module.resetwarnings()\r | |
89 | self.module.filterwarnings("always", category=UserWarning)\r | |
90 | message = "FilterTests.test_always"\r | |
91 | self.module.warn(message, UserWarning)\r | |
92 | self.assertTrue(message, w[-1].message)\r | |
93 | self.module.warn(message, UserWarning)\r | |
94 | self.assertTrue(w[-1].message, message)\r | |
95 | \r | |
96 | def test_default(self):\r | |
97 | with original_warnings.catch_warnings(record=True,\r | |
98 | module=self.module) as w:\r | |
99 | self.module.resetwarnings()\r | |
100 | self.module.filterwarnings("default", category=UserWarning)\r | |
101 | message = UserWarning("FilterTests.test_default")\r | |
102 | for x in xrange(2):\r | |
103 | self.module.warn(message, UserWarning)\r | |
104 | if x == 0:\r | |
105 | self.assertEqual(w[-1].message, message)\r | |
106 | del w[:]\r | |
107 | elif x == 1:\r | |
108 | self.assertEqual(len(w), 0)\r | |
109 | else:\r | |
110 | raise ValueError("loop variant unhandled")\r | |
111 | \r | |
112 | def test_module(self):\r | |
113 | with original_warnings.catch_warnings(record=True,\r | |
114 | module=self.module) as w:\r | |
115 | self.module.resetwarnings()\r | |
116 | self.module.filterwarnings("module", category=UserWarning)\r | |
117 | message = UserWarning("FilterTests.test_module")\r | |
118 | self.module.warn(message, UserWarning)\r | |
119 | self.assertEqual(w[-1].message, message)\r | |
120 | del w[:]\r | |
121 | self.module.warn(message, UserWarning)\r | |
122 | self.assertEqual(len(w), 0)\r | |
123 | \r | |
124 | def test_once(self):\r | |
125 | with original_warnings.catch_warnings(record=True,\r | |
126 | module=self.module) as w:\r | |
127 | self.module.resetwarnings()\r | |
128 | self.module.filterwarnings("once", category=UserWarning)\r | |
129 | message = UserWarning("FilterTests.test_once")\r | |
130 | self.module.warn_explicit(message, UserWarning, "test_warnings.py",\r | |
131 | 42)\r | |
132 | self.assertEqual(w[-1].message, message)\r | |
133 | del w[:]\r | |
134 | self.module.warn_explicit(message, UserWarning, "test_warnings.py",\r | |
135 | 13)\r | |
136 | self.assertEqual(len(w), 0)\r | |
137 | self.module.warn_explicit(message, UserWarning, "test_warnings2.py",\r | |
138 | 42)\r | |
139 | self.assertEqual(len(w), 0)\r | |
140 | \r | |
141 | def test_inheritance(self):\r | |
142 | with original_warnings.catch_warnings(module=self.module) as w:\r | |
143 | self.module.resetwarnings()\r | |
144 | self.module.filterwarnings("error", category=Warning)\r | |
145 | self.assertRaises(UserWarning, self.module.warn,\r | |
146 | "FilterTests.test_inheritance", UserWarning)\r | |
147 | \r | |
148 | def test_ordering(self):\r | |
149 | with original_warnings.catch_warnings(record=True,\r | |
150 | module=self.module) as w:\r | |
151 | self.module.resetwarnings()\r | |
152 | self.module.filterwarnings("ignore", category=UserWarning)\r | |
153 | self.module.filterwarnings("error", category=UserWarning,\r | |
154 | append=True)\r | |
155 | del w[:]\r | |
156 | try:\r | |
157 | self.module.warn("FilterTests.test_ordering", UserWarning)\r | |
158 | except UserWarning:\r | |
159 | self.fail("order handling for actions failed")\r | |
160 | self.assertEqual(len(w), 0)\r | |
161 | \r | |
162 | def test_filterwarnings(self):\r | |
163 | # Test filterwarnings().\r | |
164 | # Implicitly also tests resetwarnings().\r | |
165 | with original_warnings.catch_warnings(record=True,\r | |
166 | module=self.module) as w:\r | |
167 | self.module.filterwarnings("error", "", Warning, "", 0)\r | |
168 | self.assertRaises(UserWarning, self.module.warn, 'convert to error')\r | |
169 | \r | |
170 | self.module.resetwarnings()\r | |
171 | text = 'handle normally'\r | |
172 | self.module.warn(text)\r | |
173 | self.assertEqual(str(w[-1].message), text)\r | |
174 | self.assertTrue(w[-1].category is UserWarning)\r | |
175 | \r | |
176 | self.module.filterwarnings("ignore", "", Warning, "", 0)\r | |
177 | text = 'filtered out'\r | |
178 | self.module.warn(text)\r | |
179 | self.assertNotEqual(str(w[-1].message), text)\r | |
180 | \r | |
181 | self.module.resetwarnings()\r | |
182 | self.module.filterwarnings("error", "hex*", Warning, "", 0)\r | |
183 | self.assertRaises(UserWarning, self.module.warn, 'hex/oct')\r | |
184 | text = 'nonmatching text'\r | |
185 | self.module.warn(text)\r | |
186 | self.assertEqual(str(w[-1].message), text)\r | |
187 | self.assertTrue(w[-1].category is UserWarning)\r | |
188 | \r | |
189 | class CFilterTests(BaseTest, FilterTests):\r | |
190 | module = c_warnings\r | |
191 | \r | |
192 | class PyFilterTests(BaseTest, FilterTests):\r | |
193 | module = py_warnings\r | |
194 | \r | |
195 | \r | |
196 | class WarnTests(unittest.TestCase):\r | |
197 | \r | |
198 | """Test warnings.warn() and warnings.warn_explicit()."""\r | |
199 | \r | |
200 | def test_message(self):\r | |
201 | with original_warnings.catch_warnings(record=True,\r | |
202 | module=self.module) as w:\r | |
203 | self.module.simplefilter("once")\r | |
204 | for i in range(4):\r | |
205 | text = 'multi %d' %i # Different text on each call.\r | |
206 | self.module.warn(text)\r | |
207 | self.assertEqual(str(w[-1].message), text)\r | |
208 | self.assertTrue(w[-1].category is UserWarning)\r | |
209 | \r | |
210 | def test_filename(self):\r | |
211 | with warnings_state(self.module):\r | |
212 | with original_warnings.catch_warnings(record=True,\r | |
213 | module=self.module) as w:\r | |
214 | warning_tests.inner("spam1")\r | |
215 | self.assertEqual(os.path.basename(w[-1].filename),\r | |
216 | "warning_tests.py")\r | |
217 | warning_tests.outer("spam2")\r | |
218 | self.assertEqual(os.path.basename(w[-1].filename),\r | |
219 | "warning_tests.py")\r | |
220 | \r | |
221 | def test_stacklevel(self):\r | |
222 | # Test stacklevel argument\r | |
223 | # make sure all messages are different, so the warning won't be skipped\r | |
224 | with warnings_state(self.module):\r | |
225 | with original_warnings.catch_warnings(record=True,\r | |
226 | module=self.module) as w:\r | |
227 | warning_tests.inner("spam3", stacklevel=1)\r | |
228 | self.assertEqual(os.path.basename(w[-1].filename),\r | |
229 | "warning_tests.py")\r | |
230 | warning_tests.outer("spam4", stacklevel=1)\r | |
231 | self.assertEqual(os.path.basename(w[-1].filename),\r | |
232 | "warning_tests.py")\r | |
233 | \r | |
234 | warning_tests.inner("spam5", stacklevel=2)\r | |
235 | self.assertEqual(os.path.basename(w[-1].filename),\r | |
236 | "test_warnings.py")\r | |
237 | warning_tests.outer("spam6", stacklevel=2)\r | |
238 | self.assertEqual(os.path.basename(w[-1].filename),\r | |
239 | "warning_tests.py")\r | |
240 | warning_tests.outer("spam6.5", stacklevel=3)\r | |
241 | self.assertEqual(os.path.basename(w[-1].filename),\r | |
242 | "test_warnings.py")\r | |
243 | \r | |
244 | warning_tests.inner("spam7", stacklevel=9999)\r | |
245 | self.assertEqual(os.path.basename(w[-1].filename),\r | |
246 | "sys")\r | |
247 | \r | |
248 | def test_missing_filename_not_main(self):\r | |
249 | # If __file__ is not specified and __main__ is not the module name,\r | |
250 | # then __file__ should be set to the module name.\r | |
251 | filename = warning_tests.__file__\r | |
252 | try:\r | |
253 | del warning_tests.__file__\r | |
254 | with warnings_state(self.module):\r | |
255 | with original_warnings.catch_warnings(record=True,\r | |
256 | module=self.module) as w:\r | |
257 | warning_tests.inner("spam8", stacklevel=1)\r | |
258 | self.assertEqual(w[-1].filename, warning_tests.__name__)\r | |
259 | finally:\r | |
260 | warning_tests.__file__ = filename\r | |
261 | \r | |
262 | def test_missing_filename_main_with_argv(self):\r | |
263 | # If __file__ is not specified and the caller is __main__ and sys.argv\r | |
264 | # exists, then use sys.argv[0] as the file.\r | |
265 | if not hasattr(sys, 'argv'):\r | |
266 | return\r | |
267 | filename = warning_tests.__file__\r | |
268 | module_name = warning_tests.__name__\r | |
269 | try:\r | |
270 | del warning_tests.__file__\r | |
271 | warning_tests.__name__ = '__main__'\r | |
272 | with warnings_state(self.module):\r | |
273 | with original_warnings.catch_warnings(record=True,\r | |
274 | module=self.module) as w:\r | |
275 | warning_tests.inner('spam9', stacklevel=1)\r | |
276 | self.assertEqual(w[-1].filename, sys.argv[0])\r | |
277 | finally:\r | |
278 | warning_tests.__file__ = filename\r | |
279 | warning_tests.__name__ = module_name\r | |
280 | \r | |
281 | def test_missing_filename_main_without_argv(self):\r | |
282 | # If __file__ is not specified, the caller is __main__, and sys.argv\r | |
283 | # is not set, then '__main__' is the file name.\r | |
284 | filename = warning_tests.__file__\r | |
285 | module_name = warning_tests.__name__\r | |
286 | argv = sys.argv\r | |
287 | try:\r | |
288 | del warning_tests.__file__\r | |
289 | warning_tests.__name__ = '__main__'\r | |
290 | del sys.argv\r | |
291 | with warnings_state(self.module):\r | |
292 | with original_warnings.catch_warnings(record=True,\r | |
293 | module=self.module) as w:\r | |
294 | warning_tests.inner('spam10', stacklevel=1)\r | |
295 | self.assertEqual(w[-1].filename, '__main__')\r | |
296 | finally:\r | |
297 | warning_tests.__file__ = filename\r | |
298 | warning_tests.__name__ = module_name\r | |
299 | sys.argv = argv\r | |
300 | \r | |
301 | def test_missing_filename_main_with_argv_empty_string(self):\r | |
302 | # If __file__ is not specified, the caller is __main__, and sys.argv[0]\r | |
303 | # is the empty string, then '__main__ is the file name.\r | |
304 | # Tests issue 2743.\r | |
305 | file_name = warning_tests.__file__\r | |
306 | module_name = warning_tests.__name__\r | |
307 | argv = sys.argv\r | |
308 | try:\r | |
309 | del warning_tests.__file__\r | |
310 | warning_tests.__name__ = '__main__'\r | |
311 | sys.argv = ['']\r | |
312 | with warnings_state(self.module):\r | |
313 | with original_warnings.catch_warnings(record=True,\r | |
314 | module=self.module) as w:\r | |
315 | warning_tests.inner('spam11', stacklevel=1)\r | |
316 | self.assertEqual(w[-1].filename, '__main__')\r | |
317 | finally:\r | |
318 | warning_tests.__file__ = file_name\r | |
319 | warning_tests.__name__ = module_name\r | |
320 | sys.argv = argv\r | |
321 | \r | |
322 | def test_warn_explicit_type_errors(self):\r | |
323 | # warn_explicit() should error out gracefully if it is given objects\r | |
324 | # of the wrong types.\r | |
325 | # lineno is expected to be an integer.\r | |
326 | self.assertRaises(TypeError, self.module.warn_explicit,\r | |
327 | None, UserWarning, None, None)\r | |
328 | # Either 'message' needs to be an instance of Warning or 'category'\r | |
329 | # needs to be a subclass.\r | |
330 | self.assertRaises(TypeError, self.module.warn_explicit,\r | |
331 | None, None, None, 1)\r | |
332 | # 'registry' must be a dict or None.\r | |
333 | self.assertRaises((TypeError, AttributeError),\r | |
334 | self.module.warn_explicit,\r | |
335 | None, Warning, None, 1, registry=42)\r | |
336 | \r | |
337 | def test_bad_str(self):\r | |
338 | # issue 6415\r | |
339 | # Warnings instance with a bad format string for __str__ should not\r | |
340 | # trigger a bus error.\r | |
341 | class BadStrWarning(Warning):\r | |
342 | """Warning with a bad format string for __str__."""\r | |
343 | def __str__(self):\r | |
344 | return ("A bad formatted string %(err)" %\r | |
345 | {"err" : "there is no %(err)s"})\r | |
346 | \r | |
347 | with self.assertRaises(ValueError):\r | |
348 | self.module.warn(BadStrWarning())\r | |
349 | \r | |
350 | \r | |
351 | class CWarnTests(BaseTest, WarnTests):\r | |
352 | module = c_warnings\r | |
353 | \r | |
354 | # As an early adopter, we sanity check the\r | |
355 | # test_support.import_fresh_module utility function\r | |
356 | def test_accelerated(self):\r | |
357 | self.assertFalse(original_warnings is self.module)\r | |
358 | self.assertFalse(hasattr(self.module.warn, 'func_code'))\r | |
359 | \r | |
360 | class PyWarnTests(BaseTest, WarnTests):\r | |
361 | module = py_warnings\r | |
362 | \r | |
363 | # As an early adopter, we sanity check the\r | |
364 | # test_support.import_fresh_module utility function\r | |
365 | def test_pure_python(self):\r | |
366 | self.assertFalse(original_warnings is self.module)\r | |
367 | self.assertTrue(hasattr(self.module.warn, 'func_code'))\r | |
368 | \r | |
369 | \r | |
370 | class WCmdLineTests(unittest.TestCase):\r | |
371 | \r | |
372 | def test_improper_input(self):\r | |
373 | # Uses the private _setoption() function to test the parsing\r | |
374 | # of command-line warning arguments\r | |
375 | with original_warnings.catch_warnings(module=self.module):\r | |
376 | self.assertRaises(self.module._OptionError,\r | |
377 | self.module._setoption, '1:2:3:4:5:6')\r | |
378 | self.assertRaises(self.module._OptionError,\r | |
379 | self.module._setoption, 'bogus::Warning')\r | |
380 | self.assertRaises(self.module._OptionError,\r | |
381 | self.module._setoption, 'ignore:2::4:-5')\r | |
382 | self.module._setoption('error::Warning::0')\r | |
383 | self.assertRaises(UserWarning, self.module.warn, 'convert to error')\r | |
384 | \r | |
385 | def test_improper_option(self):\r | |
386 | # Same as above, but check that the message is printed out when\r | |
387 | # the interpreter is executed. This also checks that options are\r | |
388 | # actually parsed at all.\r | |
389 | rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")\r | |
390 | self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)\r | |
391 | \r | |
392 | def test_warnings_bootstrap(self):\r | |
393 | # Check that the warnings module does get loaded when -W<some option>\r | |
394 | # is used (see issue #10372 for an example of silent bootstrap failure).\r | |
395 | rc, out, err = assert_python_ok("-Wi", "-c",\r | |
396 | "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")\r | |
397 | # '-Wi' was observed\r | |
398 | self.assertFalse(out.strip())\r | |
399 | self.assertNotIn(b'RuntimeWarning', err)\r | |
400 | \r | |
401 | class CWCmdLineTests(BaseTest, WCmdLineTests):\r | |
402 | module = c_warnings\r | |
403 | \r | |
404 | class PyWCmdLineTests(BaseTest, WCmdLineTests):\r | |
405 | module = py_warnings\r | |
406 | \r | |
407 | \r | |
408 | class _WarningsTests(BaseTest):\r | |
409 | \r | |
410 | """Tests specific to the _warnings module."""\r | |
411 | \r | |
412 | module = c_warnings\r | |
413 | \r | |
414 | def test_filter(self):\r | |
415 | # Everything should function even if 'filters' is not in warnings.\r | |
416 | with original_warnings.catch_warnings(module=self.module) as w:\r | |
417 | self.module.filterwarnings("error", "", Warning, "", 0)\r | |
418 | self.assertRaises(UserWarning, self.module.warn,\r | |
419 | 'convert to error')\r | |
420 | del self.module.filters\r | |
421 | self.assertRaises(UserWarning, self.module.warn,\r | |
422 | 'convert to error')\r | |
423 | \r | |
424 | def test_onceregistry(self):\r | |
425 | # Replacing or removing the onceregistry should be okay.\r | |
426 | global __warningregistry__\r | |
427 | message = UserWarning('onceregistry test')\r | |
428 | try:\r | |
429 | original_registry = self.module.onceregistry\r | |
430 | __warningregistry__ = {}\r | |
431 | with original_warnings.catch_warnings(record=True,\r | |
432 | module=self.module) as w:\r | |
433 | self.module.resetwarnings()\r | |
434 | self.module.filterwarnings("once", category=UserWarning)\r | |
435 | self.module.warn_explicit(message, UserWarning, "file", 42)\r | |
436 | self.assertEqual(w[-1].message, message)\r | |
437 | del w[:]\r | |
438 | self.module.warn_explicit(message, UserWarning, "file", 42)\r | |
439 | self.assertEqual(len(w), 0)\r | |
440 | # Test the resetting of onceregistry.\r | |
441 | self.module.onceregistry = {}\r | |
442 | __warningregistry__ = {}\r | |
443 | self.module.warn('onceregistry test')\r | |
444 | self.assertEqual(w[-1].message.args, message.args)\r | |
445 | # Removal of onceregistry is okay.\r | |
446 | del w[:]\r | |
447 | del self.module.onceregistry\r | |
448 | __warningregistry__ = {}\r | |
449 | self.module.warn_explicit(message, UserWarning, "file", 42)\r | |
450 | self.assertEqual(len(w), 0)\r | |
451 | finally:\r | |
452 | self.module.onceregistry = original_registry\r | |
453 | \r | |
454 | def test_default_action(self):\r | |
455 | # Replacing or removing defaultaction should be okay.\r | |
456 | message = UserWarning("defaultaction test")\r | |
457 | original = self.module.defaultaction\r | |
458 | try:\r | |
459 | with original_warnings.catch_warnings(record=True,\r | |
460 | module=self.module) as w:\r | |
461 | self.module.resetwarnings()\r | |
462 | registry = {}\r | |
463 | self.module.warn_explicit(message, UserWarning, "<test>", 42,\r | |
464 | registry=registry)\r | |
465 | self.assertEqual(w[-1].message, message)\r | |
466 | self.assertEqual(len(w), 1)\r | |
467 | self.assertEqual(len(registry), 1)\r | |
468 | del w[:]\r | |
469 | # Test removal.\r | |
470 | del self.module.defaultaction\r | |
471 | __warningregistry__ = {}\r | |
472 | registry = {}\r | |
473 | self.module.warn_explicit(message, UserWarning, "<test>", 43,\r | |
474 | registry=registry)\r | |
475 | self.assertEqual(w[-1].message, message)\r | |
476 | self.assertEqual(len(w), 1)\r | |
477 | self.assertEqual(len(registry), 1)\r | |
478 | del w[:]\r | |
479 | # Test setting.\r | |
480 | self.module.defaultaction = "ignore"\r | |
481 | __warningregistry__ = {}\r | |
482 | registry = {}\r | |
483 | self.module.warn_explicit(message, UserWarning, "<test>", 44,\r | |
484 | registry=registry)\r | |
485 | self.assertEqual(len(w), 0)\r | |
486 | finally:\r | |
487 | self.module.defaultaction = original\r | |
488 | \r | |
489 | def test_showwarning_missing(self):\r | |
490 | # Test that showwarning() missing is okay.\r | |
491 | text = 'del showwarning test'\r | |
492 | with original_warnings.catch_warnings(module=self.module):\r | |
493 | self.module.filterwarnings("always", category=UserWarning)\r | |
494 | del self.module.showwarning\r | |
495 | with test_support.captured_output('stderr') as stream:\r | |
496 | self.module.warn(text)\r | |
497 | result = stream.getvalue()\r | |
498 | self.assertIn(text, result)\r | |
499 | \r | |
500 | def test_showwarning_not_callable(self):\r | |
501 | with original_warnings.catch_warnings(module=self.module):\r | |
502 | self.module.filterwarnings("always", category=UserWarning)\r | |
503 | old_showwarning = self.module.showwarning\r | |
504 | self.module.showwarning = 23\r | |
505 | try:\r | |
506 | self.assertRaises(TypeError, self.module.warn, "Warning!")\r | |
507 | finally:\r | |
508 | self.module.showwarning = old_showwarning\r | |
509 | \r | |
510 | def test_show_warning_output(self):\r | |
511 | # With showarning() missing, make sure that output is okay.\r | |
512 | text = 'test show_warning'\r | |
513 | with original_warnings.catch_warnings(module=self.module):\r | |
514 | self.module.filterwarnings("always", category=UserWarning)\r | |
515 | del self.module.showwarning\r | |
516 | with test_support.captured_output('stderr') as stream:\r | |
517 | warning_tests.inner(text)\r | |
518 | result = stream.getvalue()\r | |
519 | self.assertEqual(result.count('\n'), 2,\r | |
520 | "Too many newlines in %r" % result)\r | |
521 | first_line, second_line = result.split('\n', 1)\r | |
522 | expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'\r | |
523 | first_line_parts = first_line.rsplit(':', 3)\r | |
524 | path, line, warning_class, message = first_line_parts\r | |
525 | line = int(line)\r | |
526 | self.assertEqual(expected_file, path)\r | |
527 | self.assertEqual(warning_class, ' ' + UserWarning.__name__)\r | |
528 | self.assertEqual(message, ' ' + text)\r | |
529 | expected_line = ' ' + linecache.getline(path, line).strip() + '\n'\r | |
530 | assert expected_line\r | |
531 | self.assertEqual(second_line, expected_line)\r | |
532 | \r | |
533 | \r | |
534 | class WarningsDisplayTests(unittest.TestCase):\r | |
535 | \r | |
536 | """Test the displaying of warnings and the ability to overload functions\r | |
537 | related to displaying warnings."""\r | |
538 | \r | |
539 | def test_formatwarning(self):\r | |
540 | message = "msg"\r | |
541 | category = Warning\r | |
542 | file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'\r | |
543 | line_num = 3\r | |
544 | file_line = linecache.getline(file_name, line_num).strip()\r | |
545 | format = "%s:%s: %s: %s\n %s\n"\r | |
546 | expect = format % (file_name, line_num, category.__name__, message,\r | |
547 | file_line)\r | |
548 | self.assertEqual(expect, self.module.formatwarning(message,\r | |
549 | category, file_name, line_num))\r | |
550 | # Test the 'line' argument.\r | |
551 | file_line += " for the win!"\r | |
552 | expect = format % (file_name, line_num, category.__name__, message,\r | |
553 | file_line)\r | |
554 | self.assertEqual(expect, self.module.formatwarning(message,\r | |
555 | category, file_name, line_num, file_line))\r | |
556 | \r | |
557 | def test_showwarning(self):\r | |
558 | file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'\r | |
559 | line_num = 3\r | |
560 | expected_file_line = linecache.getline(file_name, line_num).strip()\r | |
561 | message = 'msg'\r | |
562 | category = Warning\r | |
563 | file_object = StringIO.StringIO()\r | |
564 | expect = self.module.formatwarning(message, category, file_name,\r | |
565 | line_num)\r | |
566 | self.module.showwarning(message, category, file_name, line_num,\r | |
567 | file_object)\r | |
568 | self.assertEqual(file_object.getvalue(), expect)\r | |
569 | # Test 'line' argument.\r | |
570 | expected_file_line += "for the win!"\r | |
571 | expect = self.module.formatwarning(message, category, file_name,\r | |
572 | line_num, expected_file_line)\r | |
573 | file_object = StringIO.StringIO()\r | |
574 | self.module.showwarning(message, category, file_name, line_num,\r | |
575 | file_object, expected_file_line)\r | |
576 | self.assertEqual(expect, file_object.getvalue())\r | |
577 | \r | |
578 | class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):\r | |
579 | module = c_warnings\r | |
580 | \r | |
581 | class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):\r | |
582 | module = py_warnings\r | |
583 | \r | |
584 | \r | |
585 | class CatchWarningTests(BaseTest):\r | |
586 | \r | |
587 | """Test catch_warnings()."""\r | |
588 | \r | |
589 | def test_catch_warnings_restore(self):\r | |
590 | wmod = self.module\r | |
591 | orig_filters = wmod.filters\r | |
592 | orig_showwarning = wmod.showwarning\r | |
593 | # Ensure both showwarning and filters are restored when recording\r | |
594 | with wmod.catch_warnings(module=wmod, record=True):\r | |
595 | wmod.filters = wmod.showwarning = object()\r | |
596 | self.assertTrue(wmod.filters is orig_filters)\r | |
597 | self.assertTrue(wmod.showwarning is orig_showwarning)\r | |
598 | # Same test, but with recording disabled\r | |
599 | with wmod.catch_warnings(module=wmod, record=False):\r | |
600 | wmod.filters = wmod.showwarning = object()\r | |
601 | self.assertTrue(wmod.filters is orig_filters)\r | |
602 | self.assertTrue(wmod.showwarning is orig_showwarning)\r | |
603 | \r | |
604 | def test_catch_warnings_recording(self):\r | |
605 | wmod = self.module\r | |
606 | # Ensure warnings are recorded when requested\r | |
607 | with wmod.catch_warnings(module=wmod, record=True) as w:\r | |
608 | self.assertEqual(w, [])\r | |
609 | self.assertTrue(type(w) is list)\r | |
610 | wmod.simplefilter("always")\r | |
611 | wmod.warn("foo")\r | |
612 | self.assertEqual(str(w[-1].message), "foo")\r | |
613 | wmod.warn("bar")\r | |
614 | self.assertEqual(str(w[-1].message), "bar")\r | |
615 | self.assertEqual(str(w[0].message), "foo")\r | |
616 | self.assertEqual(str(w[1].message), "bar")\r | |
617 | del w[:]\r | |
618 | self.assertEqual(w, [])\r | |
619 | # Ensure warnings are not recorded when not requested\r | |
620 | orig_showwarning = wmod.showwarning\r | |
621 | with wmod.catch_warnings(module=wmod, record=False) as w:\r | |
622 | self.assertTrue(w is None)\r | |
623 | self.assertTrue(wmod.showwarning is orig_showwarning)\r | |
624 | \r | |
625 | def test_catch_warnings_reentry_guard(self):\r | |
626 | wmod = self.module\r | |
627 | # Ensure catch_warnings is protected against incorrect usage\r | |
628 | x = wmod.catch_warnings(module=wmod, record=True)\r | |
629 | self.assertRaises(RuntimeError, x.__exit__)\r | |
630 | with x:\r | |
631 | self.assertRaises(RuntimeError, x.__enter__)\r | |
632 | # Same test, but with recording disabled\r | |
633 | x = wmod.catch_warnings(module=wmod, record=False)\r | |
634 | self.assertRaises(RuntimeError, x.__exit__)\r | |
635 | with x:\r | |
636 | self.assertRaises(RuntimeError, x.__enter__)\r | |
637 | \r | |
638 | def test_catch_warnings_defaults(self):\r | |
639 | wmod = self.module\r | |
640 | orig_filters = wmod.filters\r | |
641 | orig_showwarning = wmod.showwarning\r | |
642 | # Ensure default behaviour is not to record warnings\r | |
643 | with wmod.catch_warnings(module=wmod) as w:\r | |
644 | self.assertTrue(w is None)\r | |
645 | self.assertTrue(wmod.showwarning is orig_showwarning)\r | |
646 | self.assertTrue(wmod.filters is not orig_filters)\r | |
647 | self.assertTrue(wmod.filters is orig_filters)\r | |
648 | if wmod is sys.modules['warnings']:\r | |
649 | # Ensure the default module is this one\r | |
650 | with wmod.catch_warnings() as w:\r | |
651 | self.assertTrue(w is None)\r | |
652 | self.assertTrue(wmod.showwarning is orig_showwarning)\r | |
653 | self.assertTrue(wmod.filters is not orig_filters)\r | |
654 | self.assertTrue(wmod.filters is orig_filters)\r | |
655 | \r | |
656 | def test_check_warnings(self):\r | |
657 | # Explicit tests for the test_support convenience wrapper\r | |
658 | wmod = self.module\r | |
659 | if wmod is not sys.modules['warnings']:\r | |
660 | return\r | |
661 | with test_support.check_warnings(quiet=False) as w:\r | |
662 | self.assertEqual(w.warnings, [])\r | |
663 | wmod.simplefilter("always")\r | |
664 | wmod.warn("foo")\r | |
665 | self.assertEqual(str(w.message), "foo")\r | |
666 | wmod.warn("bar")\r | |
667 | self.assertEqual(str(w.message), "bar")\r | |
668 | self.assertEqual(str(w.warnings[0].message), "foo")\r | |
669 | self.assertEqual(str(w.warnings[1].message), "bar")\r | |
670 | w.reset()\r | |
671 | self.assertEqual(w.warnings, [])\r | |
672 | \r | |
673 | with test_support.check_warnings():\r | |
674 | # defaults to quiet=True without argument\r | |
675 | pass\r | |
676 | with test_support.check_warnings(('foo', UserWarning)):\r | |
677 | wmod.warn("foo")\r | |
678 | \r | |
679 | with self.assertRaises(AssertionError):\r | |
680 | with test_support.check_warnings(('', RuntimeWarning)):\r | |
681 | # defaults to quiet=False with argument\r | |
682 | pass\r | |
683 | with self.assertRaises(AssertionError):\r | |
684 | with test_support.check_warnings(('foo', RuntimeWarning)):\r | |
685 | wmod.warn("foo")\r | |
686 | \r | |
687 | \r | |
688 | class CCatchWarningTests(CatchWarningTests):\r | |
689 | module = c_warnings\r | |
690 | \r | |
691 | class PyCatchWarningTests(CatchWarningTests):\r | |
692 | module = py_warnings\r | |
693 | \r | |
694 | \r | |
695 | class EnvironmentVariableTests(BaseTest):\r | |
696 | \r | |
697 | def test_single_warning(self):\r | |
698 | newenv = os.environ.copy()\r | |
699 | newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"\r | |
700 | p = subprocess.Popen([sys.executable,\r | |
701 | "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],\r | |
702 | stdout=subprocess.PIPE, env=newenv)\r | |
703 | self.assertEqual(p.communicate()[0], "['ignore::DeprecationWarning']")\r | |
704 | self.assertEqual(p.wait(), 0)\r | |
705 | \r | |
706 | def test_comma_separated_warnings(self):\r | |
707 | newenv = os.environ.copy()\r | |
708 | newenv["PYTHONWARNINGS"] = ("ignore::DeprecationWarning,"\r | |
709 | "ignore::UnicodeWarning")\r | |
710 | p = subprocess.Popen([sys.executable,\r | |
711 | "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],\r | |
712 | stdout=subprocess.PIPE, env=newenv)\r | |
713 | self.assertEqual(p.communicate()[0],\r | |
714 | "['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")\r | |
715 | self.assertEqual(p.wait(), 0)\r | |
716 | \r | |
717 | def test_envvar_and_command_line(self):\r | |
718 | newenv = os.environ.copy()\r | |
719 | newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"\r | |
720 | p = subprocess.Popen([sys.executable, "-W" "ignore::UnicodeWarning",\r | |
721 | "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],\r | |
722 | stdout=subprocess.PIPE, env=newenv)\r | |
723 | self.assertEqual(p.communicate()[0],\r | |
724 | "['ignore::UnicodeWarning', 'ignore::DeprecationWarning']")\r | |
725 | self.assertEqual(p.wait(), 0)\r | |
726 | \r | |
727 | class CEnvironmentVariableTests(EnvironmentVariableTests):\r | |
728 | module = c_warnings\r | |
729 | \r | |
730 | class PyEnvironmentVariableTests(EnvironmentVariableTests):\r | |
731 | module = py_warnings\r | |
732 | \r | |
733 | \r | |
734 | def test_main():\r | |
735 | py_warnings.onceregistry.clear()\r | |
736 | c_warnings.onceregistry.clear()\r | |
737 | test_support.run_unittest(CFilterTests, PyFilterTests,\r | |
738 | CWarnTests, PyWarnTests,\r | |
739 | CWCmdLineTests, PyWCmdLineTests,\r | |
740 | _WarningsTests,\r | |
741 | CWarningsDisplayTests, PyWarningsDisplayTests,\r | |
742 | CCatchWarningTests, PyCatchWarningTests,\r | |
743 | CEnvironmentVariableTests,\r | |
744 | PyEnvironmentVariableTests\r | |
745 | )\r | |
746 | \r | |
747 | \r | |
748 | if __name__ == "__main__":\r | |
749 | test_main()\r |