stdio_test_halfclose.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # -*- test-case-name: twisted.test.test_stdio.StandardInputOutputTests.test_readConnectionLost -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Main program for the child process run by
  6. L{twisted.test.test_stdio.StandardInputOutputTests.test_readConnectionLost}
  7. to test that IHalfCloseableProtocol.readConnectionLost works for process
  8. transports.
  9. """
  10. from __future__ import absolute_import, division
  11. import sys
  12. from zope.interface import implementer
  13. from twisted.internet.interfaces import IHalfCloseableProtocol
  14. from twisted.internet import stdio, protocol
  15. from twisted.python import reflect, log
  16. @implementer(IHalfCloseableProtocol)
  17. class HalfCloseProtocol(protocol.Protocol):
  18. """
  19. A protocol to hook up to stdio and observe its transport being
  20. half-closed. If all goes as expected, C{exitCode} will be set to C{0};
  21. otherwise it will be set to C{1} to indicate failure.
  22. """
  23. exitCode = None
  24. def connectionMade(self):
  25. """
  26. Signal the parent process that we're ready.
  27. """
  28. self.transport.write(b"x")
  29. def readConnectionLost(self):
  30. """
  31. This is the desired event. Once it has happened, stop the reactor so
  32. the process will exit.
  33. """
  34. self.exitCode = 0
  35. reactor.stop()
  36. def connectionLost(self, reason):
  37. """
  38. This may only be invoked after C{readConnectionLost}. If it happens
  39. otherwise, mark it as an error and shut down.
  40. """
  41. if self.exitCode is None:
  42. self.exitCode = 1
  43. log.err(reason, "Unexpected call to connectionLost")
  44. reactor.stop()
  45. if __name__ == '__main__':
  46. reflect.namedAny(sys.argv[1]).install()
  47. log.startLogging(open(sys.argv[2], 'wb'))
  48. from twisted.internet import reactor
  49. protocol = HalfCloseProtocol()
  50. stdio.StandardIO(protocol)
  51. reactor.run()
  52. sys.exit(protocol.exitCode)