test_asyncassertions.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Tests for async assertions provided by C{twisted.trial.unittest.TestCase}.
  5. """
  6. from __future__ import division, absolute_import
  7. import unittest as pyunit
  8. from twisted.python import failure
  9. from twisted.internet import defer
  10. from twisted.trial import unittest
  11. class AsynchronousAssertionsTests(unittest.TestCase):
  12. """
  13. Tests for L{TestCase}'s asynchronous extensions to L{SynchronousTestCase}.
  14. That is, assertFailure.
  15. """
  16. def test_assertFailure(self):
  17. d = defer.maybeDeferred(lambda: 1/0)
  18. return self.assertFailure(d, ZeroDivisionError)
  19. def test_assertFailure_wrongException(self):
  20. d = defer.maybeDeferred(lambda: 1/0)
  21. self.assertFailure(d, OverflowError)
  22. d.addCallbacks(lambda x: self.fail('Should have failed'),
  23. lambda x: x.trap(self.failureException))
  24. return d
  25. def test_assertFailure_noException(self):
  26. d = defer.succeed(None)
  27. self.assertFailure(d, ZeroDivisionError)
  28. d.addCallbacks(lambda x: self.fail('Should have failed'),
  29. lambda x: x.trap(self.failureException))
  30. return d
  31. def test_assertFailure_moreInfo(self):
  32. """
  33. In the case of assertFailure failing, check that we get lots of
  34. information about the exception that was raised.
  35. """
  36. try:
  37. 1/0
  38. except ZeroDivisionError:
  39. f = failure.Failure()
  40. d = defer.fail(f)
  41. d = self.assertFailure(d, RuntimeError)
  42. d.addErrback(self._checkInfo, f)
  43. return d
  44. def _checkInfo(self, assertionFailure, f):
  45. assert assertionFailure.check(self.failureException)
  46. output = assertionFailure.getErrorMessage()
  47. self.assertIn(f.getErrorMessage(), output)
  48. self.assertIn(f.getBriefTraceback(), output)
  49. def test_assertFailure_masked(self):
  50. """
  51. A single wrong assertFailure should fail the whole test.
  52. """
  53. class ExampleFailure(Exception):
  54. pass
  55. class TC(unittest.TestCase):
  56. failureException = ExampleFailure
  57. def test_assertFailure(self):
  58. d = defer.maybeDeferred(lambda: 1/0)
  59. self.assertFailure(d, OverflowError)
  60. self.assertFailure(d, ZeroDivisionError)
  61. return d
  62. test = TC('test_assertFailure')
  63. result = pyunit.TestResult()
  64. test.run(result)
  65. self.assertEqual(1, len(result.failures))