本文整理汇总了Python中twisted.internet.task.Clock.callLater方法的典型用法代码示例。如果您正苦于以下问题:Python Clock.callLater方法的具体用法?Python Clock.callLater怎么用?Python Clock.callLater使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.internet.task.Clock
的用法示例。
在下文中一共展示了Clock.callLater方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_tick
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import callLater [as 别名]
def test_tick(self):
"""
``/mimic/v1.1/tick`` (handled by :func:`MimicRoot.advance_time`)
advances the clock associated with the service.
"""
clock = Clock()
def do():
do.done = True
do.done = False
clock.callLater(3.5, do)
core = MimicCore(clock, [])
root = MimicRoot(core, clock).app.resource()
self.assertEqual(do.done, False)
jreq = json_request(
self, root, "POST", "/mimic/v1.1/tick", body={"amount": 3.6}
)
[response, json_content] = self.successResultOf(jreq)
self.assertEqual(response.code, 200)
expected = {
'advanced': 3.6,
'now': '1970-01-01T00:00:03.600000Z',
}
self.assertEqual(json_content, expected)
self.assertEqual(do.done, True)
示例2: clockIsBroken
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import callLater [as 别名]
def clockIsBroken():
"""
Returns whether twisted.internet.task.Clock has the bug that
returns the wrong DelayedCall or not.
"""
clock = Clock()
dc1 = clock.callLater(10, lambda: None)
dc2 = clock.callLater(1, lambda: None)
if dc1 is dc2:
return True
else:
return False
示例3: test_stopService_while_retrying
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import callLater [as 别名]
def test_stopService_while_retrying(self):
s, e, f = self.make_reconnector()
clock = Clock()
r = s._delayedRetry = clock.callLater(1.0, lambda: None)
yield s.stopService()
self.assertTrue(r.cancelled)
self.assertIdentical(s._delayedRetry, None)
示例4: UDPScraper
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import callLater [as 别名]
class UDPScraper(DatagramProtocol):
def __init__(self, ip, port):
self.ip = ip
self.port = port
self.expect_connection_response = True
# Timeout after 15 seconds if nothing received.
self.timeout_seconds = 15
self.clock = Clock()
self.timeout = self.clock.callLater(self.timeout_seconds, self.on_error)
def on_error(self):
"""
This method handles everything that needs to be done when something during
the UDP scraping went wrong.
"""
raise RuntimeError("error")
def stop(self):
"""
Stops the UDP scraper and closes the socket.
:return: A deferred that fires once it has closed the connection.
"""
if self.timeout.active():
self.timeout.cancel()
if self.transport:
return maybeDeferred(self.transport.stopListening)
else:
return defer.succeed(True)
def startProtocol(self):
"""
This function is called when the scraper is initialized.
Initiates the connection with the tracker.
"""
self.transport.connect(self.ip, self.port)
self.udpsession.on_start()
def write_data(self, data):
"""
This function can be called to send serialized data to the tracker.
:param data: The serialized data to be send.
"""
self.transport.write(data) # no need to pass the ip and port
def datagramReceived(self, data, (host, port)):
"""
This function dispatches data received from a UDP tracker.
If it's the first response, it will dispatch the data to the handle_connection_response
function of the UDP session.
All subsequent data will be send to the _handle_response function of the UDP session.
:param data: The data received from the UDP tracker.
"""
# Cancel the timeout
if self.timeout.active():
self.timeout.cancel()
示例5: callLater
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import callLater [as 别名]
def callLater(self, when, what, *a, **kw):
"""
Unlike the real reactor, Clock.callLater doesn't raise an exception
when the time is negative.
https://twistedmatrix.com/trac/ticket/9166#comment
Until that's fixed upstream, emulate the behavior here.
"""
assert when >= 0, \
"%s is not greater than or equal to 0 seconds" % (when,)
return Clock.callLater(self, when, what, *a, **kw)
示例6: test_runDeferred_non_deferred
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import callLater [as 别名]
def test_runDeferred_non_deferred(self):
"""
An assertion error is raised when runDeferred is called for
something which is not an deferred.
Ex. a delayedCall
"""
scheduler = Clock()
delayed_call = scheduler.callLater(0, lambda: None) # pragma: no cover
with self.assertRaises(AssertionError) as context:
self.runDeferred(delayed_call)
self.assertEqual(
'This is not a deferred.', context.exception.args[0])
示例7: TestEventDispatcher
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import callLater [as 别名]
class TestEventDispatcher(events.EventDispatcher):
def __init__(self):
events.EventDispatcher.__init__(self, lambda a: None)
self.clock = Clock()
self.advance = self.clock.advance
def dispatch_delayed(self, event, delay):
return self.clock.callLater(delay, self.dispatch, event)
def dispatch_repeating(self, event, interval, now=False):
t = task.LoopingCall(self.dispatch, event)
t.clock = self.clock
t.start(interval, now)
return t
示例8: test_sendFile
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import callLater [as 别名]
def test_sendFile(self):
fileToSend = StringIO(fileData)
clock = Clock()
cooperator = Cooperator(scheduler=lambda f: clock.callLater(0.1, f))
d1 = self.client.sendFile(fileToSend, cooperator=cooperator)
self.pump.pump()
self.pump.pump()
self.assertNoResult(d1)
d2 = deliverContent(self.server.producer)
clock.advance(1)
while self.pump.pump():
clock.advance(1)
self.successResultOf(d1)
self.assertEqual(self.successResultOf(d2), fileData)
示例9: test_deliverContent
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import callLater [as 别名]
def test_deliverContent(self):
fileToSend = StringIO(fileData)
clock = Clock()
cooperator = Cooperator(scheduler=lambda f: clock.callLater(0.1, f))
@ProducerStarter
def registerWithConsumer(consumer):
producer = FileBodyProducer(fileToSend, cooperator=cooperator)
d = producer.startProducing(consumer)
d.addCallback(lambda ign: consumer.unregisterProducer())
d.addErrback(log.err, 'error producing file body')
consumer.registerProducer(producer, True)
self.client.callRemote(SendProducer, producer=registerWithConsumer)
self.pump.pump()
d = deliverContent(self.server.producer)
while self.pump.pump():
clock.advance(1)
self.assertEqual(self.successResultOf(d), fileData)
示例10: test_sendFileDisconnection
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import callLater [as 别名]
def test_sendFileDisconnection(self):
fileToSend = StringIO(fileData)
clock = Clock()
cooperator = Cooperator(scheduler=lambda f: clock.callLater(0.1, f))
d1 = self.client.sendFile(fileToSend, cooperator=cooperator)
self.assertFailure(d1, FakeDisconnectedError)
self.pump.pump()
self.pump.pump()
self.assertNoResult(d1)
d2 = deliverContent(self.server.producer)
self.assertFailure(d2, FakeDisconnectedError)
self.pump.pump()
clock.advance(1)
f = failure.Failure(FakeDisconnectedError())
self.client.connectionLost(f)
self.server.connectionLost(f)
self.assertEqual(len(self.flushLoggedErrors(FakeDisconnectedError)), 2)
self.successResultOf(d1)
self.successResultOf(d2)
示例11: test_receivePushProducer
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import callLater [as 别名]
def test_receivePushProducer(self):
fileToSend = StringIO(fileData)
consumer = FileConsumer()
clock = Clock()
cooperator = Cooperator(scheduler=lambda f: clock.callLater(0.1, f))
@ProducerStarter
def registerWithConsumer(consumer):
producer = FileBodyProducer(fileToSend, cooperator=cooperator)
d = producer.startProducing(consumer)
d.addCallback(lambda ign: consumer.unregisterProducer())
d.addErrback(log.err, 'error producing file body')
consumer.registerProducer(producer, True)
self.server.registerWithConsumer = registerWithConsumer
d = self.client.callRemote(ReceiveProducer)
self.pump.flush()
receivedProducer = self.successResultOf(d)['producer']
receivedProducer.registerConsumer(consumer)
clock.advance(1)
while self.pump.pump():
clock.advance(1)
self.assertEqual(consumer.value(), fileData)
self.assertIdentical(consumer._producer, None)
示例12: FakeReactor
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import callLater [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)
示例13: InputParsingTests
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import callLater [as 别名]
class InputParsingTests(TestCase):
"""
Tests for dealing with user input which may contain commands or be a
message destined for the network.
"""
def setUp(self):
self.tcpConnections = []
self.clock = Clock()
self.transport = None
self.terminal = TerminalBuffer()
self.terminal.makeConnection(self.transport)
self.protocol = UserInterface()
self.protocol.reactor = self
self.protocol.makeConnection(self.terminal)
def connectTCP(self, host, port, factory, timeout=30, bindAddress=''):
self.tcpConnections.append((host, port, factory, timeout, bindAddress))
def callLater(self, n, f, *a, **kw):
return self.clock.callLater(n, f, *a, **kw)
def test_commandDispatch(self):
"""
Verify that a line starting with C{/} and a word is dispatched to a
function determined by that word.
"""
dispatched = []
self.protocol.cmd_DISPATCHTEST = dispatched.append
self.protocol.parseInputLine('/dispatchtest')
self.assertEqual(dispatched, ['/dispatchtest'])
def test_serverCommand(self):
"""
Verify that C{/server} is interpreted as a command to establish a new
server connection. Also some more things (that a connection attempt is
made, that when it succeeds an IRC login is attempted over it with the
right nickname).
This is poorly factored. IRC testing should be done elsewhere.
Connection setup testing should be done elsewhere.
"""
# XXX See #2504 in Twisted tracker
from twisted.words.im import ircsupport
self.patch(ircsupport, 'reactor', self)
self.protocol.cmd_SERVER('/server irc.example.org testuser')
self.assertEqual(len(self.tcpConnections), 1)
self.assertEqual(self.tcpConnections[0][:2], ('irc.example.org', 6667))
factory = self.tcpConnections[0][2]
protocol = factory.buildProtocol(('irc.example.org', 6667))
transport = StringTransport()
protocol.makeConnection(transport)
while self.clock.calls:
self.clock.advance(1)
self.assertEqual(
transport.value(),
'NICK testuser\r\n'
'USER testuser foo bar :Twisted-IM user\r\n')
output = str(self.terminal).splitlines()
input = output.pop()
status = output.pop()
report = output.pop()
for L in output:
self.assertEqual(L, ' ' * 80)
message = '== Connection to irc.example.org established.'
self.assertEqual(report, message + ' ' * (80 - len(message)))
def test_serverCommandFailedConnection(self):
"""
Like L{test_serverCommand} but for a connection which fails.
"""
# XXX See #2504 in Twisted tracker
from twisted.words.im import ircsupport
self.patch(ircsupport, 'reactor', self)
self.protocol.cmd_SERVER('/server irc.example.org testuser')
self.assertEqual(len(self.tcpConnections), 1)
self.assertEqual(self.tcpConnections[0][:2], ('irc.example.org', 6667))
factory = self.tcpConnections[0][2]
factory.clientConnectionFailed(None, TimeoutError("mock"))
while self.clock.calls:
self.clock.advance(1)
output = str(self.terminal).splitlines()
input = output.pop()
status = output.pop()
report = output.pop()
for L in output:
self.assertEqual(L, ' ' * 80)
message = '== irc.example.org failed: User timeout caused connection failure: mock.'
#.........这里部分代码省略.........
示例14: SelfHealTests
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import callLater [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())
示例15: APITestsMixin
# 需要导入模块: from twisted.internet.task import Clock [as 别名]
# 或者: from twisted.internet.task.Clock import callLater [as 别名]
#.........这里部分代码省略.........
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,
{u"Err": None,
u"Mountpoint": u"/flocker/{}".format(dataset_id)}))
d.addCallback(lambda _: self.flocker_client.list_datasets_state())
def final_assertions(datasets):
self.assertEqual([self.NODE_A],
[d.primary for d in datasets
if d.dataset_id == dataset_id])
# There should be less than 20 calls to list_datasets_state over
# the course of 5 seconds.
self.assertLess(
self.flocker_client.num_calls('list_datasets_state'), 20)
d.addCallback(final_assertions)
return d
def test_mount_timeout(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. If it does not arrive within 120 seconds, then it
returns an error up to docker.
"""
name = u"myvol"
dataset_id = UUID(dataset_id_from_name(name))
# Create dataset on a different node: