proto_helpers.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  1. # -*- test-case-name: twisted.test.test_stringtransport -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Assorted functionality which is commonly useful when writing unit tests.
  6. """
  7. from __future__ import division, absolute_import
  8. from socket import AF_INET, AF_INET6
  9. from io import BytesIO
  10. from zope.interface import implementer, implementedBy
  11. from zope.interface.verify import verifyClass
  12. from twisted.python import failure
  13. from twisted.python.compat import unicode, intToBytes
  14. from twisted.internet.defer import Deferred
  15. from twisted.internet.interfaces import (
  16. ITransport, IConsumer, IPushProducer, IConnector,
  17. IReactorCore, IReactorTCP, IReactorSSL, IReactorUNIX, IReactorSocket,
  18. IListeningPort, IReactorFDSet,
  19. )
  20. from twisted.internet.abstract import isIPv6Address
  21. from twisted.internet.error import UnsupportedAddressFamily
  22. from twisted.protocols import basic
  23. from twisted.internet import protocol, error, address, task
  24. from twisted.internet.task import Clock
  25. from twisted.internet.address import IPv4Address, UNIXAddress, IPv6Address
  26. class AccumulatingProtocol(protocol.Protocol):
  27. """
  28. L{AccumulatingProtocol} is an L{IProtocol} implementation which collects
  29. the data delivered to it and can fire a Deferred when it is connected or
  30. disconnected.
  31. @ivar made: A flag indicating whether C{connectionMade} has been called.
  32. @ivar data: Bytes giving all the data passed to C{dataReceived}.
  33. @ivar closed: A flag indicated whether C{connectionLost} has been called.
  34. @ivar closedReason: The value of the I{reason} parameter passed to
  35. C{connectionLost}.
  36. @ivar closedDeferred: If set to a L{Deferred}, this will be fired when
  37. C{connectionLost} is called.
  38. """
  39. made = closed = 0
  40. closedReason = None
  41. closedDeferred = None
  42. data = b""
  43. factory = None
  44. def connectionMade(self):
  45. self.made = 1
  46. if (self.factory is not None and
  47. self.factory.protocolConnectionMade is not None):
  48. d = self.factory.protocolConnectionMade
  49. self.factory.protocolConnectionMade = None
  50. d.callback(self)
  51. def dataReceived(self, data):
  52. self.data += data
  53. def connectionLost(self, reason):
  54. self.closed = 1
  55. self.closedReason = reason
  56. if self.closedDeferred is not None:
  57. d, self.closedDeferred = self.closedDeferred, None
  58. d.callback(None)
  59. class LineSendingProtocol(basic.LineReceiver):
  60. lostConn = False
  61. def __init__(self, lines, start = True):
  62. self.lines = lines[:]
  63. self.response = []
  64. self.start = start
  65. def connectionMade(self):
  66. if self.start:
  67. for line in self.lines:
  68. self.sendLine(line)
  69. def lineReceived(self, line):
  70. if not self.start:
  71. for line in self.lines:
  72. self.sendLine(line)
  73. self.lines = []
  74. self.response.append(line)
  75. def connectionLost(self, reason):
  76. self.lostConn = True
  77. class FakeDatagramTransport:
  78. noAddr = object()
  79. def __init__(self):
  80. self.written = []
  81. def write(self, packet, addr=noAddr):
  82. self.written.append((packet, addr))
  83. @implementer(ITransport, IConsumer, IPushProducer)
  84. class StringTransport:
  85. """
  86. A transport implementation which buffers data in memory and keeps track of
  87. its other state without providing any behavior.
  88. L{StringTransport} has a number of attributes which are not part of any of
  89. the interfaces it claims to implement. These attributes are provided for
  90. testing purposes. Implementation code should not use any of these
  91. attributes; they are not provided by other transports.
  92. @ivar disconnecting: A C{bool} which is C{False} until L{loseConnection} is
  93. called, then C{True}.
  94. @ivar disconnected: A C{bool} which is C{False} until L{abortConnection} is
  95. called, then C{True}.
  96. @ivar producer: If a producer is currently registered, C{producer} is a
  97. reference to it. Otherwise, L{None}.
  98. @ivar streaming: If a producer is currently registered, C{streaming} refers
  99. to the value of the second parameter passed to C{registerProducer}.
  100. @ivar hostAddr: L{None} or an object which will be returned as the host
  101. address of this transport. If L{None}, a nasty tuple will be returned
  102. instead.
  103. @ivar peerAddr: L{None} or an object which will be returned as the peer
  104. address of this transport. If L{None}, a nasty tuple will be returned
  105. instead.
  106. @ivar producerState: The state of this L{StringTransport} in its capacity
  107. as an L{IPushProducer}. One of C{'producing'}, C{'paused'}, or
  108. C{'stopped'}.
  109. @ivar io: A L{io.BytesIO} which holds the data which has been written to
  110. this transport since the last call to L{clear}. Use L{value} instead
  111. of accessing this directly.
  112. @ivar _lenient: By default L{StringTransport} enforces that
  113. L{resumeProducing} is not called after the connection is lost. This is
  114. to ensure that any code that does call L{resumeProducing} after the
  115. connection is lost is not blindly expecting L{resumeProducing} to have
  116. any impact.
  117. However, if your test case is calling L{resumeProducing} after
  118. connection close on purpose, and you know it won't block expecting
  119. further data to show up, this flag may safely be set to L{True}.
  120. Defaults to L{False}.
  121. @type lenient: L{bool}
  122. """
  123. disconnecting = False
  124. disconnected = False
  125. producer = None
  126. streaming = None
  127. hostAddr = None
  128. peerAddr = None
  129. producerState = 'producing'
  130. def __init__(self, hostAddress=None, peerAddress=None, lenient=False):
  131. self.clear()
  132. if hostAddress is not None:
  133. self.hostAddr = hostAddress
  134. if peerAddress is not None:
  135. self.peerAddr = peerAddress
  136. self.connected = True
  137. self._lenient = lenient
  138. def clear(self):
  139. """
  140. Discard all data written to this transport so far.
  141. This is not a transport method. It is intended for tests. Do not use
  142. it in implementation code.
  143. """
  144. self.io = BytesIO()
  145. def value(self):
  146. """
  147. Retrieve all data which has been buffered by this transport.
  148. This is not a transport method. It is intended for tests. Do not use
  149. it in implementation code.
  150. @return: A C{bytes} giving all data written to this transport since the
  151. last call to L{clear}.
  152. @rtype: C{bytes}
  153. """
  154. return self.io.getvalue()
  155. # ITransport
  156. def write(self, data):
  157. if isinstance(data, unicode): # no, really, I mean it
  158. raise TypeError("Data must not be unicode")
  159. self.io.write(data)
  160. def writeSequence(self, data):
  161. self.io.write(b''.join(data))
  162. def loseConnection(self):
  163. """
  164. Close the connection. Does nothing besides toggle the C{disconnecting}
  165. instance variable to C{True}.
  166. """
  167. self.disconnecting = True
  168. def abortConnection(self):
  169. """
  170. Abort the connection. Same as C{loseConnection}, but also toggles the
  171. C{aborted} instance variable to C{True}.
  172. """
  173. self.disconnected = True
  174. self.loseConnection()
  175. def getPeer(self):
  176. if self.peerAddr is None:
  177. return address.IPv4Address('TCP', '192.168.1.1', 54321)
  178. return self.peerAddr
  179. def getHost(self):
  180. if self.hostAddr is None:
  181. return address.IPv4Address('TCP', '10.0.0.1', 12345)
  182. return self.hostAddr
  183. # IConsumer
  184. def registerProducer(self, producer, streaming):
  185. if self.producer is not None:
  186. raise RuntimeError("Cannot register two producers")
  187. self.producer = producer
  188. self.streaming = streaming
  189. def unregisterProducer(self):
  190. if self.producer is None:
  191. raise RuntimeError(
  192. "Cannot unregister a producer unless one is registered")
  193. self.producer = None
  194. self.streaming = None
  195. # IPushProducer
  196. def _checkState(self):
  197. if self.disconnecting and not self._lenient:
  198. raise RuntimeError(
  199. "Cannot resume producing after loseConnection")
  200. if self.producerState == 'stopped':
  201. raise RuntimeError("Cannot resume a stopped producer")
  202. def pauseProducing(self):
  203. self._checkState()
  204. self.producerState = 'paused'
  205. def stopProducing(self):
  206. self.producerState = 'stopped'
  207. def resumeProducing(self):
  208. self._checkState()
  209. self.producerState = 'producing'
  210. class StringTransportWithDisconnection(StringTransport):
  211. """
  212. A L{StringTransport} which can be disconnected.
  213. """
  214. def loseConnection(self):
  215. if self.connected:
  216. self.connected = False
  217. self.protocol.connectionLost(
  218. failure.Failure(error.ConnectionDone("Bye.")))
  219. class StringIOWithoutClosing(BytesIO):
  220. """
  221. A BytesIO that can't be closed.
  222. """
  223. def close(self):
  224. """
  225. Do nothing.
  226. """
  227. @implementer(IListeningPort)
  228. class _FakePort(object):
  229. """
  230. A fake L{IListeningPort} to be used in tests.
  231. @ivar _hostAddress: The L{IAddress} this L{IListeningPort} is pretending
  232. to be listening on.
  233. """
  234. def __init__(self, hostAddress):
  235. """
  236. @param hostAddress: An L{IAddress} this L{IListeningPort} should
  237. pretend to be listening on.
  238. """
  239. self._hostAddress = hostAddress
  240. def startListening(self):
  241. """
  242. Fake L{IListeningPort.startListening} that doesn't do anything.
  243. """
  244. def stopListening(self):
  245. """
  246. Fake L{IListeningPort.stopListening} that doesn't do anything.
  247. """
  248. def getHost(self):
  249. """
  250. Fake L{IListeningPort.getHost} that returns our L{IAddress}.
  251. """
  252. return self._hostAddress
  253. @implementer(IConnector)
  254. class _FakeConnector(object):
  255. """
  256. A fake L{IConnector} that allows us to inspect if it has been told to stop
  257. connecting.
  258. @ivar stoppedConnecting: has this connector's
  259. L{_FakeConnector.stopConnecting} method been invoked yet?
  260. @ivar _address: An L{IAddress} provider that represents our destination.
  261. """
  262. _disconnected = False
  263. stoppedConnecting = False
  264. def __init__(self, address):
  265. """
  266. @param address: An L{IAddress} provider that represents this
  267. connector's destination.
  268. """
  269. self._address = address
  270. def stopConnecting(self):
  271. """
  272. Implement L{IConnector.stopConnecting} and set
  273. L{_FakeConnector.stoppedConnecting} to C{True}
  274. """
  275. self.stoppedConnecting = True
  276. def disconnect(self):
  277. """
  278. Implement L{IConnector.disconnect} as a no-op.
  279. """
  280. self._disconnected = True
  281. def connect(self):
  282. """
  283. Implement L{IConnector.connect} as a no-op.
  284. """
  285. def getDestination(self):
  286. """
  287. Implement L{IConnector.getDestination} to return the C{address} passed
  288. to C{__init__}.
  289. """
  290. return self._address
  291. @implementer(
  292. IReactorCore,
  293. IReactorTCP, IReactorSSL, IReactorUNIX, IReactorSocket, IReactorFDSet
  294. )
  295. class MemoryReactor(object):
  296. """
  297. A fake reactor to be used in tests. This reactor doesn't actually do
  298. much that's useful yet. It accepts TCP connection setup attempts, but
  299. they will never succeed.
  300. @ivar hasInstalled: Keeps track of whether this reactor has been installed.
  301. @type hasInstalled: L{bool}
  302. @ivar running: Keeps track of whether this reactor is running.
  303. @type running: L{bool}
  304. @ivar hasStopped: Keeps track of whether this reactor has been stopped.
  305. @type hasStopped: L{bool}
  306. @ivar hasCrashed: Keeps track of whether this reactor has crashed.
  307. @type hasCrashed: L{bool}
  308. @ivar whenRunningHooks: Keeps track of hooks registered with
  309. C{callWhenRunning}.
  310. @type whenRunningHooks: L{list}
  311. @ivar triggers: Keeps track of hooks registered with
  312. C{addSystemEventTrigger}.
  313. @type triggers: L{dict}
  314. @ivar tcpClients: Keeps track of connection attempts (ie, calls to
  315. C{connectTCP}).
  316. @type tcpClients: L{list}
  317. @ivar tcpServers: Keeps track of server listen attempts (ie, calls to
  318. C{listenTCP}).
  319. @type tcpServers: L{list}
  320. @ivar sslClients: Keeps track of connection attempts (ie, calls to
  321. C{connectSSL}).
  322. @type sslClients: L{list}
  323. @ivar sslServers: Keeps track of server listen attempts (ie, calls to
  324. C{listenSSL}).
  325. @type sslServers: L{list}
  326. @ivar unixClients: Keeps track of connection attempts (ie, calls to
  327. C{connectUNIX}).
  328. @type unixClients: L{list}
  329. @ivar unixServers: Keeps track of server listen attempts (ie, calls to
  330. C{listenUNIX}).
  331. @type unixServers: L{list}
  332. @ivar adoptedPorts: Keeps track of server listen attempts (ie, calls to
  333. C{adoptStreamPort}).
  334. @ivar adoptedStreamConnections: Keeps track of stream-oriented
  335. connections added using C{adoptStreamConnection}.
  336. """
  337. def __init__(self):
  338. """
  339. Initialize the tracking lists.
  340. """
  341. self.hasInstalled = False
  342. self.running = False
  343. self.hasRun = True
  344. self.hasStopped = True
  345. self.hasCrashed = True
  346. self.whenRunningHooks = []
  347. self.triggers = {}
  348. self.tcpClients = []
  349. self.tcpServers = []
  350. self.sslClients = []
  351. self.sslServers = []
  352. self.unixClients = []
  353. self.unixServers = []
  354. self.adoptedPorts = []
  355. self.adoptedStreamConnections = []
  356. self.connectors = []
  357. self.readers = set()
  358. self.writers = set()
  359. def install(self):
  360. """
  361. Fake install callable to emulate reactor module installation.
  362. """
  363. self.hasInstalled = True
  364. def resolve(self, name, timeout=10):
  365. """
  366. Not implemented; raises L{NotImplementedError}.
  367. """
  368. raise NotImplementedError()
  369. def run(self):
  370. """
  371. Fake L{IReactorCore.run}.
  372. Sets C{self.running} to L{True}, runs all of the hooks passed to
  373. C{self.callWhenRunning}, then calls C{self.stop} to simulate a request
  374. to stop the reactor.
  375. Sets C{self.hasRun} to L{True}.
  376. """
  377. assert self.running is False
  378. self.running = True
  379. self.hasRun = True
  380. for f, args, kwargs in self.whenRunningHooks:
  381. f(*args, **kwargs)
  382. self.stop()
  383. # That we stopped means we can return, phew.
  384. def stop(self):
  385. """
  386. Fake L{IReactorCore.run}.
  387. Sets C{self.running} to L{False}.
  388. Sets C{self.hasStopped} to L{True}.
  389. """
  390. self.running = False
  391. self.hasStopped = True
  392. def crash(self):
  393. """
  394. Fake L{IReactorCore.crash}.
  395. Sets C{self.running} to L{None}, because that feels crashy.
  396. Sets C{self.hasCrashed} to L{True}.
  397. """
  398. self.running = None
  399. self.hasCrashed = True
  400. def iterate(self, delay=0):
  401. """
  402. Not implemented; raises L{NotImplementedError}.
  403. """
  404. raise NotImplementedError()
  405. def fireSystemEvent(self, eventType):
  406. """
  407. Not implemented; raises L{NotImplementedError}.
  408. """
  409. raise NotImplementedError()
  410. def addSystemEventTrigger(self, phase, eventType, callable, *args, **kw):
  411. """
  412. Fake L{IReactorCore.run}.
  413. Keep track of trigger by appending it to
  414. self.triggers[phase][eventType].
  415. """
  416. phaseTriggers = self.triggers.setdefault(phase, {})
  417. eventTypeTriggers = phaseTriggers.setdefault(eventType, [])
  418. eventTypeTriggers.append((callable, args, kw))
  419. def removeSystemEventTrigger(self, triggerID):
  420. """
  421. Not implemented; raises L{NotImplementedError}.
  422. """
  423. raise NotImplementedError()
  424. def callWhenRunning(self, callable, *args, **kw):
  425. """
  426. Fake L{IReactorCore.callWhenRunning}.
  427. Keeps a list of invocations to make in C{self.whenRunningHooks}.
  428. """
  429. self.whenRunningHooks.append((callable, args, kw))
  430. def adoptStreamPort(self, fileno, addressFamily, factory):
  431. """
  432. Fake L{IReactorSocket.adoptStreamPort}, that logs the call and returns
  433. an L{IListeningPort}.
  434. """
  435. if addressFamily == AF_INET:
  436. addr = IPv4Address('TCP', '0.0.0.0', 1234)
  437. elif addressFamily == AF_INET6:
  438. addr = IPv6Address('TCP', '::', 1234)
  439. else:
  440. raise UnsupportedAddressFamily()
  441. self.adoptedPorts.append((fileno, addressFamily, factory))
  442. return _FakePort(addr)
  443. def adoptStreamConnection(self, fileDescriptor, addressFamily, factory):
  444. """
  445. Record the given stream connection in C{adoptedStreamConnections}.
  446. @see: L{twisted.internet.interfaces.IReactorSocket.adoptStreamConnection}
  447. """
  448. self.adoptedStreamConnections.append((
  449. fileDescriptor, addressFamily, factory))
  450. def adoptDatagramPort(self, fileno, addressFamily, protocol,
  451. maxPacketSize=8192):
  452. """
  453. Fake L{IReactorSocket.adoptDatagramPort}, that logs the call and returns
  454. a fake L{IListeningPort}.
  455. @see: L{twisted.internet.interfaces.IReactorSocket.adoptDatagramPort}
  456. """
  457. if addressFamily == AF_INET:
  458. addr = IPv4Address('UDP', '0.0.0.0', 1234)
  459. elif addressFamily == AF_INET6:
  460. addr = IPv6Address('UDP', '::', 1234)
  461. else:
  462. raise UnsupportedAddressFamily()
  463. self.adoptedPorts.append(
  464. (fileno, addressFamily, protocol, maxPacketSize))
  465. return _FakePort(addr)
  466. def listenTCP(self, port, factory, backlog=50, interface=''):
  467. """
  468. Fake L{IReactorTCP.listenTCP}, that logs the call and
  469. returns an L{IListeningPort}.
  470. """
  471. self.tcpServers.append((port, factory, backlog, interface))
  472. if isIPv6Address(interface):
  473. address = IPv6Address('TCP', interface, port)
  474. else:
  475. address = IPv4Address('TCP', '0.0.0.0', port)
  476. return _FakePort(address)
  477. def connectTCP(self, host, port, factory, timeout=30, bindAddress=None):
  478. """
  479. Fake L{IReactorTCP.connectTCP}, that logs the call and
  480. returns an L{IConnector}.
  481. """
  482. self.tcpClients.append((host, port, factory, timeout, bindAddress))
  483. if isIPv6Address(host):
  484. conn = _FakeConnector(IPv6Address('TCP', host, port))
  485. else:
  486. conn = _FakeConnector(IPv4Address('TCP', host, port))
  487. factory.startedConnecting(conn)
  488. self.connectors.append(conn)
  489. return conn
  490. def listenSSL(self, port, factory, contextFactory,
  491. backlog=50, interface=''):
  492. """
  493. Fake L{IReactorSSL.listenSSL}, that logs the call and
  494. returns an L{IListeningPort}.
  495. """
  496. self.sslServers.append((port, factory, contextFactory,
  497. backlog, interface))
  498. return _FakePort(IPv4Address('TCP', '0.0.0.0', port))
  499. def connectSSL(self, host, port, factory, contextFactory,
  500. timeout=30, bindAddress=None):
  501. """
  502. Fake L{IReactorSSL.connectSSL}, that logs the call and returns an
  503. L{IConnector}.
  504. """
  505. self.sslClients.append((host, port, factory, contextFactory,
  506. timeout, bindAddress))
  507. conn = _FakeConnector(IPv4Address('TCP', host, port))
  508. factory.startedConnecting(conn)
  509. self.connectors.append(conn)
  510. return conn
  511. def listenUNIX(self, address, factory,
  512. backlog=50, mode=0o666, wantPID=0):
  513. """
  514. Fake L{IReactorUNIX.listenUNIX}, that logs the call and returns an
  515. L{IListeningPort}.
  516. """
  517. self.unixServers.append((address, factory, backlog, mode, wantPID))
  518. return _FakePort(UNIXAddress(address))
  519. def connectUNIX(self, address, factory, timeout=30, checkPID=0):
  520. """
  521. Fake L{IReactorUNIX.connectUNIX}, that logs the call and returns an
  522. L{IConnector}.
  523. """
  524. self.unixClients.append((address, factory, timeout, checkPID))
  525. conn = _FakeConnector(UNIXAddress(address))
  526. factory.startedConnecting(conn)
  527. self.connectors.append(conn)
  528. return conn
  529. def addReader(self, reader):
  530. """
  531. Fake L{IReactorFDSet.addReader} which adds the reader to a local set.
  532. """
  533. self.readers.add(reader)
  534. def removeReader(self, reader):
  535. """
  536. Fake L{IReactorFDSet.removeReader} which removes the reader from a
  537. local set.
  538. """
  539. self.readers.discard(reader)
  540. def addWriter(self, writer):
  541. """
  542. Fake L{IReactorFDSet.addWriter} which adds the writer to a local set.
  543. """
  544. self.writers.add(writer)
  545. def removeWriter(self, writer):
  546. """
  547. Fake L{IReactorFDSet.removeWriter} which removes the writer from a
  548. local set.
  549. """
  550. self.writers.discard(writer)
  551. def getReaders(self):
  552. """
  553. Fake L{IReactorFDSet.getReaders} which returns a list of readers from
  554. the local set.
  555. """
  556. return list(self.readers)
  557. def getWriters(self):
  558. """
  559. Fake L{IReactorFDSet.getWriters} which returns a list of writers from
  560. the local set.
  561. """
  562. return list(self.writers)
  563. def removeAll(self):
  564. """
  565. Fake L{IReactorFDSet.removeAll} which removed all readers and writers
  566. from the local sets.
  567. """
  568. self.readers.clear()
  569. self.writers.clear()
  570. for iface in implementedBy(MemoryReactor):
  571. verifyClass(iface, MemoryReactor)
  572. class MemoryReactorClock(MemoryReactor, Clock):
  573. def __init__(self):
  574. MemoryReactor.__init__(self)
  575. Clock.__init__(self)
  576. @implementer(IReactorTCP, IReactorSSL, IReactorUNIX, IReactorSocket)
  577. class RaisingMemoryReactor(object):
  578. """
  579. A fake reactor to be used in tests. It accepts TCP connection setup
  580. attempts, but they will fail.
  581. @ivar _listenException: An instance of an L{Exception}
  582. @ivar _connectException: An instance of an L{Exception}
  583. """
  584. def __init__(self, listenException=None, connectException=None):
  585. """
  586. @param listenException: An instance of an L{Exception} to raise when any
  587. C{listen} method is called.
  588. @param connectException: An instance of an L{Exception} to raise when
  589. any C{connect} method is called.
  590. """
  591. self._listenException = listenException
  592. self._connectException = connectException
  593. def adoptStreamPort(self, fileno, addressFamily, factory):
  594. """
  595. Fake L{IReactorSocket.adoptStreamPort}, that raises
  596. L{_listenException}.
  597. """
  598. raise self._listenException
  599. def listenTCP(self, port, factory, backlog=50, interface=''):
  600. """
  601. Fake L{IReactorTCP.listenTCP}, that raises L{_listenException}.
  602. """
  603. raise self._listenException
  604. def connectTCP(self, host, port, factory, timeout=30, bindAddress=None):
  605. """
  606. Fake L{IReactorTCP.connectTCP}, that raises L{_connectException}.
  607. """
  608. raise self._connectException
  609. def listenSSL(self, port, factory, contextFactory,
  610. backlog=50, interface=''):
  611. """
  612. Fake L{IReactorSSL.listenSSL}, that raises L{_listenException}.
  613. """
  614. raise self._listenException
  615. def connectSSL(self, host, port, factory, contextFactory,
  616. timeout=30, bindAddress=None):
  617. """
  618. Fake L{IReactorSSL.connectSSL}, that raises L{_connectException}.
  619. """
  620. raise self._connectException
  621. def listenUNIX(self, address, factory,
  622. backlog=50, mode=0o666, wantPID=0):
  623. """
  624. Fake L{IReactorUNIX.listenUNIX}, that raises L{_listenException}.
  625. """
  626. raise self._listenException
  627. def connectUNIX(self, address, factory, timeout=30, checkPID=0):
  628. """
  629. Fake L{IReactorUNIX.connectUNIX}, that raises L{_connectException}.
  630. """
  631. raise self._connectException
  632. class NonStreamingProducer(object):
  633. """
  634. A pull producer which writes 10 times only.
  635. """
  636. counter = 0
  637. stopped = False
  638. def __init__(self, consumer):
  639. self.consumer = consumer
  640. self.result = Deferred()
  641. def resumeProducing(self):
  642. """
  643. Write the counter value once.
  644. """
  645. if self.consumer is None or self.counter >= 10:
  646. raise RuntimeError("BUG: resume after unregister/stop.")
  647. else:
  648. self.consumer.write(intToBytes(self.counter))
  649. self.counter += 1
  650. if self.counter == 10:
  651. self.consumer.unregisterProducer()
  652. self._done()
  653. def pauseProducing(self):
  654. """
  655. An implementation of C{IPushProducer.pauseProducing}. This should never
  656. be called on a pull producer, so this just raises an error.
  657. """
  658. raise RuntimeError("BUG: pause should never be called.")
  659. def _done(self):
  660. """
  661. Fire a L{Deferred} so that users can wait for this to complete.
  662. """
  663. self.consumer = None
  664. d = self.result
  665. del self.result
  666. d.callback(None)
  667. def stopProducing(self):
  668. """
  669. Stop all production.
  670. """
  671. self.stopped = True
  672. self._done()
  673. def waitUntilAllDisconnected(reactor, protocols):
  674. """
  675. Take a list of disconnecting protocols, callback a L{Deferred} when they're
  676. all done.
  677. This is a hack to make some older tests less flaky, as
  678. L{ITransport.loseConnection} is not atomic on all reactors (for example,
  679. the CoreFoundation, which sometimes takes a reactor turn for CFSocket to
  680. realise). New tests should either not use real sockets in testing, or take
  681. the advice in
  682. I{https://jml.io/pages/how-to-disconnect-in-twisted-really.html} to heart.
  683. @param reactor: The reactor to schedule the checks on.
  684. @type reactor: L{IReactorTime}
  685. @param protocols: The protocols to wait for disconnecting.
  686. @type protocols: A L{list} of L{IProtocol}s.
  687. """
  688. lc = None
  689. def _check():
  690. if not True in [x.transport.connected for x in protocols]:
  691. lc.stop()
  692. lc = task.LoopingCall(_check)
  693. lc.clock = reactor
  694. return lc.start(0.01, now=True)