/Lib/test/test_warnings.py

http://unladen-swallow.googlecode.com/ · Python · 670 lines · 519 code · 95 blank · 56 comment · 74 complexity · 4e5cf5d9c6c69eeeaf6f531be3be1151 MD5 · raw file

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