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_udp.py 27KB

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  1. # -*- test-case-name: twisted.test.test_udp -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Tests for implementations of L{IReactorUDP} and L{IReactorMulticast}.
  6. """
  7. import os
  8. from unittest import skipIf
  9. from twisted.internet import defer, error, interfaces, protocol, reactor, udp
  10. from twisted.internet.defer import Deferred, gatherResults, maybeDeferred
  11. from twisted.python import runtime
  12. from twisted.trial.unittest import TestCase
  13. class Mixin:
  14. started = 0
  15. stopped = 0
  16. startedDeferred = None
  17. def __init__(self):
  18. self.packets = []
  19. def startProtocol(self):
  20. self.started = 1
  21. if self.startedDeferred is not None:
  22. d, self.startedDeferred = self.startedDeferred, None
  23. d.callback(None)
  24. def stopProtocol(self):
  25. self.stopped = 1
  26. class Server(Mixin, protocol.DatagramProtocol):
  27. packetReceived = None
  28. refused = 0
  29. def datagramReceived(self, data, addr):
  30. self.packets.append((data, addr))
  31. if self.packetReceived is not None:
  32. d, self.packetReceived = self.packetReceived, None
  33. d.callback(None)
  34. class Client(Mixin, protocol.ConnectedDatagramProtocol):
  35. packetReceived = None
  36. refused = 0
  37. def datagramReceived(self, data):
  38. self.packets.append(data)
  39. if self.packetReceived is not None:
  40. d, self.packetReceived = self.packetReceived, None
  41. d.callback(None)
  42. def connectionFailed(self, failure):
  43. if self.startedDeferred is not None:
  44. d, self.startedDeferred = self.startedDeferred, None
  45. d.errback(failure)
  46. self.failure = failure
  47. def connectionRefused(self):
  48. if self.startedDeferred is not None:
  49. d, self.startedDeferred = self.startedDeferred, None
  50. d.errback(error.ConnectionRefusedError("yup"))
  51. self.refused = 1
  52. class GoodClient(Server):
  53. def connectionRefused(self):
  54. if self.startedDeferred is not None:
  55. d, self.startedDeferred = self.startedDeferred, None
  56. d.errback(error.ConnectionRefusedError("yup"))
  57. self.refused = 1
  58. class BadClientError(Exception):
  59. """
  60. Raised by BadClient at the end of every datagramReceived call to try and
  61. screw stuff up.
  62. """
  63. class BadClient(protocol.DatagramProtocol):
  64. """
  65. A DatagramProtocol which always raises an exception from datagramReceived.
  66. Used to test error handling behavior in the reactor for that method.
  67. """
  68. d = None
  69. def setDeferred(self, d):
  70. """
  71. Set the Deferred which will be called back when datagramReceived is
  72. called.
  73. """
  74. self.d = d
  75. def datagramReceived(self, bytes, addr):
  76. if self.d is not None:
  77. d, self.d = self.d, None
  78. d.callback(bytes)
  79. raise BadClientError("Application code is very buggy!")
  80. @skipIf(not interfaces.IReactorUDP(reactor, None), "This reactor does not support UDP")
  81. class UDPTests(TestCase):
  82. def test_oldAddress(self):
  83. """
  84. The C{type} of the host address of a listening L{DatagramProtocol}'s
  85. transport is C{"UDP"}.
  86. """
  87. server = Server()
  88. d = server.startedDeferred = defer.Deferred()
  89. p = reactor.listenUDP(0, server, interface="127.0.0.1")
  90. def cbStarted(ignored):
  91. addr = p.getHost()
  92. self.assertEqual(addr.type, "UDP")
  93. return p.stopListening()
  94. return d.addCallback(cbStarted)
  95. def test_startStop(self):
  96. """
  97. The L{DatagramProtocol}'s C{startProtocol} and C{stopProtocol}
  98. methods are called when its transports starts and stops listening,
  99. respectively.
  100. """
  101. server = Server()
  102. d = server.startedDeferred = defer.Deferred()
  103. port1 = reactor.listenUDP(0, server, interface="127.0.0.1")
  104. def cbStarted(ignored):
  105. self.assertEqual(server.started, 1)
  106. self.assertEqual(server.stopped, 0)
  107. return port1.stopListening()
  108. def cbStopped(ignored):
  109. self.assertEqual(server.stopped, 1)
  110. return d.addCallback(cbStarted).addCallback(cbStopped)
  111. def test_rebind(self):
  112. """
  113. Re-listening with the same L{DatagramProtocol} re-invokes the
  114. C{startProtocol} callback.
  115. """
  116. server = Server()
  117. d = server.startedDeferred = defer.Deferred()
  118. p = reactor.listenUDP(0, server, interface="127.0.0.1")
  119. def cbStarted(ignored, port):
  120. return port.stopListening()
  121. def cbStopped(ignored):
  122. d = server.startedDeferred = defer.Deferred()
  123. p = reactor.listenUDP(0, server, interface="127.0.0.1")
  124. return d.addCallback(cbStarted, p)
  125. return d.addCallback(cbStarted, p)
  126. def test_bindError(self):
  127. """
  128. A L{CannotListenError} exception is raised when attempting to bind a
  129. second protocol instance to an already bound port
  130. """
  131. server = Server()
  132. d = server.startedDeferred = defer.Deferred()
  133. port = reactor.listenUDP(0, server, interface="127.0.0.1")
  134. def cbStarted(ignored):
  135. self.assertEqual(port.getHost(), server.transport.getHost())
  136. server2 = Server()
  137. self.assertRaises(
  138. error.CannotListenError,
  139. reactor.listenUDP,
  140. port.getHost().port,
  141. server2,
  142. interface="127.0.0.1",
  143. )
  144. d.addCallback(cbStarted)
  145. def cbFinished(ignored):
  146. return port.stopListening()
  147. d.addCallback(cbFinished)
  148. return d
  149. def test_sendPackets(self):
  150. """
  151. Datagrams can be sent with the transport's C{write} method and
  152. received via the C{datagramReceived} callback method.
  153. """
  154. server = Server()
  155. serverStarted = server.startedDeferred = defer.Deferred()
  156. port1 = reactor.listenUDP(0, server, interface="127.0.0.1")
  157. client = GoodClient()
  158. clientStarted = client.startedDeferred = defer.Deferred()
  159. def cbServerStarted(ignored):
  160. self.port2 = reactor.listenUDP(0, client, interface="127.0.0.1")
  161. return clientStarted
  162. d = serverStarted.addCallback(cbServerStarted)
  163. def cbClientStarted(ignored):
  164. client.transport.connect("127.0.0.1", server.transport.getHost().port)
  165. cAddr = client.transport.getHost()
  166. sAddr = server.transport.getHost()
  167. serverSend = client.packetReceived = defer.Deferred()
  168. server.transport.write(b"hello", (cAddr.host, cAddr.port))
  169. clientWrites = [(b"a",), (b"b", None), (b"c", (sAddr.host, sAddr.port))]
  170. def cbClientSend(ignored):
  171. if clientWrites:
  172. nextClientWrite = server.packetReceived = defer.Deferred()
  173. nextClientWrite.addCallback(cbClientSend)
  174. client.transport.write(*clientWrites.pop(0))
  175. return nextClientWrite
  176. # No one will ever call .errback on either of these Deferreds,
  177. # but there is a non-trivial amount of test code which might
  178. # cause them to fail somehow. So fireOnOneErrback=True.
  179. return defer.DeferredList(
  180. [cbClientSend(None), serverSend], fireOnOneErrback=True
  181. )
  182. d.addCallback(cbClientStarted)
  183. def cbSendsFinished(ignored):
  184. cAddr = client.transport.getHost()
  185. sAddr = server.transport.getHost()
  186. self.assertEqual(client.packets, [(b"hello", (sAddr.host, sAddr.port))])
  187. clientAddr = (cAddr.host, cAddr.port)
  188. self.assertEqual(
  189. server.packets,
  190. [(b"a", clientAddr), (b"b", clientAddr), (b"c", clientAddr)],
  191. )
  192. d.addCallback(cbSendsFinished)
  193. def cbFinished(ignored):
  194. return defer.DeferredList(
  195. [
  196. defer.maybeDeferred(port1.stopListening),
  197. defer.maybeDeferred(self.port2.stopListening),
  198. ],
  199. fireOnOneErrback=True,
  200. )
  201. d.addCallback(cbFinished)
  202. return d
  203. @skipIf(
  204. os.environ.get("INFRASTRUCTURE") == "AZUREPIPELINES",
  205. "Hangs on Pipelines due to firewall",
  206. )
  207. def test_connectionRefused(self):
  208. """
  209. A L{ConnectionRefusedError} exception is raised when a connection
  210. attempt is actively refused by the other end.
  211. Note: This test assumes no one is listening on port 80 UDP.
  212. """
  213. client = GoodClient()
  214. clientStarted = client.startedDeferred = defer.Deferred()
  215. port = reactor.listenUDP(0, client, interface="127.0.0.1")
  216. server = Server()
  217. serverStarted = server.startedDeferred = defer.Deferred()
  218. port2 = reactor.listenUDP(0, server, interface="127.0.0.1")
  219. d = defer.DeferredList([clientStarted, serverStarted], fireOnOneErrback=True)
  220. def cbStarted(ignored):
  221. connectionRefused = client.startedDeferred = defer.Deferred()
  222. client.transport.connect("127.0.0.1", 80)
  223. for i in range(10):
  224. client.transport.write(b"%d" % (i,))
  225. server.transport.write(b"%d" % (i,), ("127.0.0.1", 80))
  226. return self.assertFailure(connectionRefused, error.ConnectionRefusedError)
  227. d.addCallback(cbStarted)
  228. def cbFinished(ignored):
  229. return defer.DeferredList(
  230. [
  231. defer.maybeDeferred(port.stopListening),
  232. defer.maybeDeferred(port2.stopListening),
  233. ],
  234. fireOnOneErrback=True,
  235. )
  236. d.addCallback(cbFinished)
  237. return d
  238. def test_serverReadFailure(self):
  239. """
  240. When a server fails to successfully read a packet the server should
  241. still be able to process future packets.
  242. The IOCP reactor had a historical problem where a failure to read caused
  243. the reactor to ignore any future reads. This test should prevent a regression.
  244. Note: This test assumes no one is listening on port 80 UDP.
  245. """
  246. client = GoodClient()
  247. clientStarted = client.startedDeferred = defer.Deferred()
  248. clientPort = reactor.listenUDP(0, client, interface="127.0.0.1")
  249. test_data_to_send = b"Sending test packet to server"
  250. server = Server()
  251. serverStarted = server.startedDeferred = defer.Deferred()
  252. serverGotData = server.packetReceived = defer.Deferred()
  253. serverPort = reactor.listenUDP(0, server, interface="127.0.0.1")
  254. server_client_started_d = defer.DeferredList(
  255. [clientStarted, serverStarted], fireOnOneErrback=True
  256. )
  257. def cbClientAndServerStarted(ignored):
  258. # Server has started. Now the server can send a
  259. # packet to a random port no one is listening on. On windows, for example, this
  260. # will cause an ICMP message to come back on the port telling us no one is listening.
  261. # We need to be able to gracefully handle this situation and continue processing
  262. # requests.
  263. server.transport.write(
  264. b"write to port no one is listening to", ("127.0.0.1", 80)
  265. )
  266. client.transport.write(
  267. test_data_to_send, ("127.0.0.1", serverPort._realPortNumber)
  268. )
  269. server_client_started_d.addCallback(cbClientAndServerStarted)
  270. all_data_sent = defer.DeferredList(
  271. [server_client_started_d, serverGotData], fireOnOneErrback=True
  272. )
  273. def verify_server_got_data(ignored):
  274. self.assertEqual(server.packets[0][0], test_data_to_send)
  275. all_data_sent.addCallback(verify_server_got_data)
  276. def cleanup(ignored):
  277. return defer.DeferredList(
  278. [
  279. defer.maybeDeferred(clientPort.stopListening),
  280. defer.maybeDeferred(serverPort.stopListening),
  281. ],
  282. fireOnOneErrback=True,
  283. )
  284. all_data_sent.addCallback(cleanup)
  285. return all_data_sent
  286. def test_badConnect(self):
  287. """
  288. A call to the transport's connect method fails with an
  289. L{InvalidAddressError} when a non-IP address is passed as the host
  290. value.
  291. A call to a transport's connect method fails with a L{RuntimeError}
  292. when the transport is already connected.
  293. """
  294. client = GoodClient()
  295. port = reactor.listenUDP(0, client, interface="127.0.0.1")
  296. self.assertRaises(
  297. error.InvalidAddressError, client.transport.connect, "localhost", 80
  298. )
  299. client.transport.connect("127.0.0.1", 80)
  300. self.assertRaises(RuntimeError, client.transport.connect, "127.0.0.1", 80)
  301. return port.stopListening()
  302. def test_datagramReceivedError(self):
  303. """
  304. When datagramReceived raises an exception it is logged but the port
  305. is not disconnected.
  306. """
  307. finalDeferred = defer.Deferred()
  308. def cbCompleted(ign):
  309. """
  310. Flush the exceptions which the reactor should have logged and make
  311. sure they're actually there.
  312. """
  313. errs = self.flushLoggedErrors(BadClientError)
  314. self.assertEqual(
  315. len(errs), 2, "Incorrectly found %d errors, expected 2" % (len(errs),)
  316. )
  317. finalDeferred.addCallback(cbCompleted)
  318. client = BadClient()
  319. port = reactor.listenUDP(0, client, interface="127.0.0.1")
  320. def cbCleanup(result):
  321. """
  322. Disconnect the port we started and pass on whatever was given to us
  323. in case it was a Failure.
  324. """
  325. return defer.maybeDeferred(port.stopListening).addBoth(lambda ign: result)
  326. finalDeferred.addBoth(cbCleanup)
  327. addr = port.getHost()
  328. # UDP is not reliable. Try to send as many as 60 packets before giving
  329. # up. Conceivably, all sixty could be lost, but they probably won't be
  330. # unless all UDP traffic is being dropped, and then the rest of these
  331. # UDP tests will likely fail as well. Ideally, this test (and probably
  332. # others) wouldn't even use actual UDP traffic: instead, they would
  333. # stub out the socket with a fake one which could be made to behave in
  334. # whatever way the test desires. Unfortunately, this is hard because
  335. # of differences in various reactor implementations.
  336. attempts = list(range(60))
  337. succeededAttempts = []
  338. def makeAttempt():
  339. """
  340. Send one packet to the listening BadClient. Set up a 0.1 second
  341. timeout to do re-transmits in case the packet is dropped. When two
  342. packets have been received by the BadClient, stop sending and let
  343. the finalDeferred's callbacks do some assertions.
  344. """
  345. if not attempts:
  346. try:
  347. self.fail("Not enough packets received")
  348. except Exception:
  349. finalDeferred.errback()
  350. self.failIfIdentical(
  351. client.transport, None, "UDP Protocol lost its transport"
  352. )
  353. packet = b"%d" % (attempts.pop(0),)
  354. packetDeferred = defer.Deferred()
  355. client.setDeferred(packetDeferred)
  356. client.transport.write(packet, (addr.host, addr.port))
  357. def cbPacketReceived(packet):
  358. """
  359. A packet arrived. Cancel the timeout for it, record it, and
  360. maybe finish the test.
  361. """
  362. timeoutCall.cancel()
  363. succeededAttempts.append(packet)
  364. if len(succeededAttempts) == 2:
  365. # The second error has not yet been logged, since the
  366. # exception which causes it hasn't even been raised yet.
  367. # Give the datagramReceived call a chance to finish, then
  368. # let the test finish asserting things.
  369. reactor.callLater(0, finalDeferred.callback, None)
  370. else:
  371. makeAttempt()
  372. def ebPacketTimeout(err):
  373. """
  374. The packet wasn't received quickly enough. Try sending another
  375. one. It doesn't matter if the packet for which this was the
  376. timeout eventually arrives: makeAttempt throws away the
  377. Deferred on which this function is the errback, so when
  378. datagramReceived callbacks, so it won't be on this Deferred, so
  379. it won't raise an AlreadyCalledError.
  380. """
  381. makeAttempt()
  382. packetDeferred.addCallbacks(cbPacketReceived, ebPacketTimeout)
  383. packetDeferred.addErrback(finalDeferred.errback)
  384. timeoutCall = reactor.callLater(
  385. 0.1,
  386. packetDeferred.errback,
  387. error.TimeoutError("Timed out in testDatagramReceivedError"),
  388. )
  389. makeAttempt()
  390. return finalDeferred
  391. def test_NoWarningOnBroadcast(self):
  392. """
  393. C{'<broadcast>'} is an alternative way to say C{'255.255.255.255'}
  394. ({socket.gethostbyname("<broadcast>")} returns C{'255.255.255.255'}),
  395. so because it becomes a valid IP address, no deprecation warning about
  396. passing hostnames to L{twisted.internet.udp.Port.write} needs to be
  397. emitted by C{write()} in this case.
  398. """
  399. class fakeSocket:
  400. def sendto(self, foo, bar):
  401. pass
  402. p = udp.Port(0, Server())
  403. p.socket = fakeSocket()
  404. p.write(b"test", ("<broadcast>", 1234))
  405. warnings = self.flushWarnings([self.test_NoWarningOnBroadcast])
  406. self.assertEqual(len(warnings), 0)
  407. @skipIf(not interfaces.IReactorUDP(reactor, None), "This reactor does not support UDP")
  408. class ReactorShutdownInteractionTests(TestCase):
  409. """Test reactor shutdown interaction"""
  410. if not interfaces.IReactorUDP(reactor, None):
  411. skip = "This reactor does not support UDP"
  412. def setUp(self):
  413. """Start a UDP port"""
  414. self.server = Server()
  415. self.port = reactor.listenUDP(0, self.server, interface="127.0.0.1")
  416. def tearDown(self):
  417. """Stop the UDP port"""
  418. return self.port.stopListening()
  419. def testShutdownFromDatagramReceived(self):
  420. """Test reactor shutdown while in a recvfrom() loop"""
  421. # udp.Port's doRead calls recvfrom() in a loop, as an optimization.
  422. # It is important this loop terminate under various conditions.
  423. # Previously, if datagramReceived synchronously invoked
  424. # reactor.stop(), under certain reactors, the Port's socket would
  425. # synchronously disappear, causing an AttributeError inside that
  426. # loop. This was mishandled, causing the loop to spin forever.
  427. # This test is primarily to ensure that the loop never spins
  428. # forever.
  429. finished = defer.Deferred()
  430. pr = self.server.packetReceived = defer.Deferred()
  431. def pktRece(ignored):
  432. # Simulate reactor.stop() behavior :(
  433. self.server.transport.connectionLost()
  434. # Then delay this Deferred chain until the protocol has been
  435. # disconnected, as the reactor should do in an error condition
  436. # such as we are inducing. This is very much a whitebox test.
  437. reactor.callLater(0, finished.callback, None)
  438. pr.addCallback(pktRece)
  439. def flushErrors(ignored):
  440. # We are breaking abstraction and calling private APIs, any
  441. # number of horrible errors might occur. As long as the reactor
  442. # doesn't hang, this test is satisfied. (There may be room for
  443. # another, stricter test.)
  444. self.flushLoggedErrors()
  445. finished.addCallback(flushErrors)
  446. self.server.transport.write(
  447. b"\0" * 64, ("127.0.0.1", self.server.transport.getHost().port)
  448. )
  449. return finished
  450. @skipIf(
  451. not interfaces.IReactorMulticast(reactor, None),
  452. "This reactor does not support multicast",
  453. )
  454. class MulticastTests(TestCase):
  455. if (
  456. os.environ.get("INFRASTRUCTURE") == "AZUREPIPELINES"
  457. and runtime.platform.isMacOSX()
  458. ):
  459. skip = "Does not work on Azure Pipelines"
  460. if not interfaces.IReactorMulticast(reactor, None):
  461. skip = "This reactor does not support multicast"
  462. def setUp(self):
  463. self.server = Server()
  464. self.client = Client()
  465. # multicast won't work if we listen over loopback, apparently
  466. self.port1 = reactor.listenMulticast(0, self.server)
  467. self.port2 = reactor.listenMulticast(0, self.client)
  468. self.client.transport.connect("127.0.0.1", self.server.transport.getHost().port)
  469. def tearDown(self):
  470. return gatherResults(
  471. [
  472. maybeDeferred(self.port1.stopListening),
  473. maybeDeferred(self.port2.stopListening),
  474. ]
  475. )
  476. def testTTL(self):
  477. for o in self.client, self.server:
  478. self.assertEqual(o.transport.getTTL(), 1)
  479. o.transport.setTTL(2)
  480. self.assertEqual(o.transport.getTTL(), 2)
  481. def test_loopback(self):
  482. """
  483. Test that after loopback mode has been set, multicast packets are
  484. delivered to their sender.
  485. """
  486. self.assertEqual(self.server.transport.getLoopbackMode(), 1)
  487. addr = self.server.transport.getHost()
  488. joined = self.server.transport.joinGroup("225.0.0.250")
  489. def cbJoined(ignored):
  490. d = self.server.packetReceived = Deferred()
  491. self.server.transport.write(b"hello", ("225.0.0.250", addr.port))
  492. return d
  493. joined.addCallback(cbJoined)
  494. def cbPacket(ignored):
  495. self.assertEqual(len(self.server.packets), 1)
  496. self.server.transport.setLoopbackMode(0)
  497. self.assertEqual(self.server.transport.getLoopbackMode(), 0)
  498. self.server.transport.write(b"hello", ("225.0.0.250", addr.port))
  499. # This is fairly lame.
  500. d = Deferred()
  501. reactor.callLater(0, d.callback, None)
  502. return d
  503. joined.addCallback(cbPacket)
  504. def cbNoPacket(ignored):
  505. self.assertEqual(len(self.server.packets), 1)
  506. joined.addCallback(cbNoPacket)
  507. return joined
  508. def test_interface(self):
  509. """
  510. Test C{getOutgoingInterface} and C{setOutgoingInterface}.
  511. """
  512. self.assertEqual(self.client.transport.getOutgoingInterface(), "0.0.0.0")
  513. self.assertEqual(self.server.transport.getOutgoingInterface(), "0.0.0.0")
  514. d1 = self.client.transport.setOutgoingInterface("127.0.0.1")
  515. d2 = self.server.transport.setOutgoingInterface("127.0.0.1")
  516. result = gatherResults([d1, d2])
  517. def cbInterfaces(ignored):
  518. self.assertEqual(self.client.transport.getOutgoingInterface(), "127.0.0.1")
  519. self.assertEqual(self.server.transport.getOutgoingInterface(), "127.0.0.1")
  520. result.addCallback(cbInterfaces)
  521. return result
  522. def test_joinLeave(self):
  523. """
  524. Test that multicast a group can be joined and left.
  525. """
  526. d = self.client.transport.joinGroup("225.0.0.250")
  527. def clientJoined(ignored):
  528. return self.client.transport.leaveGroup("225.0.0.250")
  529. d.addCallback(clientJoined)
  530. def clientLeft(ignored):
  531. return self.server.transport.joinGroup("225.0.0.250")
  532. d.addCallback(clientLeft)
  533. def serverJoined(ignored):
  534. return self.server.transport.leaveGroup("225.0.0.250")
  535. d.addCallback(serverJoined)
  536. return d
  537. # FIXME: https://twistedmatrix.com/trac/ticket/7780
  538. @skipIf(
  539. runtime.platform.isWindows() and not runtime.platform.isVista(),
  540. "Windows' UDP multicast is not yet fully supported.",
  541. )
  542. def test_joinFailure(self):
  543. """
  544. Test that an attempt to join an address which is not a multicast
  545. address fails with L{error.MulticastJoinError}.
  546. """
  547. # 127.0.0.1 is not a multicast address, so joining it should fail.
  548. return self.assertFailure(
  549. self.client.transport.joinGroup("127.0.0.1"), error.MulticastJoinError
  550. )
  551. def test_multicast(self):
  552. """
  553. Test that a multicast group can be joined and messages sent to and
  554. received from it.
  555. """
  556. c = Server()
  557. p = reactor.listenMulticast(0, c)
  558. addr = self.server.transport.getHost()
  559. joined = self.server.transport.joinGroup("225.0.0.250")
  560. def cbJoined(ignored):
  561. d = self.server.packetReceived = Deferred()
  562. c.transport.write(b"hello world", ("225.0.0.250", addr.port))
  563. return d
  564. joined.addCallback(cbJoined)
  565. def cbPacket(ignored):
  566. self.assertEqual(self.server.packets[0][0], b"hello world")
  567. joined.addCallback(cbPacket)
  568. def cleanup(passthrough):
  569. result = maybeDeferred(p.stopListening)
  570. result.addCallback(lambda ign: passthrough)
  571. return result
  572. joined.addCallback(cleanup)
  573. return joined
  574. @skipIf(
  575. runtime.platform.isWindows(),
  576. "on non-linux platforms it appears multiple "
  577. "processes can listen, but not multiple sockets "
  578. "in same process?",
  579. )
  580. def test_multiListen(self):
  581. """
  582. Test that multiple sockets can listen on the same multicast port and
  583. that they both receive multicast messages directed to that address.
  584. """
  585. firstClient = Server()
  586. firstPort = reactor.listenMulticast(0, firstClient, listenMultiple=True)
  587. portno = firstPort.getHost().port
  588. secondClient = Server()
  589. secondPort = reactor.listenMulticast(portno, secondClient, listenMultiple=True)
  590. theGroup = "225.0.0.250"
  591. joined = gatherResults(
  592. [
  593. self.server.transport.joinGroup(theGroup),
  594. firstPort.joinGroup(theGroup),
  595. secondPort.joinGroup(theGroup),
  596. ]
  597. )
  598. def serverJoined(ignored):
  599. d1 = firstClient.packetReceived = Deferred()
  600. d2 = secondClient.packetReceived = Deferred()
  601. firstClient.transport.write(b"hello world", (theGroup, portno))
  602. return gatherResults([d1, d2])
  603. joined.addCallback(serverJoined)
  604. def gotPackets(ignored):
  605. self.assertEqual(firstClient.packets[0][0], b"hello world")
  606. self.assertEqual(secondClient.packets[0][0], b"hello world")
  607. joined.addCallback(gotPackets)
  608. def cleanup(passthrough):
  609. result = gatherResults(
  610. [
  611. maybeDeferred(firstPort.stopListening),
  612. maybeDeferred(secondPort.stopListening),
  613. ]
  614. )
  615. result.addCallback(lambda ign: passthrough)
  616. return result
  617. joined.addBoth(cleanup)
  618. return joined