forked from twisted/twisted
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_internet.py
1405 lines (1140 loc) · 45.7 KB
/
test_internet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for lots of functionality provided by L{twisted.internet}.
"""
from __future__ import division, absolute_import
import os
import sys
import time
from twisted.python.compat import _PY3
from twisted.trial import unittest
from twisted.internet import reactor, protocol, error, abstract, defer
from twisted.internet import interfaces, base
from twisted.internet.tcp import Connector
try:
from twisted.internet import ssl
except ImportError:
ssl = None
if ssl and not ssl.supported:
ssl = None
from twisted.internet.defer import Deferred, passthru
if not _PY3:
from twisted.python import util
class ThreePhaseEventTests(unittest.TestCase):
"""
Tests for the private implementation helpers for system event triggers.
"""
def setUp(self):
"""
Create a trigger, an argument, and an event to be used by tests.
"""
self.trigger = lambda x: None
self.arg = object()
self.event = base._ThreePhaseEvent()
def test_addInvalidPhase(self):
"""
L{_ThreePhaseEvent.addTrigger} should raise L{KeyError} when called
with an invalid phase.
"""
self.assertRaises(
KeyError,
self.event.addTrigger, 'xxx', self.trigger, self.arg)
def test_addBeforeTrigger(self):
"""
L{_ThreePhaseEvent.addTrigger} should accept C{'before'} as a phase, a
callable, and some arguments and add the callable with the arguments to
the before list.
"""
self.event.addTrigger('before', self.trigger, self.arg)
self.assertEqual(
self.event.before,
[(self.trigger, (self.arg,), {})])
def test_addDuringTrigger(self):
"""
L{_ThreePhaseEvent.addTrigger} should accept C{'during'} as a phase, a
callable, and some arguments and add the callable with the arguments to
the during list.
"""
self.event.addTrigger('during', self.trigger, self.arg)
self.assertEqual(
self.event.during,
[(self.trigger, (self.arg,), {})])
def test_addAfterTrigger(self):
"""
L{_ThreePhaseEvent.addTrigger} should accept C{'after'} as a phase, a
callable, and some arguments and add the callable with the arguments to
the after list.
"""
self.event.addTrigger('after', self.trigger, self.arg)
self.assertEqual(
self.event.after,
[(self.trigger, (self.arg,), {})])
def test_removeTrigger(self):
"""
L{_ThreePhaseEvent.removeTrigger} should accept an opaque object
previously returned by L{_ThreePhaseEvent.addTrigger} and remove the
associated trigger.
"""
handle = self.event.addTrigger('before', self.trigger, self.arg)
self.event.removeTrigger(handle)
self.assertEqual(self.event.before, [])
def test_removeNonexistentTrigger(self):
"""
L{_ThreePhaseEvent.removeTrigger} should raise L{ValueError} when given
an object not previously returned by L{_ThreePhaseEvent.addTrigger}.
"""
self.assertRaises(ValueError, self.event.removeTrigger, object())
def test_removeRemovedTrigger(self):
"""
L{_ThreePhaseEvent.removeTrigger} should raise L{ValueError} the second
time it is called with an object returned by
L{_ThreePhaseEvent.addTrigger}.
"""
handle = self.event.addTrigger('before', self.trigger, self.arg)
self.event.removeTrigger(handle)
self.assertRaises(ValueError, self.event.removeTrigger, handle)
def test_removeAlmostValidTrigger(self):
"""
L{_ThreePhaseEvent.removeTrigger} should raise L{ValueError} if it is
given a trigger handle which resembles a valid trigger handle aside
from its phase being incorrect.
"""
self.assertRaises(
KeyError,
self.event.removeTrigger, ('xxx', self.trigger, (self.arg,), {}))
def test_fireEvent(self):
"""
L{_ThreePhaseEvent.fireEvent} should call I{before}, I{during}, and
I{after} phase triggers in that order.
"""
events = []
self.event.addTrigger('after', events.append, ('first', 'after'))
self.event.addTrigger('during', events.append, ('first', 'during'))
self.event.addTrigger('before', events.append, ('first', 'before'))
self.event.addTrigger('before', events.append, ('second', 'before'))
self.event.addTrigger('during', events.append, ('second', 'during'))
self.event.addTrigger('after', events.append, ('second', 'after'))
self.assertEqual(events, [])
self.event.fireEvent()
self.assertEqual(events,
[('first', 'before'), ('second', 'before'),
('first', 'during'), ('second', 'during'),
('first', 'after'), ('second', 'after')])
def test_asynchronousBefore(self):
"""
L{_ThreePhaseEvent.fireEvent} should wait for any L{Deferred} returned
by a I{before} phase trigger before proceeding to I{during} events.
"""
events = []
beforeResult = Deferred()
self.event.addTrigger('before', lambda: beforeResult)
self.event.addTrigger('during', events.append, 'during')
self.event.addTrigger('after', events.append, 'after')
self.assertEqual(events, [])
self.event.fireEvent()
self.assertEqual(events, [])
beforeResult.callback(None)
self.assertEqual(events, ['during', 'after'])
def test_beforeTriggerException(self):
"""
If a before-phase trigger raises a synchronous exception, it should be
logged and the remaining triggers should be run.
"""
events = []
class DummyException(Exception):
pass
def raisingTrigger():
raise DummyException()
self.event.addTrigger('before', raisingTrigger)
self.event.addTrigger('before', events.append, 'before')
self.event.addTrigger('during', events.append, 'during')
self.event.fireEvent()
self.assertEqual(events, ['before', 'during'])
errors = self.flushLoggedErrors(DummyException)
self.assertEqual(len(errors), 1)
def test_duringTriggerException(self):
"""
If a during-phase trigger raises a synchronous exception, it should be
logged and the remaining triggers should be run.
"""
events = []
class DummyException(Exception):
pass
def raisingTrigger():
raise DummyException()
self.event.addTrigger('during', raisingTrigger)
self.event.addTrigger('during', events.append, 'during')
self.event.addTrigger('after', events.append, 'after')
self.event.fireEvent()
self.assertEqual(events, ['during', 'after'])
errors = self.flushLoggedErrors(DummyException)
self.assertEqual(len(errors), 1)
def test_synchronousRemoveAlreadyExecutedBefore(self):
"""
If a before-phase trigger tries to remove another before-phase trigger
which has already run, a warning should be emitted.
"""
events = []
def removeTrigger():
self.event.removeTrigger(beforeHandle)
beforeHandle = self.event.addTrigger('before', events.append, ('first', 'before'))
self.event.addTrigger('before', removeTrigger)
self.event.addTrigger('before', events.append, ('second', 'before'))
self.assertWarns(
DeprecationWarning,
"Removing already-fired system event triggers will raise an "
"exception in a future version of Twisted.",
__file__,
self.event.fireEvent)
self.assertEqual(events, [('first', 'before'), ('second', 'before')])
def test_synchronousRemovePendingBefore(self):
"""
If a before-phase trigger removes another before-phase trigger which
has not yet run, the removed trigger should not be run.
"""
events = []
self.event.addTrigger(
'before', lambda: self.event.removeTrigger(beforeHandle))
beforeHandle = self.event.addTrigger(
'before', events.append, ('first', 'before'))
self.event.addTrigger('before', events.append, ('second', 'before'))
self.event.fireEvent()
self.assertEqual(events, [('second', 'before')])
def test_synchronousBeforeRemovesDuring(self):
"""
If a before-phase trigger removes a during-phase trigger, the
during-phase trigger should not be run.
"""
events = []
self.event.addTrigger(
'before', lambda: self.event.removeTrigger(duringHandle))
duringHandle = self.event.addTrigger('during', events.append, 'during')
self.event.addTrigger('after', events.append, 'after')
self.event.fireEvent()
self.assertEqual(events, ['after'])
def test_asynchronousBeforeRemovesDuring(self):
"""
If a before-phase trigger returns a L{Deferred} and later removes a
during-phase trigger before the L{Deferred} fires, the during-phase
trigger should not be run.
"""
events = []
beforeResult = Deferred()
self.event.addTrigger('before', lambda: beforeResult)
duringHandle = self.event.addTrigger('during', events.append, 'during')
self.event.addTrigger('after', events.append, 'after')
self.event.fireEvent()
self.event.removeTrigger(duringHandle)
beforeResult.callback(None)
self.assertEqual(events, ['after'])
def test_synchronousBeforeRemovesConspicuouslySimilarDuring(self):
"""
If a before-phase trigger removes a during-phase trigger which is
identical to an already-executed before-phase trigger aside from their
phases, no warning should be emitted and the during-phase trigger
should not be run.
"""
events = []
def trigger():
events.append('trigger')
self.event.addTrigger('before', trigger)
self.event.addTrigger(
'before', lambda: self.event.removeTrigger(duringTrigger))
duringTrigger = self.event.addTrigger('during', trigger)
self.event.fireEvent()
self.assertEqual(events, ['trigger'])
def test_synchronousRemovePendingDuring(self):
"""
If a during-phase trigger removes another during-phase trigger which
has not yet run, the removed trigger should not be run.
"""
events = []
self.event.addTrigger(
'during', lambda: self.event.removeTrigger(duringHandle))
duringHandle = self.event.addTrigger(
'during', events.append, ('first', 'during'))
self.event.addTrigger(
'during', events.append, ('second', 'during'))
self.event.fireEvent()
self.assertEqual(events, [('second', 'during')])
def test_triggersRunOnce(self):
"""
A trigger should only be called on the first call to
L{_ThreePhaseEvent.fireEvent}.
"""
events = []
self.event.addTrigger('before', events.append, 'before')
self.event.addTrigger('during', events.append, 'during')
self.event.addTrigger('after', events.append, 'after')
self.event.fireEvent()
self.event.fireEvent()
self.assertEqual(events, ['before', 'during', 'after'])
def test_finishedBeforeTriggersCleared(self):
"""
The temporary list L{_ThreePhaseEvent.finishedBefore} should be emptied
and the state reset to C{'BASE'} before the first during-phase trigger
executes.
"""
events = []
def duringTrigger():
events.append('during')
self.assertEqual(self.event.finishedBefore, [])
self.assertEqual(self.event.state, 'BASE')
self.event.addTrigger('before', events.append, 'before')
self.event.addTrigger('during', duringTrigger)
self.event.fireEvent()
self.assertEqual(events, ['before', 'during'])
class SystemEventTests(unittest.TestCase):
"""
Tests for the reactor's implementation of the C{fireSystemEvent},
C{addSystemEventTrigger}, and C{removeSystemEventTrigger} methods of the
L{IReactorCore} interface.
@ivar triggers: A list of the handles to triggers which have been added to
the reactor.
"""
def setUp(self):
"""
Create an empty list in which to store trigger handles.
"""
self.triggers = []
def tearDown(self):
"""
Remove all remaining triggers from the reactor.
"""
while self.triggers:
trigger = self.triggers.pop()
try:
reactor.removeSystemEventTrigger(trigger)
except (ValueError, KeyError):
pass
def addTrigger(self, event, phase, func):
"""
Add a trigger to the reactor and remember it in C{self.triggers}.
"""
t = reactor.addSystemEventTrigger(event, phase, func)
self.triggers.append(t)
return t
def removeTrigger(self, trigger):
"""
Remove a trigger by its handle from the reactor and from
C{self.triggers}.
"""
reactor.removeSystemEventTrigger(trigger)
self.triggers.remove(trigger)
def _addSystemEventTriggerTest(self, phase):
eventType = 'test'
events = []
def trigger():
events.append(None)
self.addTrigger(phase, eventType, trigger)
self.assertEqual(events, [])
reactor.fireSystemEvent(eventType)
self.assertEqual(events, [None])
def test_beforePhase(self):
"""
L{IReactorCore.addSystemEventTrigger} should accept the C{'before'}
phase and not call the given object until the right event is fired.
"""
self._addSystemEventTriggerTest('before')
def test_duringPhase(self):
"""
L{IReactorCore.addSystemEventTrigger} should accept the C{'during'}
phase and not call the given object until the right event is fired.
"""
self._addSystemEventTriggerTest('during')
def test_afterPhase(self):
"""
L{IReactorCore.addSystemEventTrigger} should accept the C{'after'}
phase and not call the given object until the right event is fired.
"""
self._addSystemEventTriggerTest('after')
def test_unknownPhase(self):
"""
L{IReactorCore.addSystemEventTrigger} should reject phases other than
C{'before'}, C{'during'}, or C{'after'}.
"""
eventType = 'test'
self.assertRaises(
KeyError, self.addTrigger, 'xxx', eventType, lambda: None)
def test_beforePreceedsDuring(self):
"""
L{IReactorCore.addSystemEventTrigger} should call triggers added to the
C{'before'} phase before it calls triggers added to the C{'during'}
phase.
"""
eventType = 'test'
events = []
def beforeTrigger():
events.append('before')
def duringTrigger():
events.append('during')
self.addTrigger('before', eventType, beforeTrigger)
self.addTrigger('during', eventType, duringTrigger)
self.assertEqual(events, [])
reactor.fireSystemEvent(eventType)
self.assertEqual(events, ['before', 'during'])
def test_duringPreceedsAfter(self):
"""
L{IReactorCore.addSystemEventTrigger} should call triggers added to the
C{'during'} phase before it calls triggers added to the C{'after'}
phase.
"""
eventType = 'test'
events = []
def duringTrigger():
events.append('during')
def afterTrigger():
events.append('after')
self.addTrigger('during', eventType, duringTrigger)
self.addTrigger('after', eventType, afterTrigger)
self.assertEqual(events, [])
reactor.fireSystemEvent(eventType)
self.assertEqual(events, ['during', 'after'])
def test_beforeReturnsDeferred(self):
"""
If a trigger added to the C{'before'} phase of an event returns a
L{Deferred}, the C{'during'} phase should be delayed until it is called
back.
"""
triggerDeferred = Deferred()
eventType = 'test'
events = []
def beforeTrigger():
return triggerDeferred
def duringTrigger():
events.append('during')
self.addTrigger('before', eventType, beforeTrigger)
self.addTrigger('during', eventType, duringTrigger)
self.assertEqual(events, [])
reactor.fireSystemEvent(eventType)
self.assertEqual(events, [])
triggerDeferred.callback(None)
self.assertEqual(events, ['during'])
def test_multipleBeforeReturnDeferred(self):
"""
If more than one trigger added to the C{'before'} phase of an event
return L{Deferred}s, the C{'during'} phase should be delayed until they
are all called back.
"""
firstDeferred = Deferred()
secondDeferred = Deferred()
eventType = 'test'
events = []
def firstBeforeTrigger():
return firstDeferred
def secondBeforeTrigger():
return secondDeferred
def duringTrigger():
events.append('during')
self.addTrigger('before', eventType, firstBeforeTrigger)
self.addTrigger('before', eventType, secondBeforeTrigger)
self.addTrigger('during', eventType, duringTrigger)
self.assertEqual(events, [])
reactor.fireSystemEvent(eventType)
self.assertEqual(events, [])
firstDeferred.callback(None)
self.assertEqual(events, [])
secondDeferred.callback(None)
self.assertEqual(events, ['during'])
def test_subsequentBeforeTriggerFiresPriorBeforeDeferred(self):
"""
If a trigger added to the C{'before'} phase of an event calls back a
L{Deferred} returned by an earlier trigger in the C{'before'} phase of
the same event, the remaining C{'before'} triggers for that event
should be run and any further L{Deferred}s waited on before proceeding
to the C{'during'} events.
"""
eventType = 'test'
events = []
firstDeferred = Deferred()
secondDeferred = Deferred()
def firstBeforeTrigger():
return firstDeferred
def secondBeforeTrigger():
firstDeferred.callback(None)
def thirdBeforeTrigger():
events.append('before')
return secondDeferred
def duringTrigger():
events.append('during')
self.addTrigger('before', eventType, firstBeforeTrigger)
self.addTrigger('before', eventType, secondBeforeTrigger)
self.addTrigger('before', eventType, thirdBeforeTrigger)
self.addTrigger('during', eventType, duringTrigger)
self.assertEqual(events, [])
reactor.fireSystemEvent(eventType)
self.assertEqual(events, ['before'])
secondDeferred.callback(None)
self.assertEqual(events, ['before', 'during'])
def test_removeSystemEventTrigger(self):
"""
A trigger removed with L{IReactorCore.removeSystemEventTrigger} should
not be called when the event fires.
"""
eventType = 'test'
events = []
def firstBeforeTrigger():
events.append('first')
def secondBeforeTrigger():
events.append('second')
self.addTrigger('before', eventType, firstBeforeTrigger)
self.removeTrigger(
self.addTrigger('before', eventType, secondBeforeTrigger))
self.assertEqual(events, [])
reactor.fireSystemEvent(eventType)
self.assertEqual(events, ['first'])
def test_removeNonExistentSystemEventTrigger(self):
"""
Passing an object to L{IReactorCore.removeSystemEventTrigger} which was
not returned by a previous call to
L{IReactorCore.addSystemEventTrigger} or which has already been passed
to C{removeSystemEventTrigger} should result in L{TypeError},
L{KeyError}, or L{ValueError} being raised.
"""
b = self.addTrigger('during', 'test', lambda: None)
self.removeTrigger(b)
self.assertRaises(
TypeError, reactor.removeSystemEventTrigger, None)
self.assertRaises(
ValueError, reactor.removeSystemEventTrigger, b)
self.assertRaises(
KeyError,
reactor.removeSystemEventTrigger,
(b[0], ('xxx',) + b[1][1:]))
def test_interactionBetweenDifferentEvents(self):
"""
L{IReactorCore.fireSystemEvent} should behave the same way for a
particular system event regardless of whether Deferreds are being
waited on for a different system event.
"""
events = []
firstEvent = 'first-event'
firstDeferred = Deferred()
def beforeFirstEvent():
events.append(('before', 'first'))
return firstDeferred
def afterFirstEvent():
events.append(('after', 'first'))
secondEvent = 'second-event'
secondDeferred = Deferred()
def beforeSecondEvent():
events.append(('before', 'second'))
return secondDeferred
def afterSecondEvent():
events.append(('after', 'second'))
self.addTrigger('before', firstEvent, beforeFirstEvent)
self.addTrigger('after', firstEvent, afterFirstEvent)
self.addTrigger('before', secondEvent, beforeSecondEvent)
self.addTrigger('after', secondEvent, afterSecondEvent)
self.assertEqual(events, [])
# After this, firstEvent should be stuck before 'during' waiting for
# firstDeferred.
reactor.fireSystemEvent(firstEvent)
self.assertEqual(events, [('before', 'first')])
# After this, secondEvent should be stuck before 'during' waiting for
# secondDeferred.
reactor.fireSystemEvent(secondEvent)
self.assertEqual(events, [('before', 'first'), ('before', 'second')])
# After this, firstEvent should have finished completely, but
# secondEvent should be at the same place.
firstDeferred.callback(None)
self.assertEqual(events, [('before', 'first'), ('before', 'second'),
('after', 'first')])
# After this, secondEvent should have finished completely.
secondDeferred.callback(None)
self.assertEqual(events, [('before', 'first'), ('before', 'second'),
('after', 'first'), ('after', 'second')])
class TimeTests(unittest.TestCase):
"""
Tests for the IReactorTime part of the reactor.
"""
def test_seconds(self):
"""
L{twisted.internet.reactor.seconds} should return something
like a number.
1. This test specifically does not assert any relation to the
"system time" as returned by L{time.time} or
L{twisted.python.runtime.seconds}, because at some point we
may find a better option for scheduling calls than
wallclock-time.
2. This test *also* does not assert anything about the type of
the result, because operations may not return ints or
floats: For example, datetime-datetime == timedelta(0).
"""
now = reactor.seconds()
self.assertEqual(now-now+now, now)
def test_callLaterUsesReactorSecondsInDelayedCall(self):
"""
L{reactor.callLater<twisted.internet.interfaces.IReactorTime.callLater>}
should use the reactor's seconds factory
to produce the time at which the DelayedCall will be called.
"""
oseconds = reactor.seconds
reactor.seconds = lambda: 100
try:
call = reactor.callLater(5, lambda: None)
self.assertEqual(call.getTime(), 105)
finally:
reactor.seconds = oseconds
call.cancel()
def test_callLaterUsesReactorSecondsAsDelayedCallSecondsFactory(self):
"""
L{reactor.callLater<twisted.internet.interfaces.IReactorTime.callLater>}
should propagate its own seconds factory
to the DelayedCall to use as its own seconds factory.
"""
oseconds = reactor.seconds
reactor.seconds = lambda: 100
try:
call = reactor.callLater(5, lambda: None)
self.assertEqual(call.seconds(), 100)
finally:
reactor.seconds = oseconds
call.cancel()
def test_callLater(self):
"""
Test that a DelayedCall really calls the function it is
supposed to call.
"""
d = Deferred()
reactor.callLater(0, d.callback, None)
d.addCallback(self.assertEqual, None)
return d
def test_callLaterReset(self):
"""
A L{DelayedCall} that is reset will be scheduled at the new time.
"""
call = reactor.callLater(2, passthru, passthru)
self.addCleanup(call.cancel)
origTime = call.time
call.reset(1)
self.assertNotEqual(call.time, origTime)
def test_cancelDelayedCall(self):
"""
Test that when a DelayedCall is cancelled it does not run.
"""
called = []
def function():
called.append(None)
call = reactor.callLater(0, function)
call.cancel()
# Schedule a call in two "iterations" to check to make sure that the
# above call never ran.
d = Deferred()
def check():
try:
self.assertEqual(called, [])
except:
d.errback()
else:
d.callback(None)
reactor.callLater(0, reactor.callLater, 0, check)
return d
def test_cancelCancelledDelayedCall(self):
"""
Test that cancelling a DelayedCall which has already been cancelled
raises the appropriate exception.
"""
call = reactor.callLater(0, lambda: None)
call.cancel()
self.assertRaises(error.AlreadyCancelled, call.cancel)
def test_cancelCalledDelayedCallSynchronous(self):
"""
Test that cancelling a DelayedCall in the DelayedCall's function as
that function is being invoked by the DelayedCall raises the
appropriate exception.
"""
d = Deferred()
def later():
try:
self.assertRaises(error.AlreadyCalled, call.cancel)
except:
d.errback()
else:
d.callback(None)
call = reactor.callLater(0, later)
return d
def test_cancelCalledDelayedCallAsynchronous(self):
"""
Test that cancelling a DelayedCall after it has run its function
raises the appropriate exception.
"""
d = Deferred()
def check():
try:
self.assertRaises(error.AlreadyCalled, call.cancel)
except:
d.errback()
else:
d.callback(None)
def later():
reactor.callLater(0, check)
call = reactor.callLater(0, later)
return d
def testCallLaterTime(self):
d = reactor.callLater(10, lambda: None)
try:
self.assertTrue(d.getTime() - (time.time() + 10) < 1)
finally:
d.cancel()
def testDelayedCallStringification(self):
# Mostly just make sure str() isn't going to raise anything for
# DelayedCalls within reason.
dc = reactor.callLater(0, lambda x, y: None, 'x', y=10)
str(dc)
dc.reset(5)
str(dc)
dc.cancel()
str(dc)
dc = reactor.callLater(0, lambda: None, x=[({'hello': u'world'}, 10j), reactor], *range(10))
str(dc)
dc.cancel()
str(dc)
def calledBack(ignored):
str(dc)
d = Deferred().addCallback(calledBack)
dc = reactor.callLater(0, d.callback, None)
str(dc)
return d
def testDelayedCallSecondsOverride(self):
"""
Test that the C{seconds} argument to DelayedCall gets used instead of
the default timing function, if it is not None.
"""
def seconds():
return 10
dc = base.DelayedCall(5, lambda: None, (), {}, lambda dc: None,
lambda dc: None, seconds)
self.assertEqual(dc.getTime(), 5)
dc.reset(3)
self.assertEqual(dc.getTime(), 13)
class CallFromThreadStopsAndWakeUpTests(unittest.TestCase):
def testWakeUp(self):
# Make sure other threads can wake up the reactor
d = Deferred()
def wake():
time.sleep(0.1)
# callFromThread will call wakeUp for us
reactor.callFromThread(d.callback, None)
reactor.callInThread(wake)
return d
if interfaces.IReactorThreads(reactor, None) is None:
testWakeUp.skip = "Nothing to wake up for without thread support"
def _stopCallFromThreadCallback(self):
self.stopped = True
def _callFromThreadCallback(self, d):
reactor.callFromThread(self._callFromThreadCallback2, d)
reactor.callLater(0, self._stopCallFromThreadCallback)
def _callFromThreadCallback2(self, d):
try:
self.assertTrue(self.stopped)
except:
# Send the error to the deferred
d.errback()
else:
d.callback(None)
def testCallFromThreadStops(self):
"""
Ensure that callFromThread from inside a callFromThread
callback doesn't sit in an infinite loop and lets other
things happen too.
"""
self.stopped = False
d = defer.Deferred()
reactor.callFromThread(self._callFromThreadCallback, d)
return d
class DelayedTests(unittest.TestCase):
def setUp(self):
self.finished = 0
self.counter = 0
self.timers = {}
self.deferred = defer.Deferred()
def tearDown(self):
for t in self.timers.values():
t.cancel()
def checkTimers(self):
l1 = self.timers.values()
l2 = list(reactor.getDelayedCalls())
# There should be at least the calls we put in. There may be other
# calls that are none of our business and that we should ignore,
# though.
missing = []
for dc in l1:
if dc not in l2:
missing.append(dc)
if missing:
self.finished = 1
self.assertFalse(missing, "Should have been missing no calls, instead "
+ "was missing " + repr(missing))
def callback(self, tag):
del self.timers[tag]
self.checkTimers()
def addCallback(self, tag):
self.callback(tag)
self.addTimer(15, self.callback)
def done(self, tag):
self.finished = 1
self.callback(tag)
self.deferred.callback(None)
def addTimer(self, when, callback):
self.timers[self.counter] = reactor.callLater(when * 0.01, callback,
self.counter)
self.counter += 1
self.checkTimers()
def testGetDelayedCalls(self):
if not hasattr(reactor, "getDelayedCalls"):
return
# This is not a race because we don't do anything which might call
# the reactor until we have all the timers set up. If we did, this
# test might fail on slow systems.
self.checkTimers()
self.addTimer(35, self.done)
self.addTimer(20, self.callback)
self.addTimer(30, self.callback)
which = self.counter
self.addTimer(29, self.callback)
self.addTimer(25, self.addCallback)
self.addTimer(26, self.callback)
self.timers[which].cancel()
del self.timers[which]
self.checkTimers()
self.deferred.addCallback(lambda x : self.checkTimers())
return self.deferred
def test_active(self):
"""
L{IDelayedCall.active} returns False once the call has run.
"""
dcall = reactor.callLater(0.01, self.deferred.callback, True)
self.assertTrue(dcall.active())
def checkDeferredCall(success):
self.assertFalse(dcall.active())
return success
self.deferred.addCallback(checkDeferredCall)
return self.deferred
resolve_helper = """
from __future__ import print_function
import %(reactor)s
%(reactor)s.install()
from twisted.internet import reactor
class Foo:
def __init__(self):
reactor.callWhenRunning(self.start)
self.timer = reactor.callLater(3, self.failed)
def start(self):
reactor.resolve('localhost').addBoth(self.done)
def done(self, res):
print('done', res)
reactor.stop()
def failed(self):
print('failed')
self.timer = None
reactor.stop()
f = Foo()
reactor.run()
"""
class ChildResolveProtocol(protocol.ProcessProtocol):