From dc65b4354d4344a12c89cd60913f25a5f947316f Mon Sep 17 00:00:00 2001 From: Brian Warner Date: Sun, 21 Jun 2015 21:04:33 -0700 Subject: [PATCH] twisted: split allocate_ports() out to util.py so it can be used by downstream projects --- src/wormhole/test/test_twisted.py | 23 ++--------------------- src/wormhole/twisted/util.py | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 21 deletions(-) create mode 100644 src/wormhole/twisted/util.py diff --git a/src/wormhole/test/test_twisted.py b/src/wormhole/test/test_twisted.py index 51be63d..fe016f4 100644 --- a/src/wormhole/test/test_twisted.py +++ b/src/wormhole/test/test_twisted.py @@ -1,34 +1,15 @@ import json from twisted.trial import unittest -from twisted.internet import defer, protocol, endpoints, reactor +from twisted.internet import defer from twisted.application import service from ..servers.relay import RelayServer from ..twisted.transcribe import SymmetricWormhole, UsageError +from ..twisted.util import allocate_ports from .. import __version__ #from twisted.python import log #import sys #log.startLogging(sys.stdout) -def allocate_port(): - ep = endpoints.serverFromString(reactor, "tcp:0:interface=127.0.0.1") - d = ep.listen(protocol.Factory()) - def _listening(lp): - port = lp.getHost().port - d2 = lp.stopListening() - d2.addCallback(lambda _: port) - return d2 - d.addCallback(_listening) - return d - -def allocate_ports(): - d = defer.DeferredList([allocate_port(), allocate_port()]) - def _done(results): - port1 = results[0][1] - port2 = results[1][1] - return (port1, port2) - d.addCallback(_done) - return d - class Basic(unittest.TestCase): def setUp(self): self.sp = service.MultiService() diff --git a/src/wormhole/twisted/util.py b/src/wormhole/twisted/util.py new file mode 100644 index 0000000..182fc34 --- /dev/null +++ b/src/wormhole/twisted/util.py @@ -0,0 +1,21 @@ +from twisted.internet import defer, protocol, endpoints, reactor + +def allocate_port(): + ep = endpoints.serverFromString(reactor, "tcp:0:interface=127.0.0.1") + d = ep.listen(protocol.Factory()) + def _listening(lp): + port = lp.getHost().port + d2 = lp.stopListening() + d2.addCallback(lambda _: port) + return d2 + d.addCallback(_listening) + return d + +def allocate_ports(): + d = defer.DeferredList([allocate_port(), allocate_port()]) + def _done(results): + port1 = results[0][1] + port2 = results[1][1] + return (port1, port2) + d.addCallback(_done) + return d