Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_stateful.py 2.0KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Test cases for twisted.protocols.stateful
  5. """
  6. from struct import calcsize, pack, unpack
  7. from twisted.protocols.stateful import StatefulProtocol
  8. from twisted.protocols.test import test_basic
  9. from twisted.trial.unittest import TestCase
  10. class MyInt32StringReceiver(StatefulProtocol):
  11. """
  12. A stateful Int32StringReceiver.
  13. """
  14. MAX_LENGTH = 99999
  15. structFormat = "!I"
  16. prefixLength = calcsize(structFormat)
  17. def getInitialState(self):
  18. return self._getHeader, 4
  19. def lengthLimitExceeded(self, length):
  20. self.transport.loseConnection()
  21. def _getHeader(self, msg):
  22. (length,) = unpack("!i", msg)
  23. if length > self.MAX_LENGTH:
  24. self.lengthLimitExceeded(length)
  25. return
  26. return self._getString, length
  27. def _getString(self, msg):
  28. self.stringReceived(msg)
  29. return self._getHeader, 4
  30. def stringReceived(self, msg):
  31. """
  32. Override this.
  33. """
  34. raise NotImplementedError
  35. def sendString(self, data):
  36. """
  37. Send an int32-prefixed string to the other end of the connection.
  38. """
  39. self.transport.write(pack(self.structFormat, len(data)) + data)
  40. class TestInt32(MyInt32StringReceiver):
  41. def connectionMade(self):
  42. self.received = []
  43. def stringReceived(self, s):
  44. self.received.append(s)
  45. MAX_LENGTH = 50
  46. closed = 0
  47. def connectionLost(self, reason):
  48. self.closed = 1
  49. class Int32Tests(TestCase, test_basic.IntNTestCaseMixin):
  50. protocol = TestInt32
  51. strings = [b"a", b"b" * 16]
  52. illegalStrings = [b"\x10\x00\x00\x00aaaaaa"]
  53. partialStrings = [b"\x00\x00\x00", b"hello there", b""]
  54. def test_bigReceive(self):
  55. r = self.getProtocol()
  56. big = b""
  57. for s in self.strings * 4:
  58. big += pack("!i", len(s)) + s
  59. r.dataReceived(big)
  60. self.assertEqual(r.received, self.strings * 4)