PageRenderTime 88ms CodeModel.GetById 36ms RepoModel.GetById 0ms app.codeStats 0ms

/fstmerge/examples/eXe/rev3426-3513/right-branch-3513/twisted/test/test_protocols.py

https://github.com/RoDaniel/featurehouse
Python | 315 lines | 312 code | 0 blank | 3 comment | 1 complexity | 4241c0872ee69d45523dbcc8458a9920 MD5 | raw file
  1. """
  2. Test cases for twisted.protocols package.
  3. """
  4. from twisted.trial import unittest
  5. from twisted.protocols import basic, wire, portforward
  6. from twisted.internet import reactor, protocol, defer
  7. import string, struct
  8. import StringIO
  9. class StringIOWithoutClosing(StringIO.StringIO):
  10. def close(self):
  11. pass
  12. class LineTester(basic.LineReceiver):
  13. delimiter = '\n'
  14. MAX_LENGTH = 64
  15. def connectionMade(self):
  16. self.received = []
  17. def lineReceived(self, line):
  18. self.received.append(line)
  19. if line == '':
  20. self.setRawMode()
  21. elif line == 'pause':
  22. self.pauseProducing()
  23. reactor.callLater(0, self.resumeProducing)
  24. elif line == 'rawpause':
  25. self.pauseProducing()
  26. self.setRawMode()
  27. self.received.append('')
  28. reactor.callLater(0, self.resumeProducing)
  29. elif line == 'stop':
  30. self.stopProducing()
  31. elif line[:4] == 'len ':
  32. self.length = int(line[4:])
  33. elif line.startswith('produce'):
  34. self.transport.registerProducer(self, False)
  35. elif line.startswith('unproduce'):
  36. self.transport.unregisterProducer()
  37. def rawDataReceived(self, data):
  38. data, rest = data[:self.length], data[self.length:]
  39. self.length = self.length - len(data)
  40. self.received[-1] = self.received[-1] + data
  41. if self.length == 0:
  42. self.setLineMode(rest)
  43. def lineLengthExceeded(self, line):
  44. if len(line) > self.MAX_LENGTH+1:
  45. self.setLineMode(line[self.MAX_LENGTH+1:])
  46. class LineOnlyTester(basic.LineOnlyReceiver):
  47. delimiter = '\n'
  48. MAX_LENGTH = 64
  49. def connectionMade(self):
  50. self.received = []
  51. def lineReceived(self, line):
  52. self.received.append(line)
  53. class WireTestCase(unittest.TestCase):
  54. def testEcho(self):
  55. t = StringIOWithoutClosing()
  56. a = wire.Echo()
  57. a.makeConnection(protocol.FileWrapper(t))
  58. a.dataReceived("hello")
  59. a.dataReceived("world")
  60. a.dataReceived("how")
  61. a.dataReceived("are")
  62. a.dataReceived("you")
  63. self.failUnlessEqual(t.getvalue(), "helloworldhowareyou")
  64. def testWho(self):
  65. t = StringIOWithoutClosing()
  66. a = wire.Who()
  67. a.makeConnection(protocol.FileWrapper(t))
  68. self.failUnlessEqual(t.getvalue(), "root\r\n")
  69. def testQOTD(self):
  70. t = StringIOWithoutClosing()
  71. a = wire.QOTD()
  72. a.makeConnection(protocol.FileWrapper(t))
  73. self.failUnlessEqual(t.getvalue(),
  74. "An apple a day keeps the doctor away.\r\n")
  75. def testDiscard(self):
  76. t = StringIOWithoutClosing()
  77. a = wire.Discard()
  78. a.makeConnection(protocol.FileWrapper(t))
  79. a.dataReceived("hello")
  80. a.dataReceived("world")
  81. a.dataReceived("how")
  82. a.dataReceived("are")
  83. a.dataReceived("you")
  84. self.failUnlessEqual(t.getvalue(), "")
  85. class LineReceiverTestCase(unittest.TestCase):
  86. buffer = '''\
  87. len 10
  88. 0123456789len 5
  89. 1234
  90. len 20
  91. foo 123
  92. 0123456789
  93. 012345678len 0
  94. foo 5
  95. 1234567890123456789012345678901234567890123456789012345678901234567890
  96. len 1
  97. a'''
  98. output = ['len 10', '0123456789', 'len 5', '1234\n',
  99. 'len 20', 'foo 123', '0123456789\n012345678',
  100. 'len 0', 'foo 5', '', '67890', 'len 1', 'a']
  101. def testBuffer(self):
  102. for packet_size in range(1, 10):
  103. t = StringIOWithoutClosing()
  104. a = LineTester()
  105. a.makeConnection(protocol.FileWrapper(t))
  106. for i in range(len(self.buffer)/packet_size + 1):
  107. s = self.buffer[i*packet_size:(i+1)*packet_size]
  108. a.dataReceived(s)
  109. self.failUnlessEqual(self.output, a.received)
  110. pause_buf = 'twiddle1\ntwiddle2\npause\ntwiddle3\n'
  111. pause_output1 = ['twiddle1', 'twiddle2', 'pause']
  112. pause_output2 = pause_output1+['twiddle3']
  113. def testPausing(self):
  114. for packet_size in range(1, 10):
  115. t = StringIOWithoutClosing()
  116. a = LineTester()
  117. a.makeConnection(protocol.FileWrapper(t))
  118. for i in range(len(self.pause_buf)/packet_size + 1):
  119. s = self.pause_buf[i*packet_size:(i+1)*packet_size]
  120. a.dataReceived(s)
  121. self.failUnlessEqual(self.pause_output1, a.received)
  122. reactor.iterate(0)
  123. self.failUnlessEqual(self.pause_output2, a.received)
  124. rawpause_buf = 'twiddle1\ntwiddle2\nlen 5\nrawpause\n12345twiddle3\n'
  125. rawpause_output1 = ['twiddle1', 'twiddle2', 'len 5', 'rawpause', '']
  126. rawpause_output2 = ['twiddle1', 'twiddle2', 'len 5', 'rawpause', '12345', 'twiddle3']
  127. def testRawPausing(self):
  128. for packet_size in range(1, 10):
  129. t = StringIOWithoutClosing()
  130. a = LineTester()
  131. a.makeConnection(protocol.FileWrapper(t))
  132. for i in range(len(self.rawpause_buf)/packet_size + 1):
  133. s = self.rawpause_buf[i*packet_size:(i+1)*packet_size]
  134. a.dataReceived(s)
  135. self.failUnlessEqual(self.rawpause_output1, a.received)
  136. reactor.iterate(0)
  137. self.failUnlessEqual(self.rawpause_output2, a.received)
  138. stop_buf = 'twiddle1\ntwiddle2\nstop\nmore\nstuff\n'
  139. stop_output = ['twiddle1', 'twiddle2', 'stop']
  140. def testStopProducing(self):
  141. for packet_size in range(1, 10):
  142. t = StringIOWithoutClosing()
  143. a = LineTester()
  144. a.makeConnection(protocol.FileWrapper(t))
  145. for i in range(len(self.stop_buf)/packet_size + 1):
  146. s = self.stop_buf[i*packet_size:(i+1)*packet_size]
  147. a.dataReceived(s)
  148. self.failUnlessEqual(self.stop_output, a.received)
  149. def testLineReceiverAsProducer(self):
  150. a = LineTester()
  151. t = StringIOWithoutClosing()
  152. a.makeConnection(protocol.FileWrapper(t))
  153. a.dataReceived('produce\nhello world\nunproduce\ngoodbye\n')
  154. self.assertEquals(a.received, ['produce', 'hello world', 'unproduce', 'goodbye'])
  155. class LineOnlyReceiverTestCase(unittest.TestCase):
  156. buffer = """foo
  157. bleakness
  158. desolation
  159. plastic forks
  160. """
  161. def testBuffer(self):
  162. t = StringIOWithoutClosing()
  163. a = LineOnlyTester()
  164. a.makeConnection(protocol.FileWrapper(t))
  165. for c in self.buffer:
  166. a.dataReceived(c)
  167. self.failUnlessEqual(a.received, self.buffer.split('\n')[:-1])
  168. def testLineTooLong(self):
  169. t = StringIOWithoutClosing()
  170. a = LineOnlyTester()
  171. a.makeConnection(protocol.FileWrapper(t))
  172. res = a.dataReceived('x'*200)
  173. self.failIfEqual(res, None)
  174. class TestMixin:
  175. def connectionMade(self):
  176. self.received = []
  177. def stringReceived(self, s):
  178. self.received.append(s)
  179. MAX_LENGTH = 50
  180. closed = 0
  181. def connectionLost(self, reason):
  182. self.closed = 1
  183. class TestNetstring(TestMixin, basic.NetstringReceiver):
  184. pass
  185. class LPTestCaseMixin:
  186. illegal_strings = []
  187. protocol = None
  188. def getProtocol(self):
  189. t = StringIOWithoutClosing()
  190. a = self.protocol()
  191. a.makeConnection(protocol.FileWrapper(t))
  192. return a
  193. def testIllegal(self):
  194. for s in self.illegal_strings:
  195. r = self.getProtocol()
  196. for c in s:
  197. r.dataReceived(c)
  198. self.assertEquals(r.transport.closed, 1)
  199. class NetstringReceiverTestCase(unittest.TestCase, LPTestCaseMixin):
  200. strings = ['hello', 'world', 'how', 'are', 'you123', ':today', "a"*515]
  201. illegal_strings = ['9999999999999999999999', 'abc', '4:abcde',
  202. '51:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab,',]
  203. protocol = TestNetstring
  204. def testBuffer(self):
  205. for packet_size in range(1, 10):
  206. t = StringIOWithoutClosing()
  207. a = TestNetstring()
  208. a.MAX_LENGTH = 699
  209. a.makeConnection(protocol.FileWrapper(t))
  210. for s in self.strings:
  211. a.sendString(s)
  212. out = t.getvalue()
  213. for i in range(len(out)/packet_size + 1):
  214. s = out[i*packet_size:(i+1)*packet_size]
  215. if s:
  216. a.dataReceived(s)
  217. self.assertEquals(a.received, self.strings)
  218. class TestInt32(TestMixin, basic.Int32StringReceiver):
  219. MAX_LENGTH = 50
  220. class Int32TestCase(unittest.TestCase, LPTestCaseMixin):
  221. protocol = TestInt32
  222. strings = ["a", "b" * 16]
  223. illegal_strings = ["\x10\x00\x00\x00aaaaaa"]
  224. partial_strings = ["\x00\x00\x00", "hello there", ""]
  225. def testPartial(self):
  226. for s in self.partial_strings:
  227. r = self.getProtocol()
  228. r.MAX_LENGTH = 99999999
  229. for c in s:
  230. r.dataReceived(c)
  231. self.assertEquals(r.received, [])
  232. def testReceive(self):
  233. r = self.getProtocol()
  234. for s in self.strings:
  235. for c in struct.pack("!i",len(s))+s:
  236. r.dataReceived(c)
  237. self.assertEquals(r.received, self.strings)
  238. class OnlyProducerTransport(object):
  239. paused = False
  240. disconnecting = False
  241. def __init__(self):
  242. self.data = []
  243. def pauseProducing(self):
  244. self.paused = True
  245. def resumeProducing(self):
  246. self.paused = False
  247. def write(self, bytes):
  248. self.data.append(bytes)
  249. class ConsumingProtocol(basic.LineReceiver):
  250. def lineReceived(self, line):
  251. self.transport.write(line)
  252. self.pauseProducing()
  253. class ProducerTestCase(unittest.TestCase):
  254. def testPauseResume(self):
  255. p = ConsumingProtocol()
  256. t = OnlyProducerTransport()
  257. p.makeConnection(t)
  258. p.dataReceived('hello, ')
  259. self.failIf(t.data)
  260. self.failIf(t.paused)
  261. self.failIf(p.paused)
  262. p.dataReceived('world\r\n')
  263. self.assertEquals(t.data, ['hello, world'])
  264. self.failUnless(t.paused)
  265. self.failUnless(p.paused)
  266. p.resumeProducing()
  267. self.failIf(t.paused)
  268. self.failIf(p.paused)
  269. p.dataReceived('hello\r\nworld\r\n')
  270. self.assertEquals(t.data, ['hello, world', 'hello'])
  271. self.failUnless(t.paused)
  272. self.failUnless(p.paused)
  273. p.resumeProducing()
  274. p.dataReceived('goodbye\r\n')
  275. self.assertEquals(t.data, ['hello, world', 'hello', 'world'])
  276. self.failUnless(t.paused)
  277. self.failUnless(p.paused)
  278. p.resumeProducing()
  279. self.assertEquals(t.data, ['hello, world', 'hello', 'world', 'goodbye'])
  280. self.failUnless(t.paused)
  281. self.failUnless(p.paused)
  282. p.resumeProducing()
  283. self.assertEquals(t.data, ['hello, world', 'hello', 'world', 'goodbye'])
  284. self.failIf(t.paused)
  285. self.failIf(p.paused)
  286. class Portforwarding(unittest.TestCase):
  287. def testPortforward(self):
  288. serverProtocol = wire.Echo()
  289. realServerFactory = protocol.ServerFactory()
  290. realServerFactory.protocol = lambda: serverProtocol
  291. realServerPort = reactor.listenTCP(0, realServerFactory,
  292. interface='127.0.0.1')
  293. proxyServerFactory = portforward.ProxyFactory('127.0.0.1',
  294. realServerPort.getHost().port)
  295. proxyServerPort = reactor.listenTCP(0, proxyServerFactory,
  296. interface='127.0.0.1')
  297. nBytes = 1000
  298. received = []
  299. clientProtocol = protocol.Protocol()
  300. clientProtocol.dataReceived = received.extend
  301. clientProtocol.connectionMade = lambda: clientProtocol.transport.write('x' * nBytes)
  302. clientFactory = protocol.ClientFactory()
  303. clientFactory.protocol = lambda: clientProtocol
  304. reactor.connectTCP('127.0.0.1', proxyServerPort.getHost().port,
  305. clientFactory)
  306. c = 0
  307. while len(received) < nBytes and c < 100:
  308. reactor.iterate(0.01)
  309. c += 1
  310. self.assertEquals(''.join(received), 'x' * nBytes)
  311. clientProtocol.transport.loseConnection()
  312. serverProtocol.transport.loseConnection()
  313. return defer.gatherResults([
  314. defer.maybeDeferred(realServerPort.stopListening),
  315. defer.maybeDeferred(proxyServerPort.stopListening)])