PageRenderTime 46ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/dac_io/pypy
Python | 749 lines | 719 code | 21 blank | 9 comment | 26 complexity | ed515fee44b4b8ed376ea8deda70052e 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'))
  315. class PyWarnTests(BaseTest, WarnTests):
  316. module = py_warnings
  317. # As an early adopter, we sanity check the
  318. # test_support.import_fresh_module utility function
  319. def test_pure_python(self):
  320. self.assertFalse(original_warnings is self.module)
  321. self.assertTrue(hasattr(self.module.warn, 'func_code'))
  322. class WCmdLineTests(unittest.TestCase):
  323. def test_improper_input(self):
  324. # Uses the private _setoption() function to test the parsing
  325. # of command-line warning arguments
  326. with original_warnings.catch_warnings(module=self.module):
  327. self.assertRaises(self.module._OptionError,
  328. self.module._setoption, '1:2:3:4:5:6')
  329. self.assertRaises(self.module._OptionError,
  330. self.module._setoption, 'bogus::Warning')
  331. self.assertRaises(self.module._OptionError,
  332. self.module._setoption, 'ignore:2::4:-5')
  333. self.module._setoption('error::Warning::0')
  334. self.assertRaises(UserWarning, self.module.warn, 'convert to error')
  335. def test_improper_option(self):
  336. # Same as above, but check that the message is printed out when
  337. # the interpreter is executed. This also checks that options are
  338. # actually parsed at all.
  339. rc, out, err = assert_python_ok("-Wxxx", "-c", "pass")
  340. self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err)
  341. def test_warnings_bootstrap(self):
  342. # Check that the warnings module does get loaded when -W<some option>
  343. # is used (see issue #10372 for an example of silent bootstrap failure).
  344. rc, out, err = assert_python_ok("-Wi", "-c",
  345. "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)")
  346. # '-Wi' was observed
  347. self.assertFalse(out.strip())
  348. self.assertNotIn(b'RuntimeWarning', err)
  349. class CWCmdLineTests(BaseTest, WCmdLineTests):
  350. module = c_warnings
  351. class PyWCmdLineTests(BaseTest, WCmdLineTests):
  352. module = py_warnings
  353. class _WarningsTests(BaseTest):
  354. """Tests specific to the _warnings module."""
  355. module = c_warnings
  356. def test_filter(self):
  357. # Everything should function even if 'filters' is not in warnings.
  358. with original_warnings.catch_warnings(module=self.module) as w:
  359. self.module.filterwarnings("error", "", Warning, "", 0)
  360. self.assertRaises(UserWarning, self.module.warn,
  361. 'convert to error')
  362. del self.module.filters
  363. self.assertRaises(UserWarning, self.module.warn,
  364. 'convert to error')
  365. def test_onceregistry(self):
  366. # Replacing or removing the onceregistry should be okay.
  367. global __warningregistry__
  368. message = UserWarning('onceregistry test')
  369. try:
  370. original_registry = self.module.onceregistry
  371. __warningregistry__ = {}
  372. with original_warnings.catch_warnings(record=True,
  373. module=self.module) as w:
  374. self.module.resetwarnings()
  375. self.module.filterwarnings("once", category=UserWarning)
  376. self.module.warn_explicit(message, UserWarning, "file", 42)
  377. self.assertEqual(w[-1].message, message)
  378. del w[:]
  379. self.module.warn_explicit(message, UserWarning, "file", 42)
  380. self.assertEqual(len(w), 0)
  381. # Test the resetting of onceregistry.
  382. self.module.onceregistry = {}
  383. __warningregistry__ = {}
  384. self.module.warn('onceregistry test')
  385. self.assertEqual(w[-1].message.args, message.args)
  386. # Removal of onceregistry is okay.
  387. del w[:]
  388. del self.module.onceregistry
  389. __warningregistry__ = {}
  390. self.module.warn_explicit(message, UserWarning, "file", 42)
  391. self.assertEqual(len(w), 0)
  392. finally:
  393. self.module.onceregistry = original_registry
  394. def test_default_action(self):
  395. # Replacing or removing defaultaction should be okay.
  396. message = UserWarning("defaultaction test")
  397. original = self.module.defaultaction
  398. try:
  399. with original_warnings.catch_warnings(record=True,
  400. module=self.module) as w:
  401. self.module.resetwarnings()
  402. registry = {}
  403. self.module.warn_explicit(message, UserWarning, "<test>", 42,
  404. registry=registry)
  405. self.assertEqual(w[-1].message, message)
  406. self.assertEqual(len(w), 1)
  407. self.assertEqual(len(registry), 1)
  408. del w[:]
  409. # Test removal.
  410. del self.module.defaultaction
  411. __warningregistry__ = {}
  412. registry = {}
  413. self.module.warn_explicit(message, UserWarning, "<test>", 43,
  414. registry=registry)
  415. self.assertEqual(w[-1].message, message)
  416. self.assertEqual(len(w), 1)
  417. self.assertEqual(len(registry), 1)
  418. del w[:]
  419. # Test setting.
  420. self.module.defaultaction = "ignore"
  421. __warningregistry__ = {}
  422. registry = {}
  423. self.module.warn_explicit(message, UserWarning, "<test>", 44,
  424. registry=registry)
  425. self.assertEqual(len(w), 0)
  426. finally:
  427. self.module.defaultaction = original
  428. def test_showwarning_missing(self):
  429. # Test that showwarning() missing is okay.
  430. text = 'del showwarning test'
  431. with original_warnings.catch_warnings(module=self.module):
  432. self.module.filterwarnings("always", category=UserWarning)
  433. del self.module.showwarning
  434. with test_support.captured_output('stderr') as stream:
  435. self.module.warn(text)
  436. result = stream.getvalue()
  437. self.assertIn(text, result)
  438. def test_showwarning_not_callable(self):
  439. with original_warnings.catch_warnings(module=self.module):
  440. self.module.filterwarnings("always", category=UserWarning)
  441. old_showwarning = self.module.showwarning
  442. self.module.showwarning = 23
  443. try:
  444. self.assertRaises(TypeError, self.module.warn, "Warning!")
  445. finally:
  446. self.module.showwarning = old_showwarning
  447. def test_show_warning_output(self):
  448. # With showarning() missing, make sure that output is okay.
  449. text = 'test show_warning'
  450. with original_warnings.catch_warnings(module=self.module):
  451. self.module.filterwarnings("always", category=UserWarning)
  452. del self.module.showwarning
  453. with test_support.captured_output('stderr') as stream:
  454. warning_tests.inner(text)
  455. result = stream.getvalue()
  456. self.assertEqual(result.count('\n'), 2,
  457. "Too many newlines in %r" % result)
  458. first_line, second_line = result.split('\n', 1)
  459. expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
  460. first_line_parts = first_line.rsplit(':', 3)
  461. path, line, warning_class, message = first_line_parts
  462. line = int(line)
  463. self.assertEqual(expected_file, path)
  464. self.assertEqual(warning_class, ' ' + UserWarning.__name__)
  465. self.assertEqual(message, ' ' + text)
  466. expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
  467. assert expected_line
  468. self.assertEqual(second_line, expected_line)
  469. class WarningsDisplayTests(unittest.TestCase):
  470. """Test the displaying of warnings and the ability to overload functions
  471. related to displaying warnings."""
  472. def test_formatwarning(self):
  473. message = "msg"
  474. category = Warning
  475. file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
  476. line_num = 3
  477. file_line = linecache.getline(file_name, line_num).strip()
  478. format = "%s:%s: %s: %s\n %s\n"
  479. expect = format % (file_name, line_num, category.__name__, message,
  480. file_line)
  481. self.assertEqual(expect, self.module.formatwarning(message,
  482. category, file_name, line_num))
  483. # Test the 'line' argument.
  484. file_line += " for the win!"
  485. expect = format % (file_name, line_num, category.__name__, message,
  486. file_line)
  487. self.assertEqual(expect, self.module.formatwarning(message,
  488. category, file_name, line_num, file_line))
  489. def test_showwarning(self):
  490. file_name = os.path.splitext(warning_tests.__file__)[0] + '.py'
  491. line_num = 3
  492. expected_file_line = linecache.getline(file_name, line_num).strip()
  493. message = 'msg'
  494. category = Warning
  495. file_object = StringIO.StringIO()
  496. expect = self.module.formatwarning(message, category, file_name,
  497. line_num)
  498. self.module.showwarning(message, category, file_name, line_num,
  499. file_object)
  500. self.assertEqual(file_object.getvalue(), expect)
  501. # Test 'line' argument.
  502. expected_file_line += "for the win!"
  503. expect = self.module.formatwarning(message, category, file_name,
  504. line_num, expected_file_line)
  505. file_object = StringIO.StringIO()
  506. self.module.showwarning(message, category, file_name, line_num,
  507. file_object, expected_file_line)
  508. self.assertEqual(expect, file_object.getvalue())
  509. class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
  510. module = c_warnings
  511. class PyWarningsDisplayTests(BaseTest, WarningsDisplayTests):
  512. module = py_warnings
  513. class CatchWarningTests(BaseTest):
  514. """Test catch_warnings()."""
  515. def test_catch_warnings_restore(self):
  516. wmod = self.module
  517. orig_filters = wmod.filters
  518. orig_showwarning = wmod.showwarning
  519. # Ensure both showwarning and filters are restored when recording
  520. with wmod.catch_warnings(module=wmod, record=True):
  521. wmod.filters = wmod.showwarning = object()
  522. self.assertTrue(wmod.filters is orig_filters)
  523. self.assertTrue(wmod.showwarning is orig_showwarning)
  524. # Same test, but with recording disabled
  525. with wmod.catch_warnings(module=wmod, record=False):
  526. wmod.filters = wmod.showwarning = object()
  527. self.assertTrue(wmod.filters is orig_filters)
  528. self.assertTrue(wmod.showwarning is orig_showwarning)
  529. def test_catch_warnings_recording(self):
  530. wmod = self.module
  531. # Ensure warnings are recorded when requested
  532. with wmod.catch_warnings(module=wmod, record=True) as w:
  533. self.assertEqual(w, [])
  534. self.assertTrue(type(w) is list)
  535. wmod.simplefilter("always")
  536. wmod.warn("foo")
  537. self.assertEqual(str(w[-1].message), "foo")
  538. wmod.warn("bar")
  539. self.assertEqual(str(w[-1].message), "bar")
  540. self.assertEqual(str(w[0].message), "foo")
  541. self.assertEqual(str(w[1].message), "bar")
  542. del w[:]
  543. self.assertEqual(w, [])
  544. # Ensure warnings are not recorded when not requested
  545. orig_showwarning = wmod.showwarning
  546. with wmod.catch_warnings(module=wmod, record=False) as w:
  547. self.assertTrue(w is None)
  548. self.assertTrue(wmod.showwarning is orig_showwarning)
  549. def test_catch_warnings_reentry_guard(self):
  550. wmod = self.module
  551. # Ensure catch_warnings is protected against incorrect usage
  552. x = wmod.catch_warnings(module=wmod, record=True)
  553. self.assertRaises(RuntimeError, x.__exit__)
  554. with x:
  555. self.assertRaises(RuntimeError, x.__enter__)
  556. # Same test, but with recording disabled
  557. x = wmod.catch_warnings(module=wmod, record=False)
  558. self.assertRaises(RuntimeError, x.__exit__)
  559. with x:
  560. self.assertRaises(RuntimeError, x.__enter__)
  561. def test_catch_warnings_defaults(self):
  562. wmod = self.module
  563. orig_filters = wmod.filters
  564. orig_showwarning = wmod.showwarning
  565. # Ensure default behaviour is not to record warnings
  566. with wmod.catch_warnings(module=wmod) as w:
  567. self.assertTrue(w is None)
  568. self.assertTrue(wmod.showwarning is orig_showwarning)
  569. self.assertTrue(wmod.filters is not orig_filters)
  570. self.assertTrue(wmod.filters is orig_filters)
  571. if wmod is sys.modules['warnings']:
  572. # Ensure the default module is this one
  573. with wmod.catch_warnings() as w:
  574. self.assertTrue(w is None)
  575. self.assertTrue(wmod.showwarning is orig_showwarning)
  576. self.assertTrue(wmod.filters is not orig_filters)
  577. self.assertTrue(wmod.filters is orig_filters)
  578. def test_check_warnings(self):
  579. # Explicit tests for the test_support convenience wrapper
  580. wmod = self.module
  581. if wmod is not sys.modules['warnings']:
  582. return
  583. with test_support.check_warnings(quiet=False) as w:
  584. self.assertEqual(w.warnings, [])
  585. wmod.simplefilter("always")
  586. wmod.warn("foo")
  587. self.assertEqual(str(w.message), "foo")
  588. wmod.warn("bar")
  589. self.assertEqual(str(w.message), "bar")
  590. self.assertEqual(str(w.warnings[0].message), "foo")
  591. self.assertEqual(str(w.warnings[1].message), "bar")
  592. w.reset()
  593. self.assertEqual(w.warnings, [])
  594. with test_support.check_warnings():
  595. # defaults to quiet=True without argument
  596. pass
  597. with test_support.check_warnings(('foo', UserWarning)):
  598. wmod.warn("foo")
  599. with self.assertRaises(AssertionError):
  600. with test_support.check_warnings(('', RuntimeWarning)):
  601. # defaults to quiet=False with argument
  602. pass
  603. with self.assertRaises(AssertionError):
  604. with test_support.check_warnings(('foo', RuntimeWarning)):
  605. wmod.warn("foo")
  606. class CCatchWarningTests(CatchWarningTests):
  607. module = c_warnings
  608. class PyCatchWarningTests(CatchWarningTests):
  609. module = py_warnings
  610. class EnvironmentVariableTests(BaseTest):
  611. def test_single_warning(self):
  612. newenv = os.environ.copy()
  613. newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
  614. p = subprocess.Popen([sys.executable,
  615. "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
  616. stdout=subprocess.PIPE, env=newenv)
  617. self.assertEqual(p.communicate()[0], "['ignore::DeprecationWarning']")
  618. self.assertEqual(p.wait(), 0)
  619. def test_comma_separated_warnings(self):
  620. newenv = os.environ.copy()
  621. newenv["PYTHONWARNINGS"] = ("ignore::DeprecationWarning,"
  622. "ignore::UnicodeWarning")
  623. p = subprocess.Popen([sys.executable,
  624. "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
  625. stdout=subprocess.PIPE, env=newenv)
  626. self.assertEqual(p.communicate()[0],
  627. "['ignore::DeprecationWarning', 'ignore::UnicodeWarning']")
  628. self.assertEqual(p.wait(), 0)
  629. def test_envvar_and_command_line(self):
  630. newenv = os.environ.copy()
  631. newenv["PYTHONWARNINGS"] = "ignore::DeprecationWarning"
  632. p = subprocess.Popen([sys.executable, "-W" "ignore::UnicodeWarning",
  633. "-c", "import sys; sys.stdout.write(str(sys.warnoptions))"],
  634. stdout=subprocess.PIPE, env=newenv)
  635. self.assertEqual(p.communicate()[0],
  636. "['ignore::UnicodeWarning', 'ignore::DeprecationWarning']")
  637. self.assertEqual(p.wait(), 0)
  638. class CEnvironmentVariableTests(EnvironmentVariableTests):
  639. module = c_warnings
  640. class PyEnvironmentVariableTests(EnvironmentVariableTests):
  641. module = py_warnings
  642. def test_main():
  643. py_warnings.onceregistry.clear()
  644. c_warnings.onceregistry.clear()
  645. test_support.run_unittest(CFilterTests, PyFilterTests,
  646. CWarnTests, PyWarnTests,
  647. CWCmdLineTests, PyWCmdLineTests,
  648. _WarningsTests,
  649. CWarningsDisplayTests, PyWarningsDisplayTests,
  650. CCatchWarningTests, PyCatchWarningTests,
  651. CEnvironmentVariableTests,
  652. PyEnvironmentVariableTests
  653. )
  654. if __name__ == "__main__":
  655. test_main()