本文整理汇总了Python中twisted.internet.task.Clock.getDelayedCalls方法的典型用法代码示例。如果您正苦于以下问题:Python Clock.getDelayedCalls方法的具体用法?Python Clock.getDelayedCalls怎么用?Python Clock.getDelayedCalls使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.internet.task.Clock
的用法示例。
在下文中一共展示了Clock.getDelayedCalls方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RLockTests
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import getDelayedCalls [as 别名]
class RLockTests(LockTests):
def setUp(self):
self.lock_class = glocks.RLock
self.resource = 'rlocktests:resource'
self.ttl = 2000.
self.host_info = {
'host': 'localhost',
'port': 6379,
'db': 1
}
self.clock = Clock()
self.lock = self.setup_lock(reactor=self.clock)
self.is_reentrant = True
def test_keep_alive_task(self):
self.lock.acquire()
self.assertIsInstance(
self.lock.keep_alive_task,
glocks.locks.LoopingCall
)
self.assertTrue(self.lock.keep_alive_task.running)
# now test that the progress of time executes the delayed calls
# that the keep_alive_task generates
self.assertEqual(
len(self.clock.getDelayedCalls()),
1
)
delayed_call = self.clock.getDelayedCalls()[0]
# test that the thing to be called is actually the looping call itself
self.assertEqual(
delayed_call.func,
self.lock.keep_alive_task
)
self.assertFalse(delayed_call.called)
self.clock.advance(1)
self.assertTrue(delayed_call.called)
self.assertEqual(
len(self.clock.getDelayedCalls()),
1
)
new_delayed_call = self.clock.getDelayedCalls()[0]
self.assertNotEqual(delayed_call, new_delayed_call)
self.assertFalse(new_delayed_call.called)
def test_keep_alive_interval(self):
self.lock.trigger_keep_alive()
self.assertTrue(
self.lock.keep_alive_task.interval < (
float(self.ttl) / float(self.lock.KEEP_ALIVE_FREQUENCY)
)
)
self.assertTrue(self.lock.keep_alive_task.now)
示例2: test_inactivity
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import getDelayedCalls [as 别名]
def test_inactivity(self):
clock = Clock()
self.inactivityReached = False
def becameInactive():
self.inactivityReached = True
id = InactivityDetector(clock, 5, becameInactive)
# After 3 seconds, not inactive
clock.advance(3)
self.assertFalse(self.inactivityReached)
# Activity happens, pushing out the inactivity threshold
id.activity()
clock.advance(3)
self.assertFalse(self.inactivityReached)
# Time passes without activity
clock.advance(3)
self.assertTrue(self.inactivityReached)
id.stop()
# Verify a timeout of 0 does not ever fire
id = InactivityDetector(clock, 0, becameInactive)
self.assertEquals(clock.getDelayedCalls(), [])
示例3: test_clientConnected
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import getDelayedCalls [as 别名]
def test_clientConnected(self):
"""
When a client connects, the service keeps a reference to the new
protocol and resets the delay.
"""
clock = Clock()
cq, service = self.makeReconnector(clock=clock)
awaitingProtocol = service.whenConnected()
self.assertEqual(clock.getDelayedCalls(), [])
self.assertIdentical(self.successResultOf(awaitingProtocol),
cq.applicationProtocols[0])
示例4: test_retryCancelled
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import getDelayedCalls [as 别名]
def test_retryCancelled(self):
"""
When L{ClientService.stopService} is called while waiting between
connection attempts, the pending reconnection attempt is cancelled and
the service is stopped immediately.
"""
clock = Clock()
cq, service = self.makeReconnector(fireImmediately=False, clock=clock)
cq.connectQueue[0].errback(Exception("no connection"))
d = service.stopService()
self.assertEqual(clock.getDelayedCalls(), [])
self.successResultOf(d)
示例5: test_convergence_stop
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import getDelayedCalls [as 别名]
def test_convergence_stop(self):
"""
A FSM doing convergence that receives a stop input stops when the
convergence iteration finishes.
"""
local_state = NodeState(hostname=u'192.0.2.123')
configuration = Deployment(nodes=frozenset([to_node(local_state)]))
state = DeploymentState(nodes=[local_state])
# Until this Deferred fires the first iteration won't finish:
action = ControllableAction(result=Deferred())
# Only one discovery result is configured, so a second attempt at
# discovery would fail:
deployer = ControllableDeployer(
local_state.hostname, [succeed(local_state)],
[action]
)
client = self.make_amp_client([local_state])
reactor = Clock()
loop = build_convergence_loop_fsm(reactor, deployer)
loop.receive(_ClientStatusUpdate(
client=client, configuration=configuration, state=state))
# Calculating actions happened, action is run, but waits for
# Deferred to be fired... Meanwhile a stop input is received!
loop.receive(ConvergenceLoopInputs.STOP)
# Action finally finishes:
action.result.callback(None)
reactor.advance(1.0)
# work is scheduled:
expected = (
# The actions are calculated
[(local_state, configuration, state)],
# And the result is run
[(NodeStateCommand, dict(state_changes=(local_state,)))],
# The state machine gets to the desired state.
ConvergenceLoopStates.STOPPED,
# And no subsequent work is scheduled to be run.
[],
)
actual = (
deployer.calculate_inputs,
client.calls,
loop.state,
reactor.getDelayedCalls(),
)
self.assertTupleEqual(expected, actual)
示例6: ret
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import getDelayedCalls [as 别名]
def ret():
error = [None]
clock = Clock()
d = f(clock)
@d.addErrback
def on_error(f):
error[0] = f
while True:
time_to_wait = max([0] + [call.getTime() - clock.seconds() for call in clock.getDelayedCalls()])
if time_to_wait == 0:
break
else:
clock.advance(time_to_wait)
if error[0]:
error[0].raiseException()
示例7: APITestsMixin
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import getDelayedCalls [as 别名]
#.........这里部分代码省略.........
If a dataset with the given name is created while the
``/VolumeDriver.Create`` call is in flight, the call does not
result in an error.
"""
name = u"thename"
# Create a dataset out-of-band with matching dataset ID and name
# which the docker plugin won't be able to see.
def create_after_list():
# Clean up the patched version:
del self.flocker_client.list_datasets_configuration
# But first time we're called, we create dataset and lie about
# its existence:
d = self.flocker_client.create_dataset(
self.NODE_A, int(DEFAULT_SIZE.to_Byte()), metadata={NAME_FIELD: name}
)
d.addCallback(lambda _: DatasetsConfiguration(tag=u"1234", datasets={}))
return d
self.flocker_client.list_datasets_configuration = create_after_list
return self.create(name)
def _flush_volume_plugin_reactor_on_endpoint_render(self):
"""
This method patches ``self.app`` so that after any endpoint is
rendered, the reactor used by the volume plugin is advanced repeatedly
until there are no more ``delayedCalls`` pending on the reactor.
"""
real_execute_endpoint = self.app.execute_endpoint
def patched_execute_endpoint(*args, **kwargs):
val = real_execute_endpoint(*args, **kwargs)
while self.volume_plugin_reactor.getDelayedCalls():
pending_calls = self.volume_plugin_reactor.getDelayedCalls()
next_expiration = min(t.getTime() for t in pending_calls)
now = self.volume_plugin_reactor.seconds()
self.volume_plugin_reactor.advance(max(0.0, next_expiration - now))
return val
self.patch(self.app, "execute_endpoint", patched_execute_endpoint)
def test_mount(self):
"""
``/VolumeDriver.Mount`` sets the primary of the dataset with matching
name to the current node and then waits for the dataset to
actually arrive.
"""
name = u"myvol"
dataset_id = uuid4()
mount_id = "".join(random.choice("0123456789abcdef") for n in xrange(64))
# Create dataset on a different node:
d = self.flocker_client.create_dataset(
self.NODE_B, int(DEFAULT_SIZE.to_Byte()), metadata={NAME_FIELD: name}, dataset_id=dataset_id
)
self._flush_volume_plugin_reactor_on_endpoint_render()
# Pretend that it takes 5 seconds for the dataset to get established on
# Node A.
self.volume_plugin_reactor.callLater(5.0, self.flocker_client.synchronize_state)
d.addCallback(
lambda _: self.assertResult(
b"POST",
示例8: SelfHealTests
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import getDelayedCalls [as 别名]
class SelfHealTests(SynchronousTestCase):
"""
Tests for :obj:`SelfHeal`
"""
def setUp(self):
self.clock = Clock()
self.log = mock_log()
self.patch(sh, "get_groups_to_converge", intent_func("ggtc"))
self.patch(sh, "check_and_trigger", lambda t, g: t + g)
self.s = sh.SelfHeal(self.clock, base_dispatcher, "cf", 300.0,
self.log)
self.groups = [
{"tenantId": "t{}".format(i), "groupId": "g{}".format(i)}
for i in range(5)]
def test_setup(self):
"""
``self.s.setup()`` will setup convergences to be triggered over
specified time range
"""
self.s.dispatcher = SequenceDispatcher(
[(("ggtc", "cf"), const(self.groups))])
d = self.s.setup()
self.successResultOf(d)
calls = self.clock.getDelayedCalls()
self.assertEqual(self.s._calls, calls)
for i, c in enumerate(calls):
self.assertEqual(c.getTime(), i * 60)
self.assertEqual(c.func, sh.perform)
self.assertEqual(c.args,
(self.s.dispatcher, "t{}g{}".format(i, i)))
def test_setup_err(self):
"""
``self.s.setup()`` will log any error and return success
"""
self.s.dispatcher = SequenceDispatcher(
[(("ggtc", "cf"), conste(ValueError("h")))])
d = self.s.setup()
self.successResultOf(d)
self.log.err.assert_called_once_with(
CheckFailure(ValueError), "selfheal-setup-err",
otter_service="selfheal")
def test_setup_no_groups(self):
"""
``self.s.setup()`` gets groups and does nothing if there are no groups
"""
self.s.dispatcher = SequenceDispatcher([(("ggtc", "cf"), const([]))])
d = self.s.setup()
self.successResultOf(d)
self.assertEqual(self.s._calls, [])
self.assertEqual(self.clock.getDelayedCalls(), [])
def test_setup_still_active(self):
"""
If there are scheduled calls when perform is called, they are
cancelled and err is logged. Future calls are scheduled as usual
"""
self.clock.advance(-0.6)
call1 = self.clock.callLater(1, noop, None)
call2 = self.clock.callLater(0, noop, None)
call3 = self.clock.callLater(2, noop, None)
self.clock.advance(0.6)
self.s._calls = [call1, call2, call3]
self.s.dispatcher = SequenceDispatcher(
[(("ggtc", "cf"), const(self.groups))])
d = self.s.setup()
self.successResultOf(d)
self.log.err.assert_called_once_with(
matches(IsInstance(RuntimeError)), "selfheal-calls-err", active=2,
otter_service="selfheal")
self.assertFalse(call1.active())
self.assertFalse(call2.active())
示例9: TimeoutTests
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import getDelayedCalls [as 别名]
#.........这里部分代码省略.........
deferred = timeout(self.clock, self.deferred, self.timeout)
self.clock.advance(self.timeout - 1.0)
self.assertNoResult(deferred)
def test_times_out(self):
"""
A deferred that does not fire within the timeout interval is made to
fire with ``CancelledError`` once the timeout interval elapses.
"""
deferred = timeout(self.clock, self.deferred, self.timeout)
self.clock.advance(self.timeout)
self.failureResultOf(deferred, CancelledError)
def test_times_out_with_reason(self):
"""
If a custom reason is passed to ``timeout`` and the Deferred does not
fire within the timeout interval, it is made to fire with the custom
reason once the timeout interval elapses.
"""
reason = CustomException(self.id())
deferred = timeout(self.clock, self.deferred, self.timeout, reason)
self.clock.advance(self.timeout)
self.assertEqual(
reason,
self.failureResultOf(deferred, CustomException).value,
)
def test_doesnt_time_out(self):
"""
A deferred that fires before the timeout is not cancelled by the
timeout.
"""
deferred = timeout(self.clock, self.deferred, self.timeout)
self.clock.advance(self.timeout - 1.0)
self.deferred.callback('Success')
self.assertEqual(self.successResultOf(deferred), 'Success')
def test_doesnt_time_out_failure(self):
"""
A Deferred that fails before the timeout is not cancelled by the
timeout.
"""
deferred = timeout(self.clock, self.deferred, self.timeout)
self.clock.advance(self.timeout - 1.0)
self.deferred.errback(CustomException(self.id()))
self.failureResultOf(deferred, CustomException)
def test_doesnt_time_out_failure_custom_reason(self):
"""
A Deferred that fails before the timeout is not cancelled by the
timeout.
"""
deferred = timeout(
self.clock, self.deferred, self.timeout,
ValueError("This should not appear.")
)
self.clock.advance(self.timeout - 1.0)
self.deferred.errback(CustomException(self.id()))
self.failureResultOf(deferred, CustomException)
def test_advancing_after_success(self):
"""
A Deferred that fires before the timeout continues to succeed after the
timeout has elapsed.
"""
deferred = succeed('Success')
timeout(self.clock, deferred, self.timeout)
self.clock.advance(self.timeout)
self.assertEqual(self.successResultOf(deferred), 'Success')
def test_advancing_after_failure(self):
"""
A Deferred that fires with a failure before the timeout continues to
fail after the timeout has elapsed.
"""
deferred = fail(CustomException(self.id()))
timeout(self.clock, deferred, self.timeout)
self.clock.advance(self.timeout)
self.failureResultOf(deferred, CustomException)
def test_timeout_cleaned_up_on_success(self):
"""
If the deferred is successfully completed before the timeout, the
timeout is not still pending on the reactor.
"""
timeout(self.clock, self.deferred, self.timeout)
self.deferred.callback('Success')
self.assertEqual(self.clock.getDelayedCalls(), [])
def test_timeout_cleaned_up_on_failure(self):
"""
If the deferred is failed before the timeout, the timeout is not still
pending on the reactor.
"""
timeout(self.clock, self.deferred, self.timeout)
self.deferred.errback(CustomException(self.id()))
# We need to handle the errback so that Trial and/or testtools don't
# fail with unhandled errors.
self.addCleanup(self.deferred.addErrback, lambda _: None)
self.assertEqual(self.clock.getDelayedCalls(), [])
示例10: TestPersistenceFileGlue
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import getDelayedCalls [as 别名]
class TestPersistenceFileGlue(unittest.TestCase):
def setUp(self):
self.__clock = Clock()
self.__temp_dir = tempfile.mkdtemp(prefix='shinysdr_test_persistence_tmp')
self.__state_name = os.path.join(self.__temp_dir, 'state')
self.__reset()
def tearDown(self):
self.assertFalse(self.__clock.getDelayedCalls())
shutil.rmtree(self.__temp_dir)
def __reset(self):
"""Recreate the object for write-then-read tests."""
self.__root = ValueAndBlockSpecimen(value='initial')
def __start(self,
get_defaults=lambda _: {'value': 'default'},
**kwargs):
return PersistenceFileGlue(
reactor=self.__clock,
root_object=self.__root,
filename=self.__state_name,
get_defaults=get_defaults,
**kwargs)
def test_no_defaults(self):
self.__start(get_defaults=lambda _: {})
# It would be surprising if this assertion failed; this test is mainly just to test the initialization succeeds
self.assertEqual(self.__root.get_value(), 'initial')
def test_defaults(self):
self.__start()
self.assertEqual(self.__root.get_value(), 'default')
def test_no_persistence(self):
self.__state_name = None
self.__start()
self.assertEqual(self.__root.get_value(), 'default')
def test_persistence(self):
"""Test that state persists."""
pfg = self.__start()
self.__root.set_value('set')
advance_until(self.__clock, pfg.sync(), limit=2)
self.__reset()
self.__start()
self.assertEqual(self.__root.get_value(), 'set') # check persistence
def test_delay_is_present(self):
"""Test that persistence isn't immediate."""
pfg = self.__start()
self.__root.set_value('set')
self.__reset()
self.__start()
self.assertEqual(self.__root.get_value(), 'default') # change not persisted
advance_until(self.__clock, pfg.sync(), limit=2) # clean up clock for tearDown check
def test_broken_state_recovery(self):
pfg = self.__start()
self.__root.set_value(ObjectWhichCannotBePersisted())
try:
advance_until(self.__clock, pfg.sync(), limit=2)
except TypeError: # expected error
pass
self.__reset()
self.__start()
# now we should be back to the default value
self.assertEqual(self.__root.get_value(), 'default')
def test_unparseable_file_recovery(self):
with open(self.__state_name, 'w'):
pass # write empty file
self.__start(_suppress_error_for_test=True)
self.assertEqual(self.__root.get_value(), 'default')
示例11: FakeReactor
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import getDelayedCalls [as 别名]
class FakeReactor(MemoryReactor):
"""A fake reactor to be used in tests. This reactor doesn't actually do
much that's useful yet. It accepts TCP connection setup attempts, but
they will never succeed.
Examples:
>>> import sys
>>> from twisted.internet.abstract import FileDescriptor
>>> from twisted.internet.fdesc import readFromFD, setNonBlocking
>>>
>>> # reactor = proto_helpers.FakeReactor()
>>> reactor = FakeReactor()
>>> f = FileDescriptor(reactor)
>>> f.fileno = sys.__stdout__.fileno
>>> fd = f.fileno()
>>> setNonBlocking(fd)
>>> readFromFD(fd, print)
"""
_DELAY = 1
def __init__(self):
super(FakeReactor, self).__init__()
self._clock = Clock()
reactor.fake = True
msg = 'Attention! Running fake reactor'
logger.debug('%s. Some deferreds may not work as intended.' % msg)
self.running = False
def resolve(self, *args, **kwargs):
"""Return a L{twisted.internet.defer.Deferred} that will resolve a hostname.
"""
pass
def run(self):
"""Fake L{IReactorCore.run}.
"""
self.running = True
def stop(self):
"""Fake L{IReactorCore.stop}.
"""
self.running = False
def crash(self):
"""Fake L{IReactorCore.crash}.
"""
self.running = False
def iterate(self, *args, **kwargs):
"""Fake L{IReactorCore.iterate}.
"""
pass
def fireSystemEvent(self, *args, **kwargs):
"""Fake L{IReactorCore.fireSystemEvent}.
"""
pass
def addSystemEventTrigger(self, *args, **kwargs):
"""Fake L{IReactorCore.addSystemEventTrigger}.
"""
pass
def removeSystemEventTrigger(self, *args, **kwargs):
"""Fake L{IReactorCore.removeSystemEventTrigger}.
"""
pass
def callWhenRunning(self, *args, **kwargs):
"""Fake L{IReactorCore.callWhenRunning}.
"""
pass
def getDelayedCalls(self):
"""Return all the outstanding delayed calls in the system.
"""
return self._clock.getDelayedCalls()
def callLater(self, when, what, *args, **kwargs):
"""Schedule a unit of work to be done later.
"""
delayed = self._clock.callLater(when, what, *args, **kwargs)
self.pump()
return delayed
def pump(self):
"""Perform scheduled work
"""
self._clock.advance(self._DELAY)
示例12: TimeoutTests
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import getDelayedCalls [as 别名]
class TimeoutTests(SynchronousTestCase):
"""
Tests for :py:func:`timeout`.
"""
def setUp(self):
"""Initialize testing helper variables."""
self._deferred = Deferred()
self._timeout = 1.0
self._clock = Clock()
def _execute_timeout(self):
"""Execute the timeout."""
timeout(self._clock, self._deferred, self._timeout)
def test_times_out(self):
"""
A deferred that never fires is timed out at the correct time using the
timeout function, and concludes with a CancelledError failure.
"""
self._execute_timeout()
self._clock.advance(self._timeout - 0.1)
self.assertFalse(self._deferred.called)
self._clock.advance(0.1)
self.assertTrue(self._deferred.called)
self.failureResultOf(self._deferred, CancelledError)
def test_doesnt_time_out(self):
"""
A deferred that fires before the timeout is not cancelled by the
timeout.
"""
self._execute_timeout()
self._clock.advance(self._timeout - 0.1)
self.assertFalse(self._deferred.called)
self._deferred.callback('Success')
self.assertTrue(self._deferred.called)
self.assertEqual(self._deferred.result, 'Success')
self._clock.advance(0.1)
self.assertTrue(self._deferred.called)
self.assertEqual(self._deferred.result, 'Success')
def test_timeout_cleaned_up_on_success(self):
"""
If the deferred is successfully completed before the timeout, the
timeout is not still pending on the reactor.
"""
self._execute_timeout()
self._clock.advance(self._timeout - 0.1)
self._deferred.callback('Success')
self.assertEqual(self._clock.getDelayedCalls(), [])
self.assertEqual(self._deferred.result, 'Success')
def test_timeout_cleaned_up_on_failure(self):
"""
If the deferred is failed before the timeout, the timeout is not still
pending on the reactor.
"""
self._execute_timeout()
self._clock.advance(self._timeout - 0.1)
self._deferred.errback(Exception('ErrorXYZ'))
self.assertEqual(self._clock.getDelayedCalls(), [])
self.assertEqual(self._deferred.result.getErrorMessage(), 'ErrorXYZ')
self.failureResultOf(self._deferred, Exception)
示例13: APITestsMixin
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import getDelayedCalls [as 别名]
#.........这里部分代码省略.........
If a dataset with the given name is created while the
``/VolumeDriver.Create`` call is in flight, the call does not
result in an error.
"""
name = u"thename"
# Create a dataset out-of-band with matching dataset ID and name
# which the docker plugin won't be able to see.
def create_after_list():
# Clean up the patched version:
del self.flocker_client.list_datasets_configuration
# But first time we're called, we create dataset and lie about
# its existence:
d = self.flocker_client.create_dataset(
self.NODE_A, DEFAULT_SIZE,
metadata={u"name": name},
dataset_id=UUID(dataset_id_from_name(name)))
d.addCallback(lambda _: [])
return d
self.flocker_client.list_datasets_configuration = create_after_list
return self.create(name)
def _flush_volume_plugin_reactor_on_endpoint_render(self):
"""
This method patches ``self.app`` so that after any endpoint is
rendered, the reactor used by the volume plugin is advanced repeatedly
until there are no more ``delayedCalls`` pending on the reactor.
"""
real_execute_endpoint = self.app.execute_endpoint
def patched_execute_endpoint(*args, **kwargs):
val = real_execute_endpoint(*args, **kwargs)
while self.volume_plugin_reactor.getDelayedCalls():
pending_calls = self.volume_plugin_reactor.getDelayedCalls()
next_expiration = min(t.getTime() for t in pending_calls)
now = self.volume_plugin_reactor.seconds()
self.volume_plugin_reactor.advance(
max(0.0, next_expiration - now))
return val
self.patch(self.app, 'execute_endpoint', patched_execute_endpoint)
def test_mount(self):
"""
``/VolumeDriver.Mount`` sets the primary of the dataset with matching
name to the current node and then waits for the dataset to
actually arrive.
"""
name = u"myvol"
dataset_id = UUID(dataset_id_from_name(name))
# Create dataset on a different node:
d = self.flocker_client.create_dataset(
self.NODE_B, DEFAULT_SIZE, metadata={u"name": name},
dataset_id=dataset_id)
self._flush_volume_plugin_reactor_on_endpoint_render()
# Pretend that it takes 5 seconds for the dataset to get established on
# Node A.
self.volume_plugin_reactor.callLater(
5.0, self.flocker_client.synchronize_state)
d.addCallback(lambda _:
self.assertResult(
b"POST", b"/VolumeDriver.Mount",
{u"Name": name}, OK,
示例14: TransportTestCase
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import getDelayedCalls [as 别名]
#.........这里部分代码省略.........
down.dataReceived(data)
self.dump.append((self.clock.seconds(), direction * len(data)))
return write
client.circuit.downstream.write = curry_bypass_connection(client, server, const.OUT)
server.circuit.downstream.write = curry_bypass_connection(server, client, const.IN)
def _build_protocol(self, mode):
"""Build client and server protocols for an end point."""
addr_tuple = (HOST, str(PORT))
address = IPv4Address('TCP', HOST, PORT)
pt_config = self._build_transport_configuration(mode)
transport_class = self._configure_transport_class(mode, pt_config)
f_server = net.StaticDestinationServerFactory(addr_tuple, mode, transport_class, pt_config)
protocol_server = self._set_protocol(f_server, address)
f_client = net.StaticDestinationClientFactory(protocol_server.circuit, const.CLIENT)
protocol_client = self._set_protocol(f_client, address)
if mode == const.CLIENT:
return protocol_client
elif mode == const.SERVER:
return protocol_server
else:
raise ValueError("Transport mode '%s' not recognized." % mode)
def _set_protocol(self, factory, address):
"""Make protocol connection with a Twisted string transport."""
protocol = factory.buildProtocol(address)
protocol.makeConnection(proto_helpers.StringTransport())
protocol.history = {'rcv': [], 'snd': []}
return protocol
def _build_transport_configuration(self, mode):
"""Configure transport as a managed transport."""
pt_config = transport_config.TransportConfig()
pt_config.setStateLocation(const.TEMP_DIR)
pt_config.setObfsproxyMode("managed")
pt_config.setListenerMode(mode)
return pt_config
def _configure_transport_class(self, mode, pt_config):
"""Use the global arguments to configure the trasnport."""
transport_args = [mode, ADDR, "--dest=%s" % ADDR] + self.args
sys.argv = [sys.argv[0],
"--log-file", join(const.TEMP_DIR, "%s.log" % mode),
"--log-min-severity", "debug"]
sys.argv.append("wfpad") # use wfpad transport
sys.argv += transport_args
parser = set_up_cli_parsing()
consider_cli_args(parser.parse_args())
transport_class = get_transport_class(self.transport, mode)
transport_class.setup(pt_config)
p = ArgumentParser()
transport_class.register_external_mode_cli(p)
args = p.parse_args(transport_args)
transport_class.validate_external_mode_cli(args)
return transport_class
def _lose_protocol_connection(self, protocol):
"""Disconnect client and server transports."""
protocol.circuit.upstream.transport.loseConnection()
protocol.circuit.downstream.transport.loseConnection()
def advance_next_delayed_call(self):
"""Advance clock to first delayed call in reactor."""
first_delayed_call = self.clock.getDelayedCalls()[0]
self.clock.advance(first_delayed_call.getTime() - self.clock.seconds())
def is_timeout(self, call):
"""Check if the call has actually timed out."""
return isinstance(call.args[0], TimeoutError)
def advance_delayed_calls(self, max_dcalls=NUM_DCALLS, no_timeout=True):
"""Advance clock to the point all delayed calls up to that moment have
been called.
"""
i, timeouts = 0, []
while len(self.clock.getDelayedCalls()) > 0 and i < max_dcalls:
i += 1
dcall = self.clock.getDelayedCalls()[0]
if no_timeout:
if len(dcall.args) > 0 and self.is_timeout(dcall):
if dcall in timeouts:
break
self._queue_first_call()
timeouts.append(dcall)
continue
self.advance_next_delayed_call()
def _queue_first_call(self, delay=10000.0):
"""Put the first delayed call to the last position."""
timeout = self.clock.calls.pop(0)
timeout.time = delay
self.clock.calls.append(timeout)
def tearDown(self):
"""Close connections and advance all delayed calls."""
# Need to wait a bit beacuse obfsproxy network.Circuit.circuitCompleted
# defers 0.02s a dummy call to dataReceived to flush connection.
self._lose_protocol_connection(self.proto_client)
self._lose_protocol_connection(self.proto_server)
self.advance_delayed_calls()