test_exit.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Tests for L{twisted.application.runner._exit}.
  5. """
  6. from twisted.python.compat import NativeStringIO
  7. from ...runner import _exit
  8. from .._exit import exit, ExitStatus
  9. import twisted.trial.unittest
  10. class ExitTests(twisted.trial.unittest.TestCase):
  11. """
  12. Tests for L{exit}.
  13. """
  14. def setUp(self):
  15. self.exit = DummyExit()
  16. self.patch(_exit, "sysexit", self.exit)
  17. def test_exitStatusInt(self):
  18. """
  19. L{exit} given an L{int} status code will pass it to L{sys.exit}.
  20. """
  21. status = 1234
  22. exit(status)
  23. self.assertEqual(self.exit.arg, status)
  24. def test_exitStatusStringNotInt(self):
  25. """
  26. L{exit} given a L{str} status code that isn't a string integer raises
  27. L{ValueError}.
  28. """
  29. self.assertRaises(ValueError, exit, "foo")
  30. def test_exitStatusStringInt(self):
  31. """
  32. L{exit} given a L{str} status code that is a string integer passes the
  33. corresponding L{int} to L{sys.exit}.
  34. """
  35. exit("1234")
  36. self.assertEqual(self.exit.arg, 1234)
  37. def test_exitConstant(self):
  38. """
  39. L{exit} given a L{ValueConstant} status code passes the corresponding
  40. value to L{sys.exit}.
  41. """
  42. status = ExitStatus.EX_CONFIG
  43. exit(status)
  44. self.assertEqual(self.exit.arg, status.value)
  45. def test_exitMessageZero(self):
  46. """
  47. L{exit} given a status code of zero (C{0}) writes the given message to
  48. standard output.
  49. """
  50. out = NativeStringIO()
  51. self.patch(_exit, "stdout", out)
  52. message = "Hello, world."
  53. exit(0, message)
  54. self.assertEqual(out.getvalue(), message + "\n")
  55. def test_exitMessageNonZero(self):
  56. """
  57. L{exit} given a non-zero status code writes the given message to
  58. standard error.
  59. """
  60. out = NativeStringIO()
  61. self.patch(_exit, "stderr", out)
  62. message = "Hello, world."
  63. exit(64, message)
  64. self.assertEqual(out.getvalue(), message + "\n")
  65. class DummyExit(object):
  66. """
  67. Stub for L{sys.exit} that remembers whether it's been called and, if it
  68. has, what argument it was given.
  69. """
  70. def __init__(self):
  71. self.exited = False
  72. def __call__(self, arg=None):
  73. assert not self.exited
  74. self.arg = arg
  75. self.exited = True