test_serialport.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Tests for L{twisted.internet.serialport}.
  5. """
  6. from twisted.trial import unittest
  7. from twisted.python.failure import Failure
  8. from twisted.internet.protocol import Protocol
  9. from twisted.internet.error import ConnectionDone
  10. try:
  11. from twisted.internet import serialport
  12. except ImportError:
  13. serialport = None
  14. class DoNothing(object):
  15. """
  16. Object with methods that do nothing.
  17. """
  18. def __init__(self, *args, **kwargs):
  19. pass
  20. def __getattr__(self, attr):
  21. return lambda *args, **kwargs: None
  22. class SerialPortTests(unittest.TestCase):
  23. """
  24. Minimal testing for Twisted's serial port support.
  25. See ticket #2462 for the eventual full test suite.
  26. """
  27. if serialport is None:
  28. skip = "Serial port support is not available."
  29. def test_connectionMadeLost(self):
  30. """
  31. C{connectionMade} and C{connectionLost} are called on the protocol by
  32. the C{SerialPort}.
  33. """
  34. # Serial port that doesn't actually connect to anything:
  35. class DummySerialPort(serialport.SerialPort):
  36. _serialFactory = DoNothing
  37. def _finishPortSetup(self):
  38. pass # override default win32 actions
  39. events = []
  40. class SerialProtocol(Protocol):
  41. def connectionMade(self):
  42. events.append("connectionMade")
  43. def connectionLost(self, reason):
  44. events.append(("connectionLost", reason))
  45. # Creation of port should result in connectionMade call:
  46. port = DummySerialPort(SerialProtocol(), "", reactor=DoNothing())
  47. self.assertEqual(events, ["connectionMade"])
  48. # Simulate reactor calling connectionLost on the SerialPort:
  49. f = Failure(ConnectionDone())
  50. port.connectionLost(f)
  51. self.assertEqual(events, ["connectionMade", ("connectionLost", f)])