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_loopback.py 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Test case for L{twisted.protocols.loopback}.
  5. """
  6. from zope.interface import implementer
  7. from twisted.internet import defer, interfaces, reactor
  8. from twisted.internet.defer import Deferred
  9. from twisted.internet.interfaces import IAddress, IPullProducer, IPushProducer
  10. from twisted.internet.protocol import Protocol
  11. from twisted.protocols import basic, loopback
  12. from twisted.trial import unittest
  13. class SimpleProtocol(basic.LineReceiver):
  14. def __init__(self):
  15. self.conn = defer.Deferred()
  16. self.lines = []
  17. self.connLost = []
  18. def connectionMade(self):
  19. self.conn.callback(None)
  20. def lineReceived(self, line):
  21. self.lines.append(line)
  22. def connectionLost(self, reason):
  23. self.connLost.append(reason)
  24. class DoomProtocol(SimpleProtocol):
  25. i = 0
  26. def lineReceived(self, line):
  27. self.i += 1
  28. if self.i < 4:
  29. # by this point we should have connection closed,
  30. # but just in case we didn't we won't ever send 'Hello 4'
  31. self.sendLine(b"Hello %d" % (self.i,))
  32. SimpleProtocol.lineReceived(self, line)
  33. if self.lines[-1] == b"Hello 3":
  34. self.transport.loseConnection()
  35. class LoopbackTestCaseMixin:
  36. def testRegularFunction(self):
  37. s = SimpleProtocol()
  38. c = SimpleProtocol()
  39. def sendALine(result):
  40. s.sendLine(b"THIS IS LINE ONE!")
  41. s.transport.loseConnection()
  42. s.conn.addCallback(sendALine)
  43. def check(ignored):
  44. self.assertEqual(c.lines, [b"THIS IS LINE ONE!"])
  45. self.assertEqual(len(s.connLost), 1)
  46. self.assertEqual(len(c.connLost), 1)
  47. d = defer.maybeDeferred(self.loopbackFunc, s, c)
  48. d.addCallback(check)
  49. return d
  50. def testSneakyHiddenDoom(self):
  51. s = DoomProtocol()
  52. c = DoomProtocol()
  53. def sendALine(result):
  54. s.sendLine(b"DOOM LINE")
  55. s.conn.addCallback(sendALine)
  56. def check(ignored):
  57. self.assertEqual(s.lines, [b"Hello 1", b"Hello 2", b"Hello 3"])
  58. self.assertEqual(
  59. c.lines, [b"DOOM LINE", b"Hello 1", b"Hello 2", b"Hello 3"]
  60. )
  61. self.assertEqual(len(s.connLost), 1)
  62. self.assertEqual(len(c.connLost), 1)
  63. d = defer.maybeDeferred(self.loopbackFunc, s, c)
  64. d.addCallback(check)
  65. return d
  66. class LoopbackAsyncTests(LoopbackTestCaseMixin, unittest.TestCase):
  67. loopbackFunc = staticmethod(loopback.loopbackAsync)
  68. def test_makeConnection(self):
  69. """
  70. Test that the client and server protocol both have makeConnection
  71. invoked on them by loopbackAsync.
  72. """
  73. class TestProtocol(Protocol):
  74. transport = None
  75. def makeConnection(self, transport):
  76. self.transport = transport
  77. server = TestProtocol()
  78. client = TestProtocol()
  79. loopback.loopbackAsync(server, client)
  80. self.assertIsNotNone(client.transport)
  81. self.assertIsNotNone(server.transport)
  82. def _hostpeertest(self, get, testServer):
  83. """
  84. Test one of the permutations of client/server host/peer.
  85. """
  86. class TestProtocol(Protocol):
  87. def makeConnection(self, transport):
  88. Protocol.makeConnection(self, transport)
  89. self.onConnection.callback(transport)
  90. if testServer:
  91. server = TestProtocol()
  92. d = server.onConnection = Deferred()
  93. client = Protocol()
  94. else:
  95. server = Protocol()
  96. client = TestProtocol()
  97. d = client.onConnection = Deferred()
  98. loopback.loopbackAsync(server, client)
  99. def connected(transport):
  100. host = getattr(transport, get)()
  101. self.assertTrue(IAddress.providedBy(host))
  102. return d.addCallback(connected)
  103. def test_serverHost(self):
  104. """
  105. Test that the server gets a transport with a properly functioning
  106. implementation of L{ITransport.getHost}.
  107. """
  108. return self._hostpeertest("getHost", True)
  109. def test_serverPeer(self):
  110. """
  111. Like C{test_serverHost} but for L{ITransport.getPeer}
  112. """
  113. return self._hostpeertest("getPeer", True)
  114. def test_clientHost(self, get="getHost"):
  115. """
  116. Test that the client gets a transport with a properly functioning
  117. implementation of L{ITransport.getHost}.
  118. """
  119. return self._hostpeertest("getHost", False)
  120. def test_clientPeer(self):
  121. """
  122. Like C{test_clientHost} but for L{ITransport.getPeer}.
  123. """
  124. return self._hostpeertest("getPeer", False)
  125. def _greetingtest(self, write, testServer):
  126. """
  127. Test one of the permutations of write/writeSequence client/server.
  128. @param write: The name of the method to test, C{"write"} or
  129. C{"writeSequence"}.
  130. """
  131. class GreeteeProtocol(Protocol):
  132. bytes = b""
  133. def dataReceived(self, bytes):
  134. self.bytes += bytes
  135. if self.bytes == b"bytes":
  136. self.received.callback(None)
  137. class GreeterProtocol(Protocol):
  138. def connectionMade(self):
  139. if write == "write":
  140. self.transport.write(b"bytes")
  141. else:
  142. self.transport.writeSequence([b"byt", b"es"])
  143. if testServer:
  144. server = GreeterProtocol()
  145. client = GreeteeProtocol()
  146. d = client.received = Deferred()
  147. else:
  148. server = GreeteeProtocol()
  149. d = server.received = Deferred()
  150. client = GreeterProtocol()
  151. loopback.loopbackAsync(server, client)
  152. return d
  153. def test_clientGreeting(self):
  154. """
  155. Test that on a connection where the client speaks first, the server
  156. receives the bytes sent by the client.
  157. """
  158. return self._greetingtest("write", False)
  159. def test_clientGreetingSequence(self):
  160. """
  161. Like C{test_clientGreeting}, but use C{writeSequence} instead of
  162. C{write} to issue the greeting.
  163. """
  164. return self._greetingtest("writeSequence", False)
  165. def test_serverGreeting(self, write="write"):
  166. """
  167. Test that on a connection where the server speaks first, the client
  168. receives the bytes sent by the server.
  169. """
  170. return self._greetingtest("write", True)
  171. def test_serverGreetingSequence(self):
  172. """
  173. Like C{test_serverGreeting}, but use C{writeSequence} instead of
  174. C{write} to issue the greeting.
  175. """
  176. return self._greetingtest("writeSequence", True)
  177. def _producertest(self, producerClass):
  178. toProduce = [b"%d" % (i,) for i in range(0, 10)]
  179. class ProducingProtocol(Protocol):
  180. def connectionMade(self):
  181. self.producer = producerClass(list(toProduce))
  182. self.producer.start(self.transport)
  183. class ReceivingProtocol(Protocol):
  184. bytes = b""
  185. def dataReceived(self, data):
  186. self.bytes += data
  187. if self.bytes == b"".join(toProduce):
  188. self.received.callback((client, server))
  189. server = ProducingProtocol()
  190. client = ReceivingProtocol()
  191. client.received = Deferred()
  192. loopback.loopbackAsync(server, client)
  193. return client.received
  194. def test_pushProducer(self):
  195. """
  196. Test a push producer registered against a loopback transport.
  197. """
  198. @implementer(IPushProducer)
  199. class PushProducer:
  200. resumed = False
  201. def __init__(self, toProduce):
  202. self.toProduce = toProduce
  203. def resumeProducing(self):
  204. self.resumed = True
  205. def start(self, consumer):
  206. self.consumer = consumer
  207. consumer.registerProducer(self, True)
  208. self._produceAndSchedule()
  209. def _produceAndSchedule(self):
  210. if self.toProduce:
  211. self.consumer.write(self.toProduce.pop(0))
  212. reactor.callLater(0, self._produceAndSchedule)
  213. else:
  214. self.consumer.unregisterProducer()
  215. d = self._producertest(PushProducer)
  216. def finished(results):
  217. (client, server) = results
  218. self.assertFalse(
  219. server.producer.resumed,
  220. "Streaming producer should not have been resumed.",
  221. )
  222. d.addCallback(finished)
  223. return d
  224. def test_pullProducer(self):
  225. """
  226. Test a pull producer registered against a loopback transport.
  227. """
  228. @implementer(IPullProducer)
  229. class PullProducer:
  230. def __init__(self, toProduce):
  231. self.toProduce = toProduce
  232. def start(self, consumer):
  233. self.consumer = consumer
  234. self.consumer.registerProducer(self, False)
  235. def resumeProducing(self):
  236. self.consumer.write(self.toProduce.pop(0))
  237. if not self.toProduce:
  238. self.consumer.unregisterProducer()
  239. return self._producertest(PullProducer)
  240. def test_writeNotReentrant(self):
  241. """
  242. L{loopback.loopbackAsync} does not call a protocol's C{dataReceived}
  243. method while that protocol's transport's C{write} method is higher up
  244. on the stack.
  245. """
  246. class Server(Protocol):
  247. def dataReceived(self, bytes):
  248. self.transport.write(b"bytes")
  249. class Client(Protocol):
  250. ready = False
  251. def connectionMade(self):
  252. reactor.callLater(0, self.go)
  253. def go(self):
  254. self.transport.write(b"foo")
  255. self.ready = True
  256. def dataReceived(self, bytes):
  257. self.wasReady = self.ready
  258. self.transport.loseConnection()
  259. server = Server()
  260. client = Client()
  261. d = loopback.loopbackAsync(client, server)
  262. def cbFinished(ignored):
  263. self.assertTrue(client.wasReady)
  264. d.addCallback(cbFinished)
  265. return d
  266. def test_pumpPolicy(self):
  267. """
  268. The callable passed as the value for the C{pumpPolicy} parameter to
  269. L{loopbackAsync} is called with a L{_LoopbackQueue} of pending bytes
  270. and a protocol to which they should be delivered.
  271. """
  272. pumpCalls = []
  273. def dummyPolicy(queue, target):
  274. bytes = []
  275. while queue:
  276. bytes.append(queue.get())
  277. pumpCalls.append((target, bytes))
  278. client = Protocol()
  279. server = Protocol()
  280. finished = loopback.loopbackAsync(server, client, dummyPolicy)
  281. self.assertEqual(pumpCalls, [])
  282. client.transport.write(b"foo")
  283. client.transport.write(b"bar")
  284. server.transport.write(b"baz")
  285. server.transport.write(b"quux")
  286. server.transport.loseConnection()
  287. def cbComplete(ignored):
  288. self.assertEqual(
  289. pumpCalls,
  290. # The order here is somewhat arbitrary. The implementation
  291. # happens to always deliver data to the client first.
  292. [(client, [b"baz", b"quux", None]), (server, [b"foo", b"bar"])],
  293. )
  294. finished.addCallback(cbComplete)
  295. return finished
  296. def test_identityPumpPolicy(self):
  297. """
  298. L{identityPumpPolicy} is a pump policy which calls the target's
  299. C{dataReceived} method one for each string in the queue passed to it.
  300. """
  301. bytes = []
  302. client = Protocol()
  303. client.dataReceived = bytes.append
  304. queue = loopback._LoopbackQueue()
  305. queue.put(b"foo")
  306. queue.put(b"bar")
  307. queue.put(None)
  308. loopback.identityPumpPolicy(queue, client)
  309. self.assertEqual(bytes, [b"foo", b"bar"])
  310. def test_collapsingPumpPolicy(self):
  311. """
  312. L{collapsingPumpPolicy} is a pump policy which calls the target's
  313. C{dataReceived} only once with all of the strings in the queue passed
  314. to it joined together.
  315. """
  316. bytes = []
  317. client = Protocol()
  318. client.dataReceived = bytes.append
  319. queue = loopback._LoopbackQueue()
  320. queue.put(b"foo")
  321. queue.put(b"bar")
  322. queue.put(None)
  323. loopback.collapsingPumpPolicy(queue, client)
  324. self.assertEqual(bytes, [b"foobar"])
  325. class LoopbackTCPTests(LoopbackTestCaseMixin, unittest.TestCase):
  326. loopbackFunc = staticmethod(loopback.loopbackTCP)
  327. class LoopbackUNIXTests(LoopbackTestCaseMixin, unittest.TestCase):
  328. loopbackFunc = staticmethod(loopback.loopbackUNIX)
  329. if interfaces.IReactorUNIX(reactor, None) is None:
  330. skip = "Current reactor does not support UNIX sockets"
  331. class LoopbackRelayTest(unittest.TestCase):
  332. """
  333. Test for L{twisted.protocols.loopback.LoopbackRelay}
  334. """
  335. class Receiver(Protocol):
  336. """
  337. Simple Receiver class used for testing LoopbackRelay
  338. """
  339. data = b""
  340. def dataReceived(self, data):
  341. "Accumulate received data for verification"
  342. self.data += data
  343. def test_write(self):
  344. "Test to verify that the write function works as expected"
  345. receiver = self.Receiver()
  346. relay = loopback.LoopbackRelay(receiver)
  347. relay.write(b"abc")
  348. relay.write(b"def")
  349. self.assertEqual(receiver.data, b"")
  350. relay.clearBuffer()
  351. self.assertEqual(receiver.data, b"abcdef")
  352. def test_writeSequence(self):
  353. "Test to verify that the writeSequence function works as expected"
  354. receiver = self.Receiver()
  355. relay = loopback.LoopbackRelay(receiver)
  356. relay.writeSequence([b"The ", b"quick ", b"brown ", b"fox "])
  357. relay.writeSequence([b"jumps ", b"over ", b"the lazy dog"])
  358. self.assertEqual(receiver.data, b"")
  359. relay.clearBuffer()
  360. self.assertEqual(receiver.data, b"The quick brown fox jumps over the lazy dog")