197
197
class InterfaceTestCase(unittest.TestCase):
201
def _callback(self, deferred, x, **d):
202
"""Callback for testCallLater"""
203
self.assertEquals(x, 1)
204
self.assertEquals(d, {'a': 1})
206
self._calledTime = time.time()
207
deferred.callback(None)
209
def testCallLater(self):
210
# add and remove a callback
212
raise RuntimeError, "this shouldn't have been called"
213
i = reactor.callLater(0.1, bad)
216
self.assertRaises(error.AlreadyCancelled, i.cancel)
219
i = reactor.callLater(0.5, self._callback, d, 1, a=1)
223
self.assertApproximates(self._calledTime, start + 0.5, 0.2 )
224
self.assertRaises(error.AlreadyCalled, i.cancel)
199
Tests for a random pile of crap in twisted.internet, I suppose.
202
def test_callLater(self):
204
Test that a DelayedCall really calls the function it is supposed to call.
207
reactor.callLater(0, d.callback, None)
208
d.addCallback(self.assertEqual, None)
212
def test_cancelDelayedCall(self):
214
Test that when a DelayedCall is cancelled it does not run.
219
call = reactor.callLater(0, function)
222
# Schedule a call in two "iterations" to check to make sure that the
223
# above call never ran.
227
self.assertEqual(called, [])
232
reactor.callLater(0, reactor.callLater, 0, check)
236
def test_cancelCancelledDelayedCall(self):
238
Test that cancelling a DelayedCall which has already been cancelled
239
raises the appropriate exception.
241
call = reactor.callLater(0, lambda: None)
243
self.assertRaises(error.AlreadyCancelled, call.cancel)
246
def test_cancelCalledDelayedCallSynchronous(self):
248
Test that cancelling a DelayedCall in the DelayedCall's function as
249
that function is being invoked by the DelayedCall raises the
250
appropriate exception.
255
self.assertRaises(error.AlreadyCalled, call.cancel)
260
call = reactor.callLater(0, later)
264
def test_cancelCalledDelayedCallAsynchronous(self):
266
Test that cancelling a DelayedCall after it has run its function
267
raises the appropriate exception.
272
self.assertRaises(error.AlreadyCalled, call.cancel)
278
reactor.callLater(0, check)
279
call = reactor.callLater(0, later)
389
442
if interfaces.IReactorThreads(reactor, None) is None:
390
443
testWakeUp.skip = "Nothing to wake up for without thread support"
445
def _stopCallFromThreadCallback(self):
448
def _callFromThreadCallback(self, d):
449
reactor.callFromThread(self._callFromThreadCallback2, d)
450
reactor.callLater(0, self._stopCallFromThreadCallback)
452
def _callFromThreadCallback2(self, d):
454
self.assert_(self.stopped)
456
# Send the error to the deferred
461
def testCallFromThreadStops(self):
463
Ensure that callFromThread from inside a callFromThread
464
callback doesn't sit in an infinite loop and lets other
469
reactor.callFromThread(self._callFromThreadCallback, d)
393
473
class ReactorCoreTestCase(unittest.TestCase):
395
475
self.triggers = []
397
479
def addTrigger(self, event, phase, func):
398
480
t = reactor.addSystemEventTrigger(event, phase, func)
399
481
self.triggers.append(t)
401
485
def removeTrigger(self, trigger):
402
486
reactor.removeSystemEventTrigger(trigger)
403
487
self.triggers.remove(trigger)
404
490
def addTimer(self, when, func):
405
491
t = reactor.callLater(when, func)
406
492
self.timers.append(t)
408
496
def removeTimer(self, timer):
444
534
self.failUnless(elapsed < 8)
448
print "test timed out"
450
self.fail("test timed out")
454
# XXX calling reactor.stop() in test suite causes problems with other tests
455
# def testStop(self):
456
# """reactor.stop should fire shutdown triggers"""
457
# # make sure shutdown triggers are run when the reactor is stopped
460
# self.addTrigger("before", "shutdown", self.count)
461
# self.addTimer(0.1, self.stop)
462
# t = self.addTimer(5, self.timeout)
464
# self.failUnless(self.counter == 1,
465
# "reactor.stop didn't invoke shutdown triggers")
466
# self.failIf(self.problem, "the test timed out")
467
# self.removeTimer(t)
470
"""reactor.crash should NOT fire shutdown triggers"""
473
self.addTrigger("before", "shutdown", self.count)
538
def test_crash(self):
540
reactor.crash should NOT fire shutdown triggers
544
"before", "shutdown",
545
lambda: events.append(("before", "shutdown")))
474
547
# reactor.crash called from an "after-startup" trigger is too early
475
548
# for the gtkreactor: gtk_mainloop is not yet running. Same is true
476
549
# when called with reactor.callLater(0). Must be >0 seconds in the
477
550
# future to let gtk_mainloop start first.
478
self.addTimer(0.1, self.crash)
479
t = self.addTimer(5, self.timeout)
551
reactor.callWhenRunning(
552
reactor.callLater, 0, reactor.crash)
481
# this will fire reactor.crash, which ought to exit .run without
482
# running the event triggers
483
self.failUnless(self.counter == 0,
484
"reactor.crash invoked shutdown triggers, "
485
"but it isn't supposed to")
486
self.failIf(self.problem, "the test timed out")
554
self.failIf(events, "reactor.crash invoked shutdown triggers, but it "
555
"isn't supposed to.")
557
# XXX Test that reactor.stop() invokes shutdown triggers
490
561
class DelayedTestCase(unittest.TestCase):
730
801
self.assert_( isinstance(protocol, factory.protocol) )
804
class DummyProducer(object):
806
Very uninteresting producer implementation used by tests to ensure the
807
right methods are called by the consumer with which it is registered.
809
@type events: C{list} of C{str}
810
@ivar events: The producer/consumer related events which have happened to
811
this producer. Strings in this list may be C{'resume'}, C{'stop'}, or
812
C{'pause'}. Elements are added as they occur.
736
819
def resumeProducing(self):
820
self.events.append('resume')
739
823
def stopProducing(self):
824
self.events.append('stop')
827
def pauseProducing(self):
828
self.events.append('pause')
832
class SillyDescriptor(abstract.FileDescriptor):
834
A descriptor whose data buffer gets filled very fast.
836
Useful for testing FileDescriptor's IConsumer interface, since
837
the data buffer fills as soon as at least four characters are
838
written to it, and gets emptied in a single doWrite() cycle.
843
def writeSomeData(self, data):
845
Always write all data.
850
def startWriting(self):
852
Do nothing: bypass the reactor.
854
stopWriting = startWriting
858
class ReentrantProducer(DummyProducer):
860
Similar to L{DummyProducer}, but with a resumeProducing method which calls
861
back into an L{IConsumer} method of the consumer against which it is
864
@ivar consumer: The consumer with which this producer has been or will
867
@ivar methodName: The name of the method to call on the consumer inside
870
@ivar methodArgs: The arguments to pass to the consumer method invoked in
873
def __init__(self, consumer, methodName, *methodArgs):
874
super(ReentrantProducer, self).__init__()
875
self.consumer = consumer
876
self.methodName = methodName
877
self.methodArgs = methodArgs
880
def resumeProducing(self):
881
super(ReentrantProducer, self).resumeProducing()
882
getattr(self.consumer, self.methodName)(*self.methodArgs)
742
886
class TestProducer(unittest.TestCase):
744
def testDoubleProducer(self):
888
Test abstract.FileDescriptor's consumer interface.
890
def test_doubleProducer(self):
892
Verify that registering a non-streaming producer invokes its
893
resumeProducing() method and that you can only register one producer
745
896
fd = abstract.FileDescriptor()
747
898
dp = DummyProducer()
748
899
fd.registerProducer(dp, 0)
749
self.assertEquals(dp.resumed, 1)
900
self.assertEquals(dp.events, ['resume'])
750
901
self.assertRaises(RuntimeError, fd.registerProducer, DummyProducer(), 0)
752
def testUnconnectedFileDescriptor(self):
904
def test_unconnectedFileDescriptor(self):
906
Verify that registering a producer when the connection has already
907
been closed invokes its stopProducing() method.
753
909
fd = abstract.FileDescriptor()
754
910
fd.disconnected = 1
755
911
dp = DummyProducer()
756
912
fd.registerProducer(dp, 0)
757
self.assertEquals(dp.stopped, 1)
913
self.assertEquals(dp.events, ['stop'])
916
def _dontPausePullConsumerTest(self, methodName):
917
descriptor = SillyDescriptor()
918
producer = DummyProducer()
919
descriptor.registerProducer(producer, streaming=False)
920
self.assertEqual(producer.events, ['resume'])
921
del producer.events[:]
923
# Fill up the descriptor's write buffer so we can observe whether or
924
# not it pauses its producer in that case.
925
getattr(descriptor, methodName)('1234')
927
self.assertEqual(producer.events, [])
930
def test_dontPausePullConsumerOnWrite(self):
932
Verify that FileDescriptor does not call producer.pauseProducing() on a
933
non-streaming pull producer in response to a L{IConsumer.write} call
934
which results in a full write buffer. Issue #2286.
936
return self._dontPausePullConsumerTest('write')
939
def test_dontPausePullConsumerOnWriteSequence(self):
941
Like L{test_dontPausePullConsumerOnWrite}, but for a call to
942
C{writeSequence} rather than L{IConsumer.write}.
944
C{writeSequence} is not part of L{IConsumer}, but
945
L{abstract.FileDescriptor} has supported consumery behavior in response
946
to calls to L{writeSequence} forever.
948
return self._dontPausePullConsumerTest('writeSequence')
951
def _reentrantStreamingProducerTest(self, methodName):
952
descriptor = SillyDescriptor()
953
producer = ReentrantProducer(descriptor, methodName, 'spam')
954
descriptor.registerProducer(producer, streaming=True)
956
# Start things off by filling up the descriptor's buffer so it will
957
# pause its producer.
958
getattr(descriptor, methodName)('spam')
960
# Sanity check - make sure that worked.
961
self.assertEqual(producer.events, ['pause'])
962
del producer.events[:]
964
# After one call to doWrite, the buffer has been emptied so the
965
# FileDescriptor should resume its producer. That will result in an
966
# immediate call to FileDescriptor.write which will again fill the
967
# buffer and result in the producer being paused.
969
self.assertEqual(producer.events, ['resume', 'pause'])
970
del producer.events[:]
972
# After a second call to doWrite, the exact same thing should have
973
# happened. Prior to the bugfix for which this test was written,
974
# FileDescriptor would have incorrectly believed its producer was
975
# already resumed (it was paused) and so not resume it again.
977
self.assertEqual(producer.events, ['resume', 'pause'])
980
def test_reentrantStreamingProducerUsingWrite(self):
982
Verify that FileDescriptor tracks producer's paused state correctly.
983
Issue #811, fixed in revision r12857.
985
return self._reentrantStreamingProducerTest('write')
988
def test_reentrantStreamingProducerUsingWriteSequence(self):
990
Like L{test_reentrantStreamingProducerUsingWrite}, but for calls to
993
C{writeSequence} is B{not} part of L{IConsumer}, however
994
C{abstract.FileDescriptor} has supported consumery behavior in response
995
to calls to C{writeSequence} forever.
997
return self._reentrantStreamingProducerTest('writeSequence')
759
1001
class PortStringification(unittest.TestCase):
760
1002
if interfaces.IReactorTCP(reactor, None) is not None: