PageRenderTime 86ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/modified-2.7/test/test_warnings.py

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