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.

connectionmixins.py 20KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594
  1. # -*- test-case-name: twisted.internet.test.test_tcp -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Various helpers for tests for connection-oriented transports.
  6. """
  7. import socket
  8. from gc import collect
  9. from typing import Optional
  10. from weakref import ref
  11. from zope.interface.verify import verifyObject
  12. from twisted.internet.defer import Deferred, gatherResults
  13. from twisted.internet.interfaces import IConnector, IReactorFDSet
  14. from twisted.internet.protocol import ClientFactory, Protocol, ServerFactory
  15. from twisted.internet.test.reactormixins import needsRunningReactor
  16. from twisted.python import context, log
  17. from twisted.python.failure import Failure
  18. from twisted.python.log import ILogContext, err, msg
  19. from twisted.python.runtime import platform
  20. from twisted.test.test_tcp import ClosingProtocol
  21. from twisted.trial.unittest import SkipTest
  22. def findFreePort(interface="127.0.0.1", family=socket.AF_INET, type=socket.SOCK_STREAM):
  23. """
  24. Ask the platform to allocate a free port on the specified interface, then
  25. release the socket and return the address which was allocated.
  26. @param interface: The local address to try to bind the port on.
  27. @type interface: C{str}
  28. @param type: The socket type which will use the resulting port.
  29. @return: A two-tuple of address and port, like that returned by
  30. L{socket.getsockname}.
  31. """
  32. addr = socket.getaddrinfo(interface, 0)[0][4]
  33. probe = socket.socket(family, type)
  34. try:
  35. probe.bind(addr)
  36. if family == socket.AF_INET6:
  37. sockname = probe.getsockname()
  38. hostname = socket.getnameinfo(
  39. sockname, socket.NI_NUMERICHOST | socket.NI_NUMERICSERV
  40. )[0]
  41. return (hostname, sockname[1])
  42. else:
  43. return probe.getsockname()
  44. finally:
  45. probe.close()
  46. class ConnectableProtocol(Protocol):
  47. """
  48. A protocol to be used with L{runProtocolsWithReactor}.
  49. The protocol and its pair should eventually disconnect from each other.
  50. @ivar reactor: The reactor used in this test.
  51. @ivar disconnectReason: The L{Failure} passed to C{connectionLost}.
  52. @ivar _done: A L{Deferred} which will be fired when the connection is
  53. lost.
  54. """
  55. disconnectReason = None
  56. def _setAttributes(self, reactor, done):
  57. """
  58. Set attributes on the protocol that are known only externally; this
  59. will be called by L{runProtocolsWithReactor} when this protocol is
  60. instantiated.
  61. @param reactor: The reactor used in this test.
  62. @param done: A L{Deferred} which will be fired when the connection is
  63. lost.
  64. """
  65. self.reactor = reactor
  66. self._done = done
  67. def connectionLost(self, reason):
  68. self.disconnectReason = reason
  69. self._done.callback(None)
  70. del self._done
  71. class EndpointCreator:
  72. """
  73. Create client and server endpoints that know how to connect to each other.
  74. """
  75. def server(self, reactor):
  76. """
  77. Return an object providing C{IStreamServerEndpoint} for use in creating
  78. a server to use to establish the connection type to be tested.
  79. """
  80. raise NotImplementedError()
  81. def client(self, reactor, serverAddress):
  82. """
  83. Return an object providing C{IStreamClientEndpoint} for use in creating
  84. a client to use to establish the connection type to be tested.
  85. """
  86. raise NotImplementedError()
  87. class _SingleProtocolFactory(ClientFactory):
  88. """
  89. Factory to be used by L{runProtocolsWithReactor}.
  90. It always returns the same protocol (i.e. is intended for only a single
  91. connection).
  92. """
  93. def __init__(self, protocol):
  94. self._protocol = protocol
  95. def buildProtocol(self, addr):
  96. return self._protocol
  97. def runProtocolsWithReactor(
  98. reactorBuilder, serverProtocol, clientProtocol, endpointCreator
  99. ):
  100. """
  101. Connect two protocols using endpoints and a new reactor instance.
  102. A new reactor will be created and run, with the client and server protocol
  103. instances connected to each other using the given endpoint creator. The
  104. protocols should run through some set of tests, then disconnect; when both
  105. have disconnected the reactor will be stopped and the function will
  106. return.
  107. @param reactorBuilder: A L{ReactorBuilder} instance.
  108. @param serverProtocol: A L{ConnectableProtocol} that will be the server.
  109. @param clientProtocol: A L{ConnectableProtocol} that will be the client.
  110. @param endpointCreator: An instance of L{EndpointCreator}.
  111. @return: The reactor run by this test.
  112. """
  113. reactor = reactorBuilder.buildReactor()
  114. serverProtocol._setAttributes(reactor, Deferred())
  115. clientProtocol._setAttributes(reactor, Deferred())
  116. serverFactory = _SingleProtocolFactory(serverProtocol)
  117. clientFactory = _SingleProtocolFactory(clientProtocol)
  118. # Listen on a port:
  119. serverEndpoint = endpointCreator.server(reactor)
  120. d = serverEndpoint.listen(serverFactory)
  121. # Connect to the port:
  122. def gotPort(p):
  123. clientEndpoint = endpointCreator.client(reactor, p.getHost())
  124. return clientEndpoint.connect(clientFactory)
  125. d.addCallback(gotPort)
  126. # Stop reactor when both connections are lost:
  127. def failed(result):
  128. log.err(result, "Connection setup failed.")
  129. disconnected = gatherResults([serverProtocol._done, clientProtocol._done])
  130. d.addCallback(lambda _: disconnected)
  131. d.addErrback(failed)
  132. d.addCallback(lambda _: needsRunningReactor(reactor, reactor.stop))
  133. reactorBuilder.runReactor(reactor)
  134. return reactor
  135. def _getWriters(reactor):
  136. """
  137. Like L{IReactorFDSet.getWriters}, but with support for IOCP reactor as
  138. well.
  139. """
  140. if IReactorFDSet.providedBy(reactor):
  141. return reactor.getWriters()
  142. elif "IOCP" in reactor.__class__.__name__:
  143. return reactor.handles
  144. else:
  145. # Cannot tell what is going on.
  146. raise Exception(f"Cannot find writers on {reactor!r}")
  147. class _AcceptOneClient(ServerFactory):
  148. """
  149. This factory fires a L{Deferred} with a protocol instance shortly after it
  150. is constructed (hopefully long enough afterwards so that it has been
  151. connected to a transport).
  152. @ivar reactor: The reactor used to schedule the I{shortly}.
  153. @ivar result: A L{Deferred} which will be fired with the protocol instance.
  154. """
  155. def __init__(self, reactor, result):
  156. self.reactor = reactor
  157. self.result = result
  158. def buildProtocol(self, addr):
  159. protocol = ServerFactory.buildProtocol(self, addr)
  160. self.reactor.callLater(0, self.result.callback, protocol)
  161. return protocol
  162. class _SimplePullProducer:
  163. """
  164. A pull producer which writes one byte whenever it is resumed. For use by
  165. C{test_unregisterProducerAfterDisconnect}.
  166. """
  167. def __init__(self, consumer):
  168. self.consumer = consumer
  169. def stopProducing(self):
  170. pass
  171. def resumeProducing(self):
  172. log.msg("Producer.resumeProducing")
  173. self.consumer.write(b"x")
  174. class Stop(ClientFactory):
  175. """
  176. A client factory which stops a reactor when a connection attempt fails.
  177. """
  178. failReason = None
  179. def __init__(self, reactor):
  180. self.reactor = reactor
  181. def clientConnectionFailed(self, connector, reason):
  182. self.failReason = reason
  183. msg(f"Stop(CF) cCFailed: {reason.getErrorMessage()}")
  184. self.reactor.stop()
  185. class ClosingLaterProtocol(ConnectableProtocol):
  186. """
  187. ClosingLaterProtocol exchanges one byte with its peer and then disconnects
  188. itself. This is mostly a work-around for the fact that connectionMade is
  189. called before the SSL handshake has completed.
  190. """
  191. def __init__(self, onConnectionLost):
  192. self.lostConnectionReason = None
  193. self.onConnectionLost = onConnectionLost
  194. def connectionMade(self):
  195. msg("ClosingLaterProtocol.connectionMade")
  196. def dataReceived(self, bytes):
  197. msg(f"ClosingLaterProtocol.dataReceived {bytes!r}")
  198. self.transport.loseConnection()
  199. def connectionLost(self, reason):
  200. msg("ClosingLaterProtocol.connectionLost")
  201. self.lostConnectionReason = reason
  202. self.onConnectionLost.callback(self)
  203. class ConnectionTestsMixin:
  204. """
  205. This mixin defines test methods which should apply to most L{ITransport}
  206. implementations.
  207. """
  208. endpoints: Optional[EndpointCreator] = None
  209. def test_logPrefix(self):
  210. """
  211. Client and server transports implement L{ILoggingContext.logPrefix} to
  212. return a message reflecting the protocol they are running.
  213. """
  214. class CustomLogPrefixProtocol(ConnectableProtocol):
  215. def __init__(self, prefix):
  216. self._prefix = prefix
  217. self.system = None
  218. def connectionMade(self):
  219. self.transport.write(b"a")
  220. def logPrefix(self):
  221. return self._prefix
  222. def dataReceived(self, bytes):
  223. self.system = context.get(ILogContext)["system"]
  224. self.transport.write(b"b")
  225. # Only close connection if both sides have received data, so
  226. # that both sides have system set.
  227. if b"b" in bytes:
  228. self.transport.loseConnection()
  229. client = CustomLogPrefixProtocol("Custom Client")
  230. server = CustomLogPrefixProtocol("Custom Server")
  231. runProtocolsWithReactor(self, server, client, self.endpoints)
  232. self.assertIn("Custom Client", client.system)
  233. self.assertIn("Custom Server", server.system)
  234. def test_writeAfterDisconnect(self):
  235. """
  236. After a connection is disconnected, L{ITransport.write} and
  237. L{ITransport.writeSequence} are no-ops.
  238. """
  239. reactor = self.buildReactor()
  240. finished = []
  241. serverConnectionLostDeferred = Deferred()
  242. protocol = lambda: ClosingLaterProtocol(serverConnectionLostDeferred)
  243. portDeferred = self.endpoints.server(reactor).listen(
  244. ServerFactory.forProtocol(protocol)
  245. )
  246. def listening(port):
  247. msg(f"Listening on {port.getHost()!r}")
  248. endpoint = self.endpoints.client(reactor, port.getHost())
  249. lostConnectionDeferred = Deferred()
  250. protocol = lambda: ClosingLaterProtocol(lostConnectionDeferred)
  251. client = endpoint.connect(ClientFactory.forProtocol(protocol))
  252. def write(proto):
  253. msg(f"About to write to {proto!r}")
  254. proto.transport.write(b"x")
  255. client.addCallbacks(write, lostConnectionDeferred.errback)
  256. def disconnected(proto):
  257. msg(f"{proto!r} disconnected")
  258. proto.transport.write(b"some bytes to get lost")
  259. proto.transport.writeSequence([b"some", b"more"])
  260. finished.append(True)
  261. lostConnectionDeferred.addCallback(disconnected)
  262. serverConnectionLostDeferred.addCallback(disconnected)
  263. return gatherResults([lostConnectionDeferred, serverConnectionLostDeferred])
  264. def onListen():
  265. portDeferred.addCallback(listening)
  266. portDeferred.addErrback(err)
  267. portDeferred.addCallback(lambda ignored: reactor.stop())
  268. needsRunningReactor(reactor, onListen)
  269. self.runReactor(reactor)
  270. self.assertEqual(finished, [True, True])
  271. def test_protocolGarbageAfterLostConnection(self):
  272. """
  273. After the connection a protocol is being used for is closed, the
  274. reactor discards all of its references to the protocol.
  275. """
  276. lostConnectionDeferred = Deferred()
  277. clientProtocol = ClosingLaterProtocol(lostConnectionDeferred)
  278. clientRef = ref(clientProtocol)
  279. reactor = self.buildReactor()
  280. portDeferred = self.endpoints.server(reactor).listen(
  281. ServerFactory.forProtocol(Protocol)
  282. )
  283. def listening(port):
  284. msg(f"Listening on {port.getHost()!r}")
  285. endpoint = self.endpoints.client(reactor, port.getHost())
  286. client = endpoint.connect(ClientFactory.forProtocol(lambda: clientProtocol))
  287. def disconnect(proto):
  288. msg(f"About to disconnect {proto!r}")
  289. proto.transport.loseConnection()
  290. client.addCallback(disconnect)
  291. client.addErrback(lostConnectionDeferred.errback)
  292. return lostConnectionDeferred
  293. def onListening():
  294. portDeferred.addCallback(listening)
  295. portDeferred.addErrback(err)
  296. portDeferred.addBoth(lambda ignored: reactor.stop())
  297. needsRunningReactor(reactor, onListening)
  298. self.runReactor(reactor)
  299. # Drop the reference and get the garbage collector to tell us if there
  300. # are no references to the protocol instance left in the reactor.
  301. clientProtocol = None
  302. collect()
  303. self.assertIsNone(clientRef())
  304. class LogObserverMixin:
  305. """
  306. Mixin for L{TestCase} subclasses which want to observe log events.
  307. """
  308. def observe(self):
  309. loggedMessages = []
  310. log.addObserver(loggedMessages.append)
  311. self.addCleanup(log.removeObserver, loggedMessages.append)
  312. return loggedMessages
  313. class BrokenContextFactory:
  314. """
  315. A context factory with a broken C{getContext} method, for exercising the
  316. error handling for such a case.
  317. """
  318. message = "Some path was wrong maybe"
  319. def getContext(self):
  320. raise ValueError(self.message)
  321. class StreamClientTestsMixin:
  322. """
  323. This mixin defines tests applicable to SOCK_STREAM client implementations.
  324. This must be mixed in to a L{ReactorBuilder
  325. <twisted.internet.test.reactormixins.ReactorBuilder>} subclass, as it
  326. depends on several of its methods.
  327. Then the methods C{connect} and C{listen} must defined, defining a client
  328. and a server communicating with each other.
  329. """
  330. def test_interface(self):
  331. """
  332. The C{connect} method returns an object providing L{IConnector}.
  333. """
  334. reactor = self.buildReactor()
  335. connector = self.connect(reactor, ClientFactory())
  336. self.assertTrue(verifyObject(IConnector, connector))
  337. def test_clientConnectionFailedStopsReactor(self):
  338. """
  339. The reactor can be stopped by a client factory's
  340. C{clientConnectionFailed} method.
  341. """
  342. reactor = self.buildReactor()
  343. needsRunningReactor(reactor, lambda: self.connect(reactor, Stop(reactor)))
  344. self.runReactor(reactor)
  345. def test_connectEvent(self):
  346. """
  347. This test checks that we correctly get notifications event for a
  348. client. This ought to prevent a regression under Windows using the
  349. GTK2 reactor. See #3925.
  350. """
  351. reactor = self.buildReactor()
  352. self.listen(reactor, ServerFactory.forProtocol(Protocol))
  353. connected = []
  354. class CheckConnection(Protocol):
  355. def connectionMade(self):
  356. connected.append(self)
  357. reactor.stop()
  358. clientFactory = Stop(reactor)
  359. clientFactory.protocol = CheckConnection
  360. needsRunningReactor(reactor, lambda: self.connect(reactor, clientFactory))
  361. reactor.run()
  362. self.assertTrue(connected)
  363. def test_unregisterProducerAfterDisconnect(self):
  364. """
  365. If a producer is unregistered from a transport after the transport has
  366. been disconnected (by the peer) and after C{loseConnection} has been
  367. called, the transport is not re-added to the reactor as a writer as
  368. would be necessary if the transport were still connected.
  369. """
  370. reactor = self.buildReactor()
  371. self.listen(reactor, ServerFactory.forProtocol(ClosingProtocol))
  372. finished = Deferred()
  373. finished.addErrback(log.err)
  374. finished.addCallback(lambda ign: reactor.stop())
  375. writing = []
  376. class ClientProtocol(Protocol):
  377. """
  378. Protocol to connect, register a producer, try to lose the
  379. connection, wait for the server to disconnect from us, and then
  380. unregister the producer.
  381. """
  382. def connectionMade(self):
  383. log.msg("ClientProtocol.connectionMade")
  384. self.transport.registerProducer(
  385. _SimplePullProducer(self.transport), False
  386. )
  387. self.transport.loseConnection()
  388. def connectionLost(self, reason):
  389. log.msg("ClientProtocol.connectionLost")
  390. self.unregister()
  391. writing.append(self.transport in _getWriters(reactor))
  392. finished.callback(None)
  393. def unregister(self):
  394. log.msg("ClientProtocol unregister")
  395. self.transport.unregisterProducer()
  396. clientFactory = ClientFactory()
  397. clientFactory.protocol = ClientProtocol
  398. self.connect(reactor, clientFactory)
  399. self.runReactor(reactor)
  400. self.assertFalse(writing[0], "Transport was writing after unregisterProducer.")
  401. def test_disconnectWhileProducing(self):
  402. """
  403. If C{loseConnection} is called while a producer is registered with the
  404. transport, the connection is closed after the producer is unregistered.
  405. """
  406. reactor = self.buildReactor()
  407. # For some reason, pyobject/pygtk will not deliver the close
  408. # notification that should happen after the unregisterProducer call in
  409. # this test. The selectable is in the write notification set, but no
  410. # notification ever arrives. Probably for the same reason #5233 led
  411. # win32eventreactor to be broken.
  412. skippedReactors = ["Glib2Reactor", "Gtk2Reactor"]
  413. reactorClassName = reactor.__class__.__name__
  414. if reactorClassName in skippedReactors and platform.isWindows():
  415. raise SkipTest(
  416. "A pygobject/pygtk bug disables this functionality " "on Windows."
  417. )
  418. class Producer:
  419. def resumeProducing(self):
  420. log.msg("Producer.resumeProducing")
  421. self.listen(reactor, ServerFactory.forProtocol(Protocol))
  422. finished = Deferred()
  423. finished.addErrback(log.err)
  424. finished.addCallback(lambda ign: reactor.stop())
  425. class ClientProtocol(Protocol):
  426. """
  427. Protocol to connect, register a producer, try to lose the
  428. connection, unregister the producer, and wait for the connection to
  429. actually be lost.
  430. """
  431. def connectionMade(self):
  432. log.msg("ClientProtocol.connectionMade")
  433. self.transport.registerProducer(Producer(), False)
  434. self.transport.loseConnection()
  435. # Let the reactor tick over, in case synchronously calling
  436. # loseConnection and then unregisterProducer is the same as
  437. # synchronously calling unregisterProducer and then
  438. # loseConnection (as it is in several reactors).
  439. reactor.callLater(0, reactor.callLater, 0, self.unregister)
  440. def unregister(self):
  441. log.msg("ClientProtocol unregister")
  442. self.transport.unregisterProducer()
  443. # This should all be pretty quick. Fail the test
  444. # if we don't get a connectionLost event really
  445. # soon.
  446. reactor.callLater(
  447. 1.0, finished.errback, Failure(Exception("Connection was not lost"))
  448. )
  449. def connectionLost(self, reason):
  450. log.msg("ClientProtocol.connectionLost")
  451. finished.callback(None)
  452. clientFactory = ClientFactory()
  453. clientFactory.protocol = ClientProtocol
  454. self.connect(reactor, clientFactory)
  455. self.runReactor(reactor)
  456. # If the test failed, we logged an error already and trial
  457. # will catch it.