forked from twisted/twisted
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_defer.py
3102 lines (2509 loc) · 101 KB
/
test_defer.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.
"""
Test cases for L{twisted.internet.defer}.
"""
from __future__ import division, absolute_import
import warnings
import gc, traceback
import re
from twisted.python.compat import _PY3, _PY34PLUS
if _PY34PLUS:
from asyncio import new_event_loop, Future, CancelledError
asyncSkip = None
else:
asyncSkip = "asyncio not available before python 3.4"
from twisted.python import failure, log
from twisted.internet import defer, reactor
from twisted.internet.task import Clock
from twisted.trial import unittest
class GenericError(Exception):
pass
def getDivisionFailure(*args, **kwargs):
"""
Make a L{failure.Failure} of a divide-by-zero error.
@param args: Any C{*args} are passed to Failure's constructor.
@param kwargs: Any C{**kwargs} are passed to Failure's constructor.
"""
try:
1/0
except:
f = failure.Failure(*args, **kwargs)
return f
def fakeCallbackCanceller(deferred):
"""
A fake L{defer.Deferred} canceller which callbacks the L{defer.Deferred}
with C{str} "Callback Result" when cancelling it.
@param deferred: The cancelled L{defer.Deferred}.
"""
deferred.callback("Callback Result")
class ImmediateFailureMixin(object):
"""
Add additional assertion methods.
"""
def assertImmediateFailure(self, deferred, exception):
"""
Assert that the given Deferred current result is a Failure with the
given exception.
@return: The exception instance in the Deferred.
"""
failures = []
deferred.addErrback(failures.append)
self.assertEqual(len(failures), 1)
self.assertTrue(failures[0].check(exception))
return failures[0].value
class UtilTests(unittest.TestCase):
"""
Tests for utility functions.
"""
def test_logErrorReturnsError(self):
"""
L{defer.logError} returns the given error.
"""
error = failure.Failure(RuntimeError())
result = defer.logError(error)
self.flushLoggedErrors(RuntimeError)
self.assertIs(error, result)
def test_logErrorLogsError(self):
"""
L{defer.logError} logs the given error.
"""
error = failure.Failure(RuntimeError())
defer.logError(error)
errors = self.flushLoggedErrors(RuntimeError)
self.assertEqual(errors, [error])
def test_logErrorLogsErrorNoRepr(self):
"""
The text logged by L{defer.logError} has no repr of the failure.
"""
output = []
def emit(eventDict):
output.append(log.textFromEventDict(eventDict))
log.addObserver(emit)
error = failure.Failure(RuntimeError())
defer.logError(error)
self.flushLoggedErrors(RuntimeError)
self.assertTrue(output[0].startswith("Unhandled Error\nTraceback "))
class DeferredTests(unittest.SynchronousTestCase, ImmediateFailureMixin):
def setUp(self):
self.callbackResults = None
self.errbackResults = None
self.callback2Results = None
# Restore the debug flag to its original state when done.
self.addCleanup(defer.setDebugging, defer.getDebugging())
def _callback(self, *args, **kw):
self.callbackResults = args, kw
return args[0]
def _callback2(self, *args, **kw):
self.callback2Results = args, kw
def _errback(self, *args, **kw):
self.errbackResults = args, kw
def testCallbackWithoutArgs(self):
deferred = defer.Deferred()
deferred.addCallback(self._callback)
deferred.callback("hello")
self.assertIsNone(self.errbackResults)
self.assertEqual(self.callbackResults, (('hello',), {}))
def testCallbackWithArgs(self):
deferred = defer.Deferred()
deferred.addCallback(self._callback, "world")
deferred.callback("hello")
self.assertIsNone(self.errbackResults)
self.assertEqual(self.callbackResults, (('hello', 'world'), {}))
def testCallbackWithKwArgs(self):
deferred = defer.Deferred()
deferred.addCallback(self._callback, world="world")
deferred.callback("hello")
self.assertIsNone(self.errbackResults)
self.assertEqual(self.callbackResults,
(('hello',), {'world': 'world'}))
def testTwoCallbacks(self):
deferred = defer.Deferred()
deferred.addCallback(self._callback)
deferred.addCallback(self._callback2)
deferred.callback("hello")
self.assertIsNone(self.errbackResults)
self.assertEqual(self.callbackResults,
(('hello',), {}))
self.assertEqual(self.callback2Results,
(('hello',), {}))
def testDeferredList(self):
defr1 = defer.Deferred()
defr2 = defer.Deferred()
defr3 = defer.Deferred()
dl = defer.DeferredList([defr1, defr2, defr3])
result = []
def cb(resultList, result=result):
result.extend(resultList)
def catch(err):
return None
dl.addCallbacks(cb, cb)
defr1.callback("1")
defr2.addErrback(catch)
# "catch" is added to eat the GenericError that will be passed on by
# the DeferredList's callback on defr2. If left unhandled, the
# Failure object would cause a log.err() warning about "Unhandled
# error in Deferred". Twisted's pyunit watches for log.err calls and
# treats them as failures. So "catch" must eat the error to prevent
# it from flunking the test.
defr2.errback(GenericError("2"))
defr3.callback("3")
self.assertEqual([result[0],
#result[1][1] is now a Failure instead of an Exception
(result[1][0], str(result[1][1].value)),
result[2]],
[(defer.SUCCESS, "1"),
(defer.FAILURE, "2"),
(defer.SUCCESS, "3")])
def testEmptyDeferredList(self):
result = []
def cb(resultList, result=result):
result.append(resultList)
dl = defer.DeferredList([])
dl.addCallbacks(cb)
self.assertEqual(result, [[]])
result[:] = []
dl = defer.DeferredList([], fireOnOneCallback=1)
dl.addCallbacks(cb)
self.assertEqual(result, [])
def testDeferredListFireOnOneError(self):
defr1 = defer.Deferred()
defr2 = defer.Deferred()
defr3 = defer.Deferred()
dl = defer.DeferredList([defr1, defr2, defr3], fireOnOneErrback=1)
result = []
dl.addErrback(result.append)
# consume errors after they pass through the DeferredList (to avoid
# 'Unhandled error in Deferred'.
def catch(err):
return None
defr2.addErrback(catch)
# fire one Deferred's callback, no result yet
defr1.callback("1")
self.assertEqual(result, [])
# fire one Deferred's errback -- now we have a result
defr2.errback(GenericError("from def2"))
self.assertEqual(len(result), 1)
# extract the result from the list
aFailure = result[0]
# the type of the failure is a FirstError
self.assertTrue(issubclass(aFailure.type, defer.FirstError),
'issubclass(aFailure.type, defer.FirstError) failed: '
"failure's type is %r" % (aFailure.type,)
)
firstError = aFailure.value
# check that the GenericError("2") from the deferred at index 1
# (defr2) is intact inside failure.value
self.assertEqual(firstError.subFailure.type, GenericError)
self.assertEqual(firstError.subFailure.value.args, ("from def2",))
self.assertEqual(firstError.index, 1)
def testDeferredListDontConsumeErrors(self):
d1 = defer.Deferred()
dl = defer.DeferredList([d1])
errorTrap = []
d1.addErrback(errorTrap.append)
result = []
dl.addCallback(result.append)
d1.errback(GenericError('Bang'))
self.assertEqual('Bang', errorTrap[0].value.args[0])
self.assertEqual(1, len(result))
self.assertEqual('Bang', result[0][0][1].value.args[0])
def testDeferredListConsumeErrors(self):
d1 = defer.Deferred()
dl = defer.DeferredList([d1], consumeErrors=True)
errorTrap = []
d1.addErrback(errorTrap.append)
result = []
dl.addCallback(result.append)
d1.errback(GenericError('Bang'))
self.assertEqual([], errorTrap)
self.assertEqual(1, len(result))
self.assertEqual('Bang', result[0][0][1].value.args[0])
def testDeferredListFireOnOneErrorWithAlreadyFiredDeferreds(self):
# Create some deferreds, and errback one
d1 = defer.Deferred()
d2 = defer.Deferred()
d1.errback(GenericError('Bang'))
# *Then* build the DeferredList, with fireOnOneErrback=True
dl = defer.DeferredList([d1, d2], fireOnOneErrback=True)
result = []
dl.addErrback(result.append)
self.assertEqual(1, len(result))
d1.addErrback(lambda e: None) # Swallow error
def testDeferredListWithAlreadyFiredDeferreds(self):
# Create some deferreds, and err one, call the other
d1 = defer.Deferred()
d2 = defer.Deferred()
d1.errback(GenericError('Bang'))
d2.callback(2)
# *Then* build the DeferredList
dl = defer.DeferredList([d1, d2])
result = []
dl.addCallback(result.append)
self.assertEqual(1, len(result))
d1.addErrback(lambda e: None) # Swallow error
def test_cancelDeferredList(self):
"""
When cancelling an unfired L{defer.DeferredList}, cancel every
L{defer.Deferred} in the list.
"""
deferredOne = defer.Deferred()
deferredTwo = defer.Deferred()
deferredList = defer.DeferredList([deferredOne, deferredTwo])
deferredList.cancel()
self.failureResultOf(deferredOne, defer.CancelledError)
self.failureResultOf(deferredTwo, defer.CancelledError)
def test_cancelDeferredListCallback(self):
"""
When cancelling an unfired L{defer.DeferredList} without the
C{fireOnOneCallback} and C{fireOnOneErrback} flags set, the
L{defer.DeferredList} will be callback with a C{list} of
(success, result) C{tuple}s.
"""
deferredOne = defer.Deferred(fakeCallbackCanceller)
deferredTwo = defer.Deferred()
deferredList = defer.DeferredList([deferredOne, deferredTwo])
deferredList.cancel()
self.failureResultOf(deferredTwo, defer.CancelledError)
result = self.successResultOf(deferredList)
self.assertTrue(result[0][0])
self.assertEqual(result[0][1], "Callback Result")
self.assertFalse(result[1][0])
self.assertTrue(result[1][1].check(defer.CancelledError))
def test_cancelDeferredListWithFireOnOneCallback(self):
"""
When cancelling an unfired L{defer.DeferredList} with the flag
C{fireOnOneCallback} set, cancel every L{defer.Deferred} in the list.
"""
deferredOne = defer.Deferred()
deferredTwo = defer.Deferred()
deferredList = defer.DeferredList([deferredOne, deferredTwo],
fireOnOneCallback=True)
deferredList.cancel()
self.failureResultOf(deferredOne, defer.CancelledError)
self.failureResultOf(deferredTwo, defer.CancelledError)
def test_cancelDeferredListWithFireOnOneCallbackAndDeferredCallback(self):
"""
When cancelling an unfired L{defer.DeferredList} with the flag
C{fireOnOneCallback} set, if one of the L{defer.Deferred} callbacks
in its canceller, the L{defer.DeferredList} will callback with the
result and the index of the L{defer.Deferred} in a C{tuple}.
"""
deferredOne = defer.Deferred(fakeCallbackCanceller)
deferredTwo = defer.Deferred()
deferredList = defer.DeferredList([deferredOne, deferredTwo],
fireOnOneCallback=True)
deferredList.cancel()
self.failureResultOf(deferredTwo, defer.CancelledError)
result = self.successResultOf(deferredList)
self.assertEqual(result, ("Callback Result", 0))
def test_cancelDeferredListWithFireOnOneErrback(self):
"""
When cancelling an unfired L{defer.DeferredList} with the flag
C{fireOnOneErrback} set, cancel every L{defer.Deferred} in the list.
"""
deferredOne = defer.Deferred()
deferredTwo = defer.Deferred()
deferredList = defer.DeferredList([deferredOne, deferredTwo],
fireOnOneErrback=True)
deferredList.cancel()
self.failureResultOf(deferredOne, defer.CancelledError)
self.failureResultOf(deferredTwo, defer.CancelledError)
deferredListFailure = self.failureResultOf(deferredList,
defer.FirstError)
firstError = deferredListFailure.value
self.assertTrue(firstError.subFailure.check(defer.CancelledError))
def test_cancelDeferredListWithFireOnOneErrbackAllDeferredsCallback(self):
"""
When cancelling an unfired L{defer.DeferredList} with the flag
C{fireOnOneErrback} set, if all the L{defer.Deferred} callbacks
in its canceller, the L{defer.DeferredList} will callback with a
C{list} of (success, result) C{tuple}s.
"""
deferredOne = defer.Deferred(fakeCallbackCanceller)
deferredTwo = defer.Deferred(fakeCallbackCanceller)
deferredList = defer.DeferredList([deferredOne, deferredTwo],
fireOnOneErrback=True)
deferredList.cancel()
result = self.successResultOf(deferredList)
self.assertTrue(result[0][0])
self.assertEqual(result[0][1], "Callback Result")
self.assertTrue(result[1][0])
self.assertEqual(result[1][1], "Callback Result")
def test_cancelDeferredListWithOriginalDeferreds(self):
"""
Cancelling a L{defer.DeferredList} will cancel the original
L{defer.Deferred}s passed in.
"""
deferredOne = defer.Deferred()
deferredTwo = defer.Deferred()
argumentList = [deferredOne, deferredTwo]
deferredList = defer.DeferredList(argumentList)
deferredThree = defer.Deferred()
argumentList.append(deferredThree)
deferredList.cancel()
self.failureResultOf(deferredOne, defer.CancelledError)
self.failureResultOf(deferredTwo, defer.CancelledError)
self.assertNoResult(deferredThree)
def test_cancelDeferredListWithException(self):
"""
Cancelling a L{defer.DeferredList} will cancel every L{defer.Deferred}
in the list even exceptions raised from the C{cancel} method of the
L{defer.Deferred}s.
"""
def cancellerRaisesException(deferred):
"""
A L{defer.Deferred} canceller that raises an exception.
@param deferred: The cancelled L{defer.Deferred}.
"""
raise RuntimeError("test")
deferredOne = defer.Deferred(cancellerRaisesException)
deferredTwo = defer.Deferred()
deferredList = defer.DeferredList([deferredOne, deferredTwo])
deferredList.cancel()
self.failureResultOf(deferredTwo, defer.CancelledError)
errors = self.flushLoggedErrors(RuntimeError)
self.assertEqual(len(errors), 1)
def test_cancelFiredOnOneCallbackDeferredList(self):
"""
When a L{defer.DeferredList} has fired because one L{defer.Deferred} in
the list fired with a non-failure result, the cancellation will do
nothing instead of cancelling the rest of the L{defer.Deferred}s.
"""
deferredOne = defer.Deferred()
deferredTwo = defer.Deferred()
deferredList = defer.DeferredList([deferredOne, deferredTwo],
fireOnOneCallback=True)
deferredOne.callback(None)
deferredList.cancel()
self.assertNoResult(deferredTwo)
def test_cancelFiredOnOneErrbackDeferredList(self):
"""
When a L{defer.DeferredList} has fired because one L{defer.Deferred} in
the list fired with a failure result, the cancellation will do
nothing instead of cancelling the rest of the L{defer.Deferred}s.
"""
deferredOne = defer.Deferred()
deferredTwo = defer.Deferred()
deferredList = defer.DeferredList([deferredOne, deferredTwo],
fireOnOneErrback=True)
deferredOne.errback(GenericError("test"))
deferredList.cancel()
self.assertNoResult(deferredTwo)
self.failureResultOf(deferredOne, GenericError)
self.failureResultOf(deferredList, defer.FirstError)
def testImmediateSuccess(self):
l = []
d = defer.succeed("success")
d.addCallback(l.append)
self.assertEqual(l, ["success"])
def testImmediateFailure(self):
l = []
d = defer.fail(GenericError("fail"))
d.addErrback(l.append)
self.assertEqual(str(l[0].value), "fail")
def testPausedFailure(self):
l = []
d = defer.fail(GenericError("fail"))
d.pause()
d.addErrback(l.append)
self.assertEqual(l, [])
d.unpause()
self.assertEqual(str(l[0].value), "fail")
def testCallbackErrors(self):
l = []
d = defer.Deferred().addCallback(lambda _: 1 // 0).addErrback(l.append)
d.callback(1)
self.assertIsInstance(l[0].value, ZeroDivisionError)
l = []
d = defer.Deferred().addCallback(
lambda _: failure.Failure(ZeroDivisionError())).addErrback(l.append)
d.callback(1)
self.assertIsInstance(l[0].value, ZeroDivisionError)
def testUnpauseBeforeCallback(self):
d = defer.Deferred()
d.pause()
d.addCallback(self._callback)
d.unpause()
def testReturnDeferred(self):
d = defer.Deferred()
d2 = defer.Deferred()
d2.pause()
d.addCallback(lambda r, d2=d2: d2)
d.addCallback(self._callback)
d.callback(1)
assert self.callbackResults is None, "Should not have been called yet."
d2.callback(2)
assert self.callbackResults is None, "Still should not have been called yet."
d2.unpause()
assert self.callbackResults[0][0] == 2, "Result should have been from second deferred:%s" % (self.callbackResults,)
def test_chainedPausedDeferredWithResult(self):
"""
When a paused Deferred with a result is returned from a callback on
another Deferred, the other Deferred is chained to the first and waits
for it to be unpaused.
"""
expected = object()
paused = defer.Deferred()
paused.callback(expected)
paused.pause()
chained = defer.Deferred()
chained.addCallback(lambda ignored: paused)
chained.callback(None)
result = []
chained.addCallback(result.append)
self.assertEqual(result, [])
paused.unpause()
self.assertEqual(result, [expected])
def test_pausedDeferredChained(self):
"""
A paused Deferred encountered while pushing a result forward through a
chain does not prevent earlier Deferreds from continuing to execute
their callbacks.
"""
first = defer.Deferred()
second = defer.Deferred()
first.addCallback(lambda ignored: second)
first.callback(None)
first.pause()
second.callback(None)
result = []
second.addCallback(result.append)
self.assertEqual(result, [None])
def test_gatherResults(self):
# test successful list of deferreds
l = []
defer.gatherResults([defer.succeed(1), defer.succeed(2)]).addCallback(l.append)
self.assertEqual(l, [[1, 2]])
# test failing list of deferreds
l = []
dl = [defer.succeed(1), defer.fail(ValueError())]
defer.gatherResults(dl).addErrback(l.append)
self.assertEqual(len(l), 1)
self.assertIsInstance(l[0], failure.Failure)
# get rid of error
dl[1].addErrback(lambda e: 1)
def test_gatherResultsWithConsumeErrors(self):
"""
If a L{Deferred} in the list passed to L{gatherResults} fires with a
failure and C{consumerErrors} is C{True}, the failure is converted to a
L{None} result on that L{Deferred}.
"""
# test successful list of deferreds
dgood = defer.succeed(1)
dbad = defer.fail(RuntimeError("oh noes"))
d = defer.gatherResults([dgood, dbad], consumeErrors=True)
unconsumedErrors = []
dbad.addErrback(unconsumedErrors.append)
gatheredErrors = []
d.addErrback(gatheredErrors.append)
self.assertEqual((len(unconsumedErrors), len(gatheredErrors)),
(0, 1))
self.assertIsInstance(gatheredErrors[0].value, defer.FirstError)
firstError = gatheredErrors[0].value.subFailure
self.assertIsInstance(firstError.value, RuntimeError)
def test_cancelGatherResults(self):
"""
When cancelling the L{defer.gatherResults} call, all the
L{defer.Deferred}s in the list will be cancelled.
"""
deferredOne = defer.Deferred()
deferredTwo = defer.Deferred()
result = defer.gatherResults([deferredOne, deferredTwo])
result.cancel()
self.failureResultOf(deferredOne, defer.CancelledError)
self.failureResultOf(deferredTwo, defer.CancelledError)
gatherResultsFailure = self.failureResultOf(result, defer.FirstError)
firstError = gatherResultsFailure.value
self.assertTrue(firstError.subFailure.check(defer.CancelledError))
def test_cancelGatherResultsWithAllDeferredsCallback(self):
"""
When cancelling the L{defer.gatherResults} call, if all the
L{defer.Deferred}s callback in their canceller, the L{defer.Deferred}
returned by L{defer.gatherResults} will be callbacked with the C{list}
of the results.
"""
deferredOne = defer.Deferred(fakeCallbackCanceller)
deferredTwo = defer.Deferred(fakeCallbackCanceller)
result = defer.gatherResults([deferredOne, deferredTwo])
result.cancel()
callbackResult = self.successResultOf(result)
self.assertEqual(callbackResult[0], "Callback Result")
self.assertEqual(callbackResult[1], "Callback Result")
def test_maybeDeferredSync(self):
"""
L{defer.maybeDeferred} should retrieve the result of a synchronous
function and pass it to its resulting L{defer.Deferred}.
"""
S, E = [], []
d = defer.maybeDeferred((lambda x: x + 5), 10)
d.addCallbacks(S.append, E.append)
self.assertEqual(E, [])
self.assertEqual(S, [15])
def test_maybeDeferredSyncError(self):
"""
L{defer.maybeDeferred} should catch exception raised by a synchronous
function and errback its resulting L{defer.Deferred} with it.
"""
S, E = [], []
try:
'10' + 5
except TypeError as e:
expected = str(e)
d = defer.maybeDeferred((lambda x: x + 5), '10')
d.addCallbacks(S.append, E.append)
self.assertEqual(S, [])
self.assertEqual(len(E), 1)
self.assertEqual(str(E[0].value), expected)
def test_maybeDeferredAsync(self):
"""
L{defer.maybeDeferred} should let L{defer.Deferred} instance pass by
so that original result is the same.
"""
d = defer.Deferred()
d2 = defer.maybeDeferred(lambda: d)
d.callback('Success')
result = []
d2.addCallback(result.append)
self.assertEqual(result, ['Success'])
def test_maybeDeferredAsyncError(self):
"""
L{defer.maybeDeferred} should let L{defer.Deferred} instance pass by
so that L{failure.Failure} returned by the original instance is the
same.
"""
d = defer.Deferred()
d2 = defer.maybeDeferred(lambda: d)
d.errback(failure.Failure(RuntimeError()))
self.assertImmediateFailure(d2, RuntimeError)
def test_innerCallbacksPreserved(self):
"""
When a L{Deferred} encounters a result which is another L{Deferred}
which is waiting on a third L{Deferred}, the middle L{Deferred}'s
callbacks are executed after the third L{Deferred} fires and before the
first receives a result.
"""
results = []
failures = []
inner = defer.Deferred()
def cb(result):
results.append(('start-of-cb', result))
d = defer.succeed('inner')
def firstCallback(result):
results.append(('firstCallback', 'inner'))
return inner
def secondCallback(result):
results.append(('secondCallback', result))
return result * 2
d.addCallback(firstCallback).addCallback(secondCallback)
d.addErrback(failures.append)
return d
outer = defer.succeed('outer')
outer.addCallback(cb)
inner.callback('orange')
outer.addCallback(results.append)
inner.addErrback(failures.append)
outer.addErrback(failures.append)
self.assertEqual([], failures)
self.assertEqual(
results,
[('start-of-cb', 'outer'),
('firstCallback', 'inner'),
('secondCallback', 'orange'),
'orangeorange'])
def test_continueCallbackNotFirst(self):
"""
The continue callback of a L{Deferred} waiting for another L{Deferred}
is not necessarily the first one. This is somewhat a whitebox test
checking that we search for that callback among the whole list of
callbacks.
"""
results = []
failures = []
a = defer.Deferred()
def cb(result):
results.append(('cb', result))
d = defer.Deferred()
def firstCallback(ignored):
results.append(('firstCallback', ignored))
return defer.gatherResults([a])
def secondCallback(result):
results.append(('secondCallback', result))
d.addCallback(firstCallback)
d.addCallback(secondCallback)
d.addErrback(failures.append)
d.callback(None)
return d
outer = defer.succeed('outer')
outer.addCallback(cb)
outer.addErrback(failures.append)
self.assertEqual([('cb', 'outer'), ('firstCallback', None)], results)
a.callback('withers')
self.assertEqual([], failures)
self.assertEqual(
results,
[('cb', 'outer'),
('firstCallback', None),
('secondCallback', ['withers'])])
def test_callbackOrderPreserved(self):
"""
A callback added to a L{Deferred} after a previous callback attached
another L{Deferred} as a result is run after the callbacks of the other
L{Deferred} are run.
"""
results = []
failures = []
a = defer.Deferred()
def cb(result):
results.append(('cb', result))
d = defer.Deferred()
def firstCallback(ignored):
results.append(('firstCallback', ignored))
return defer.gatherResults([a])
def secondCallback(result):
results.append(('secondCallback', result))
d.addCallback(firstCallback)
d.addCallback(secondCallback)
d.addErrback(failures.append)
d.callback(None)
return d
outer = defer.Deferred()
outer.addCallback(cb)
outer.addCallback(lambda x: results.append('final'))
outer.addErrback(failures.append)
outer.callback('outer')
self.assertEqual([('cb', 'outer'), ('firstCallback', None)], results)
a.callback('withers')
self.assertEqual([], failures)
self.assertEqual(
results,
[('cb', 'outer'),
('firstCallback', None),
('secondCallback', ['withers']), 'final'])
def test_reentrantRunCallbacks(self):
"""
A callback added to a L{Deferred} by a callback on that L{Deferred}
should be added to the end of the callback chain.
"""
deferred = defer.Deferred()
called = []
def callback3(result):
called.append(3)
def callback2(result):
called.append(2)
def callback1(result):
called.append(1)
deferred.addCallback(callback3)
deferred.addCallback(callback1)
deferred.addCallback(callback2)
deferred.callback(None)
self.assertEqual(called, [1, 2, 3])
def test_nonReentrantCallbacks(self):
"""
A callback added to a L{Deferred} by a callback on that L{Deferred}
should not be executed until the running callback returns.
"""
deferred = defer.Deferred()
called = []
def callback2(result):
called.append(2)
def callback1(result):
called.append(1)
deferred.addCallback(callback2)
self.assertEqual(called, [1])
deferred.addCallback(callback1)
deferred.callback(None)
self.assertEqual(called, [1, 2])
def test_reentrantRunCallbacksWithFailure(self):
"""
After an exception is raised by a callback which was added to a
L{Deferred} by a callback on that L{Deferred}, the L{Deferred} should
call the first errback with a L{Failure} wrapping that exception.
"""
exceptionMessage = "callback raised exception"
deferred = defer.Deferred()
def callback2(result):
raise Exception(exceptionMessage)
def callback1(result):
deferred.addCallback(callback2)
deferred.addCallback(callback1)
deferred.callback(None)
exception = self.assertImmediateFailure(deferred, Exception)
self.assertEqual(exception.args, (exceptionMessage,))
def test_synchronousImplicitChain(self):
"""
If a first L{Deferred} with a result is returned from a callback on a
second L{Deferred}, the result of the second L{Deferred} becomes the
result of the first L{Deferred} and the result of the first L{Deferred}
becomes L{None}.
"""
result = object()
first = defer.succeed(result)
second = defer.Deferred()
second.addCallback(lambda ign: first)
second.callback(None)
results = []
first.addCallback(results.append)
self.assertIsNone(results[0])
second.addCallback(results.append)
self.assertIs(results[1], result)
def test_asynchronousImplicitChain(self):
"""
If a first L{Deferred} without a result is returned from a callback on
a second L{Deferred}, the result of the second L{Deferred} becomes the
result of the first L{Deferred} as soon as the first L{Deferred} has
one and the result of the first L{Deferred} becomes L{None}.
"""
first = defer.Deferred()
second = defer.Deferred()
second.addCallback(lambda ign: first)
second.callback(None)
firstResult = []
first.addCallback(firstResult.append)
secondResult = []
second.addCallback(secondResult.append)
self.assertEqual(firstResult, [])
self.assertEqual(secondResult, [])
result = object()
first.callback(result)
self.assertEqual(firstResult, [None])
self.assertEqual(secondResult, [result])
def test_synchronousImplicitErrorChain(self):
"""
If a first L{Deferred} with a L{Failure} result is returned from a
callback on a second L{Deferred}, the first L{Deferred}'s result is
converted to L{None} and no unhandled error is logged when it is
garbage collected.
"""
first = defer.fail(RuntimeError("First Deferred's Failure"))
second = defer.Deferred()
second.addCallback(lambda ign, first=first: first)
second.callback(None)
firstResult = []
first.addCallback(firstResult.append)
self.assertIsNone(firstResult[0])
self.assertImmediateFailure(second, RuntimeError)
def test_asynchronousImplicitErrorChain(self):
"""
Let C{a} and C{b} be two L{Deferred}s.
If C{a} has no result and is returned from a callback on C{b} then when
C{a} fails, C{b}'s result becomes the L{Failure} that was C{a}'s result,
the result of C{a} becomes L{None} so that no unhandled error is logged
when it is garbage collected.
"""
first = defer.Deferred()
second = defer.Deferred()
second.addCallback(lambda ign: first)
second.callback(None)
secondError = []
second.addErrback(secondError.append)
firstResult = []
first.addCallback(firstResult.append)
secondResult = []
second.addCallback(secondResult.append)
self.assertEqual(firstResult, [])
self.assertEqual(secondResult, [])
first.errback(RuntimeError("First Deferred's Failure"))
self.assertTrue(secondError[0].check(RuntimeError))
self.assertEqual(firstResult, [None])
self.assertEqual(len(secondResult), 1)
def test_doubleAsynchronousImplicitChaining(self):
"""
L{Deferred} chaining is transitive.
In other words, let A, B, and C be Deferreds. If C is returned from a
callback on B and B is returned from a callback on A then when C fires,
A fires.
"""
first = defer.Deferred()
second = defer.Deferred()
second.addCallback(lambda ign: first)
third = defer.Deferred()
third.addCallback(lambda ign: second)
thirdResult = []
third.addCallback(thirdResult.append)
result = object()
# After this, second is waiting for first to tell it to continue.
second.callback(None)