twisted / twisted
Showing 2 of 4 files from the diff.

@@ -1058,7 +1058,11 @@
Loading
1058 1058
1059 1059
    @classmethod
1060 1060
    def fromCoroutine(
1061 -
        cls, coro: Coroutine["Deferred[_T]", object, _T]
1061 +
        cls,
1062 +
        coro: Union[
1063 +
            Coroutine["Deferred[_T]", Any, _T],
1064 +
            Generator["Deferred[_T]", Any, _T],
1065 +
        ],
1062 1066
    ) -> "Deferred[_T]":
1063 1067
        """
1064 1068
        Schedule the execution of a coroutine that awaits on L{Deferred}s,
@@ -1095,14 +1099,19 @@
Loading
1095 1099
1096 1100
        @raise ValueError: If C{coro} is not a coroutine or generator.
1097 1101
        """
1098 -
        if not iscoroutine(coro) and not isinstance(coro, GeneratorType):
1102 +
        # type note: Subclass of "Generator[Deferred[_T], object, _T]" and "GeneratorType" cannot exist
1103 +
        if not iscoroutine(coro) and not isinstance(coro, GeneratorType):  # type: ignore[unreachable]
1099 1104
            raise NotACoroutineError(f"{coro!r} is not a coroutine")
1100 1105
1101 1106
        return _cancellableInlineCallbacks(coro)
1102 1107
1103 1108
1104 1109
def ensureDeferred(
1105 -
    coro: Union[Coroutine["Deferred[_T]", object, "_T"], Deferred[_T]]
1110 +
    coro: Union[
1111 +
        Coroutine[Deferred[_T], Any, _T],
1112 +
        Generator[Deferred[_T], Any, _T],
1113 +
        Deferred[_T],
1114 +
    ]
1106 1115
) -> Deferred[_T]:
1107 1116
    """
1108 1117
    Schedule the execution of a coroutine that awaits/yields from L{Deferred}s,
@@ -1169,6 +1178,10 @@
Loading
1169 1178
        return -1
1170 1179
1171 1180
1181 +
_DeferredListSingleResultT = Tuple[_DeferredResultT, int]
1182 +
_DeferredListResultItemT = Tuple[bool, _DeferredResultT]
1183 +
_DeferredListResultListT = List[_DeferredListResultItemT]
1184 +
1172 1185
if TYPE_CHECKING:
1173 1186
1174 1187
    # The result type is different depending on whether fireOnOneCallback
@@ -1178,34 +1191,36 @@
Loading
1178 1191
1179 1192
    @overload
1180 1193
    def _DeferredList(
1181 -
        deferredList: Iterable[Deferred[_T]],
1194 +
        deferredList: Iterable[Deferred[_DeferredResultT]],
1182 1195
        fireOnOneCallback: Literal[True],
1183 1196
        fireOnOneErrback: bool = False,
1184 1197
        consumeErrors: bool = False,
1185 -
    ) -> Deferred[Tuple[_T, int]]:
1198 +
    ) -> Deferred[_DeferredListSingleResultT]:
1186 1199
        ...
1187 1200
1188 1201
    @overload
1189 1202
    def _DeferredList(
1190 -
        deferredList: Iterable[Deferred[_T]],
1203 +
        deferredList: Iterable[Deferred[_DeferredResultT]],
1191 1204
        fireOnOneCallback: Literal[False] = False,
1192 1205
        fireOnOneErrback: bool = False,
1193 1206
        consumeErrors: bool = False,
1194 -
    ) -> Deferred[List[Tuple[bool, _T]]]:
1207 +
    ) -> Deferred[_DeferredListResultListT]:
1195 1208
        ...
1196 1209
1197 1210
    def _DeferredList(
1198 -
        deferredList: Iterable[Deferred[_T]],
1211 +
        deferredList: Iterable[Deferred[_DeferredResultT]],
1199 1212
        fireOnOneCallback: bool = False,
1200 1213
        fireOnOneErrback: bool = False,
1201 1214
        consumeErrors: bool = False,
1202 -
    ) -> Deferred[Any]:
1215 +
    ) -> Union[
1216 +
        Deferred[_DeferredListSingleResultT], Deferred[_DeferredListResultListT]
1217 +
    ]:
1203 1218
        ...
1204 1219
1205 1220
    DeferredList = _DeferredList
1206 1221
1207 1222
1208 -
class DeferredList(Deferred[List[Tuple[bool, _DeferredResultT]]]):  # type: ignore[no-redef]
1223 +
class DeferredList(Deferred[_DeferredListResultListT]):  # type: ignore[no-redef]
1209 1224
    """
1210 1225
    L{DeferredList} is a tool for collecting the results of several Deferreds.
1211 1226
@@ -1266,7 +1281,10 @@
Loading
1266 1281
        """
1267 1282
        self._deferredList = list(deferredList)
1268 1283
1269 -
        self.resultList: List[Optional[Tuple[bool, _DeferredResultT]]] = [None] * len(
1284 +
        # Note this contains optional result values as the DeferredList is
1285 +
        # processing its results, even though the callback result will not,
1286 +
        # which is why we aren't using _DeferredListResultListT here.
1287 +
        self.resultList: List[Optional[_DeferredListResultItemT]] = [None] * len(
1270 1288
            self._deferredList
1271 1289
        )
1272 1290
        """
@@ -1314,11 +1332,10 @@
Loading
1314 1332
                assert isinstance(result, Failure)
1315 1333
                self.errback(Failure(FirstError(result, index)))
1316 1334
            elif self.finishedCount == len(self.resultList):
1317 -
                # All the None values have been replaced by results, so we can
1318 -
                # safely cast away the Optional[].
1319 -
                self.callback(
1320 -
                    cast(List[Tuple[bool, _DeferredResultT]], self.resultList)
1321 -
                )
1335 +
                # At this point, None values in self.resultList have been
1336 +
                # replaced by result values, so we cast it to
1337 +
                # _DeferredListResultListT to match the callback result type.
1338 +
                self.callback(cast(_DeferredListResultListT, self.resultList))
1322 1339
1323 1340
        if succeeded == FAILURE and self.consumeErrors:
1324 1341
            return None
@@ -1346,10 +1363,12 @@
Loading
1346 1363
1347 1364
1348 1365
def _parseDeferredListResult(
1349 -
    resultList: List[Tuple[bool, _T]], fireOnOneErrback: bool = False
1366 +
    resultList: List[_DeferredListResultItemT], fireOnOneErrback: bool = False
1350 1367
) -> List[_T]:
1351 1368
    if __debug__:
1352 -
        for success, value in resultList:
1369 +
        for result in resultList:
1370 +
            assert result is not None
1371 +
            success, value = result
1353 1372
            assert success
1354 1373
    return [x[1] for x in resultList]
1355 1374

@@ -12,28 +12,60 @@
Loading
12 12
import traceback
13 13
import re
14 14
import types
15 -
16 -
from asyncio import new_event_loop, Future, CancelledError
17 -
18 -
from twisted.python.reflect import requireModule
19 -
from twisted.python import failure, log
15 +
from typing import (
16 +
    Any,
17 +
    Callable,
18 +
    Coroutine,
19 +
    Dict,
20 +
    Generator,
21 +
    List,
22 +
    Mapping,
23 +
    Optional,
24 +
    Tuple,
25 +
    Type,
26 +
    TypeVar,
27 +
    TYPE_CHECKING,
28 +
    Union,
29 +
    cast,
30 +
)
31 +
32 +
from asyncio import new_event_loop, AbstractEventLoop, Future, CancelledError
33 +
34 +
from twisted.python import log
35 +
from twisted.python.failure import Failure
20 36
from twisted.trial import unittest
21 37
from twisted.internet import defer, reactor
38 +
from twisted.internet.defer import (
39 +
    _DeferredResultT,
40 +
    _DeferredListResultListT,
41 +
    _DeferredListSingleResultT,
42 +
    ensureDeferred,
43 +
    Deferred,
44 +
    DeferredFilesystemLock,
45 +
    DeferredList,
46 +
    DeferredLock,
47 +
    DeferredSemaphore,
48 +
    DeferredQueue,
49 +
)
22 50
from twisted.internet.task import Clock
23 51
24 52
25 -
contextvars = requireModule("contextvars")
26 -
if contextvars:
27 -
    contextvarsSkip = None
53 +
if TYPE_CHECKING:
54 +
    import contextvars
28 55
else:
29 -
    contextvarsSkip = "contextvars is not available"
56 +
    try:
57 +
        import contextvars
58 +
    except ImportError:
59 +
        contextvars = None
30 60
31 61
32 -
def ensuringDeferred(f):
62 +
def ensuringDeferred(
63 +
    f: Callable[..., Coroutine[Deferred[_DeferredResultT], Any, _DeferredResultT]]
64 +
) -> Callable[..., Deferred[_DeferredResultT]]:
33 65
    @functools.wraps(f)
34 -
    def wrapper(*args, **kwargs):
35 -
        result = f(*args, **kwargs)
36 -
        return defer.ensureDeferred(result)
66 +
    def wrapper(*args: object, **kwargs: object) -> Deferred[_DeferredResultT]:
67 +
        coro = f(*args, **kwargs)
68 +
        return Deferred.fromCoroutine(coro)
37 69
38 70
    return wrapper
39 71
@@ -42,9 +74,9 @@
Loading
42 74
    pass
43 75
44 76
45 -
def getDivisionFailure(*args, **kwargs):
77 +
def getDivisionFailure(*args: object, **kwargs: object) -> Failure:
46 78
    """
47 -
    Make a L{failure.Failure} of a divide-by-zero error.
79 +
    Make a L{Failure} of a divide-by-zero error.
48 80
49 81
    @param args: Any C{*args} are passed to Failure's constructor.
50 82
    @param kwargs: Any C{**kwargs} are passed to Failure's constructor.
@@ -52,37 +84,43 @@
Loading
52 84
    try:
53 85
        1 / 0
54 86
    except BaseException:
55 -
        f = failure.Failure(*args, **kwargs)
87 +
        f = Failure(*args, **kwargs)
56 88
    return f
57 89
58 90
59 -
def fakeCallbackCanceller(deferred):
91 +
def fakeCallbackCanceller(deferred: Deferred[str]) -> None:
60 92
    """
61 -
    A fake L{defer.Deferred} canceller which callbacks the L{defer.Deferred}
93 +
    A fake L{Deferred} canceller which callbacks the L{Deferred}
62 94
    with C{str} "Callback Result" when cancelling it.
63 95
64 -
    @param deferred: The cancelled L{defer.Deferred}.
96 +
    @param deferred: The cancelled L{Deferred}.
65 97
    """
66 98
    deferred.callback("Callback Result")
67 99
68 100
101 +
_ExceptionT = TypeVar("_ExceptionT", bound=Exception)
102 +
103 +
69 104
class ImmediateFailureMixin:
70 105
    """
71 106
    Add additional assertion methods.
72 107
    """
73 108
74 -
    def assertImmediateFailure(self, deferred, exception):
109 +
    def assertImmediateFailure(
110 +
        self, deferred: Deferred[Any], exception: Type[_ExceptionT]
111 +
    ) -> _ExceptionT:
75 112
        """
76 113
        Assert that the given Deferred current result is a Failure with the
77 114
        given exception.
78 115
79 116
        @return: The exception instance in the Deferred.
80 117
        """
81 -
        failures = []
118 +
        testCase = cast(unittest.TestCase, self)
119 +
        failures: List[Failure] = []
82 120
        deferred.addErrback(failures.append)
83 -
        self.assertEqual(len(failures), 1)
84 -
        self.assertTrue(failures[0].check(exception))
85 -
        return failures[0].value
121 +
        testCase.assertEqual(len(failures), 1)
122 +
        testCase.assertTrue(failures[0].check(exception))
123 +
        return cast(_ExceptionT, failures[0].value)
86 124
87 125
88 126
class UtilTests(unittest.TestCase):
@@ -90,38 +128,40 @@
Loading
90 128
    Tests for utility functions.
91 129
    """
92 130
93 -
    def test_logErrorReturnsError(self):
131 +
    def test_logErrorReturnsError(self) -> None:
94 132
        """
95 133
        L{defer.logError} returns the given error.
96 134
        """
97 -
        error = failure.Failure(RuntimeError())
135 +
        error = Failure(RuntimeError())
98 136
        result = defer.logError(error)
99 137
        self.flushLoggedErrors(RuntimeError)
100 138
101 139
        self.assertIs(error, result)
102 140
103 -
    def test_logErrorLogsError(self):
141 +
    def test_logErrorLogsError(self) -> None:
104 142
        """
105 143
        L{defer.logError} logs the given error.
106 144
        """
107 -
        error = failure.Failure(RuntimeError())
145 +
        error = Failure(RuntimeError())
108 146
        defer.logError(error)
109 147
        errors = self.flushLoggedErrors(RuntimeError)
110 148
111 149
        self.assertEqual(errors, [error])
112 150
113 -
    def test_logErrorLogsErrorNoRepr(self):
151 +
    def test_logErrorLogsErrorNoRepr(self) -> None:
114 152
        """
115 153
        The text logged by L{defer.logError} has no repr of the failure.
116 154
        """
117 155
        output = []
118 156
119 -
        def emit(eventDict):
120 -
            output.append(log.textFromEventDict(eventDict))
157 +
        def emit(eventDict: Dict[str, Any]) -> None:
158 +
            text = log.textFromEventDict(eventDict)
159 +
            assert text is not None
160 +
            output.append(text)
121 161
122 162
        log.addObserver(emit)
123 163
124 -
        error = failure.Failure(RuntimeError())
164 +
        error = Failure(RuntimeError())
125 165
        defer.logError(error)
126 166
        self.flushLoggedErrors(RuntimeError)
127 167
@@ -129,46 +169,53 @@
Loading
129 169
130 170
131 171
class DeferredTests(unittest.SynchronousTestCase, ImmediateFailureMixin):
132 -
    def setUp(self):
133 -
        self.callbackResults = None
134 -
        self.errbackResults = None
135 -
        self.callback2Results = None
172 +
    def setUp(self) -> None:
173 +
        self.callbackResults: Optional[
174 +
            Tuple[Tuple[object, ...], Dict[str, object]]
175 +
        ] = None
176 +
        self.callback2Results: Optional[
177 +
            Tuple[Tuple[object, ...], Dict[str, object]]
178 +
        ] = None
179 +
        self.errbackResults: Optional[
180 +
            Tuple[Tuple[Failure, ...], Dict[str, object]]
181 +
        ] = None
182 +
136 183
        # Restore the debug flag to its original state when done.
137 184
        self.addCleanup(defer.setDebugging, defer.getDebugging())
138 185
139 -
    def _callback(self, *args, **kw):
140 -
        self.callbackResults = args, kw
186 +
    def _callback(self, *args: object, **kwargs: object) -> Any:
187 +
        self.callbackResults = args, kwargs
141 188
        return args[0]
142 189
143 -
    def _callback2(self, *args, **kw):
144 -
        self.callback2Results = args, kw
190 +
    def _callback2(self, *args: object, **kwargs: object) -> None:
191 +
        self.callback2Results = args, kwargs
145 192
146 -
    def _errback(self, *args, **kw):
147 -
        self.errbackResults = args, kw
193 +
    def _errback(self, *args: Failure, **kwargs: object) -> None:
194 +
        self.errbackResults = args, kwargs
148 195
149 -
    def testCallbackWithoutArgs(self):
150 -
        deferred = defer.Deferred()
196 +
    def testCallbackWithoutArgs(self) -> None:
197 +
        deferred: Deferred[str] = Deferred()
151 198
        deferred.addCallback(self._callback)
152 199
        deferred.callback("hello")
153 200
        self.assertIsNone(self.errbackResults)
154 201
        self.assertEqual(self.callbackResults, (("hello",), {}))
155 202
156 -
    def testCallbackWithArgs(self):
157 -
        deferred = defer.Deferred()
203 +
    def testCallbackWithArgs(self) -> None:
204 +
        deferred: Deferred[str] = Deferred()
158 205
        deferred.addCallback(self._callback, "world")
159 206
        deferred.callback("hello")
160 207
        self.assertIsNone(self.errbackResults)
161 208
        self.assertEqual(self.callbackResults, (("hello", "world"), {}))
162 209
163 -
    def testCallbackWithKwArgs(self):
164 -
        deferred = defer.Deferred()
210 +
    def testCallbackWithKwArgs(self) -> None:
211 +
        deferred: Deferred[str] = Deferred()
165 212
        deferred.addCallback(self._callback, world="world")
166 213
        deferred.callback("hello")
167 214
        self.assertIsNone(self.errbackResults)
168 215
        self.assertEqual(self.callbackResults, (("hello",), {"world": "world"}))
169 216
170 -
    def testTwoCallbacks(self):
171 -
        deferred = defer.Deferred()
217 +
    def testTwoCallbacks(self) -> None:
218 +
        deferred: Deferred[str] = Deferred()
172 219
        deferred.addCallback(self._callback)
173 220
        deferred.addCallback(self._callback2)
174 221
        deferred.callback("hello")
@@ -176,55 +223,73 @@
Loading
176 223
        self.assertEqual(self.callbackResults, (("hello",), {}))
177 224
        self.assertEqual(self.callback2Results, (("hello",), {}))
178 225
179 -
    def test_addCallbacksNoneErrback(self):
226 +
    def test_addCallbacksNoneErrback(self) -> None:
180 227
        """
181 228
        If given None for an errback, addCallbacks uses a pass-through.
182 229
        """
183 230
        error = GenericError("oopsie")
184 -
        deferred = defer.Deferred()
185 -
        deferred.addCallbacks(self._callback, None)
231 +
        deferred: Deferred[None] = Deferred()
232 +
        deferred.addCallbacks(self._callback, cast(Callable[..., object], None))
186 233
        deferred.errback(error)
187 234
        deferred.addErrback(self._errback)
188 235
        self.assertIsNone(self.callbackResults)
236 +
        assert self.errbackResults is not None
189 237
        self.assertEqual(len(self.errbackResults[0]), 1)
190 238
        self.assertEqual(self.errbackResults[0][0].value, error)
191 239
        self.assertEqual(self.errbackResults[1], {})
192 240
193 -
    def test_addCallbacksNoneCallbackArgs(self):
241 +
    def test_addCallbacksNoneCallbackArgs(self) -> None:
194 242
        """
195 243
        If given None as a callback args and kwargs, () and {} are used.
196 244
        """
197 -
        deferred = defer.Deferred()
198 -
        deferred.addCallbacks(self._callback, self._errback, None, None, (), {})
245 +
        deferred: Deferred[str] = Deferred()
246 +
        deferred.addCallbacks(
247 +
            self._callback,
248 +
            self._errback,
249 +
            cast(Tuple[object], None),
250 +
            cast(Mapping[str, object], None),
251 +
            (),
252 +
            {},
253 +
        )
199 254
        deferred.callback("hello")
200 255
        self.assertIsNone(self.errbackResults)
201 256
        self.assertEqual(self.callbackResults, (("hello",), {}))
202 257
203 -
    def test_addCallbacksNoneErrbackArgs(self):
258 +
    def test_addCallbacksNoneErrbackArgs(self) -> None:
204 259
        """
205 260
        If given None as a errback args and kwargs, () and {} are used.
206 261
        """
207 262
        error = GenericError("oopsie")
208 -
        deferred = defer.Deferred()
209 -
        deferred.addCallbacks(self._callback, self._errback, (), {}, None, None)
263 +
        deferred: Deferred[None] = Deferred()
264 +
        deferred.addCallbacks(
265 +
            self._callback,
266 +
            self._errback,
267 +
            (),
268 +
            {},
269 +
            cast(Tuple[object], None),
270 +
            cast(Mapping[str, object], None),
271 +
        )
210 272
        deferred.errback(error)
211 273
        deferred.addErrback(self._errback)
212 274
        self.assertIsNone(self.callbackResults)
275 +
        assert self.errbackResults is not None
213 276
        self.assertEqual(len(self.errbackResults[0]), 1)
214 277
        self.assertEqual(self.errbackResults[0][0].value, error)
215 278
        self.assertEqual(self.errbackResults[1], {})
216 279
217 -
    def testDeferredList(self):
218 -
        defr1 = defer.Deferred()
219 -
        defr2 = defer.Deferred()
220 -
        defr3 = defer.Deferred()
221 -
        dl = defer.DeferredList([defr1, defr2, defr3])
222 -
        result = []
280 +
    def testDeferredList(self) -> None:
281 +
        ResultList = List[Tuple[bool, Union[str, Failure]]]
223 282
224 -
        def cb(resultList, result=result):
283 +
        defr1: Deferred[str] = Deferred()
284 +
        defr2: Deferred[str] = Deferred()
285 +
        defr3: Deferred[str] = Deferred()
286 +
        dl = DeferredList([defr1, defr2, defr3])
287 +
        result: ResultList = []
288 +
289 +
        def cb(resultList: ResultList, result: ResultList = result) -> None:
225 290
            result.extend(resultList)
226 291
227 -
        def catch(err):
292 +
        def catch(err: Failure) -> None:
228 293
            return None
229 294
230 295
        dl.addCallbacks(cb, cb)
@@ -242,38 +307,43 @@
Loading
242 307
            [
243 308
                result[0],
244 309
                # result[1][1] is now a Failure instead of an Exception
245 -
                (result[1][0], str(result[1][1].value)),
310 +
                (result[1][0], str(cast(Failure, result[1][1]).value)),
246 311
                result[2],
247 312
            ],
248 313
            [(defer.SUCCESS, "1"), (defer.FAILURE, "2"), (defer.SUCCESS, "3")],
249 314
        )
250 315
251 -
    def testEmptyDeferredList(self):
252 -
        result = []
316 +
    def testEmptyDeferredList(self) -> None:
317 +
        result: List[_DeferredListResultListT] = []
253 318
254 -
        def cb(resultList, result=result):
319 +
        def cb(
320 +
            resultList: _DeferredListResultListT,
321 +
            result: List[_DeferredListResultListT] = result,
322 +
        ) -> None:
255 323
            result.append(resultList)
256 324
257 -
        dl = defer.DeferredList([])
258 -
        dl.addCallbacks(cb)
325 +
        dl1: Deferred[_DeferredListResultListT] = DeferredList([])
326 +
        dl1.addCallbacks(cb)
259 327
        self.assertEqual(result, [[]])
260 328
261 329
        result[:] = []
262 -
        dl = defer.DeferredList([], fireOnOneCallback=1)
263 -
        dl.addCallbacks(cb)
330 +
        dl2: Deferred[_DeferredListSingleResultT] = DeferredList(
331 +
            [], fireOnOneCallback=True
332 +
        )
333 +
        dl2.addCallbacks(cb)
264 334
        self.assertEqual(result, [])
265 335
266 -
    def testDeferredListFireOnOneError(self):
267 -
        defr1 = defer.Deferred()
268 -
        defr2 = defer.Deferred()
269 -
        defr3 = defer.Deferred()
270 -
        dl = defer.DeferredList([defr1, defr2, defr3], fireOnOneErrback=1)
271 -
        result = []
336 +
    def testDeferredListFireOnOneError(self) -> None:
337 +
        defr1: Deferred[str] = Deferred()
338 +
        defr2: Deferred[str] = Deferred()
339 +
        defr3: Deferred[str] = Deferred()
340 +
        dl = DeferredList([defr1, defr2, defr3], fireOnOneErrback=True)
341 +
        result: List[Failure] = []
272 342
        dl.addErrback(result.append)
273 343
274 344
        # consume errors after they pass through the DeferredList (to avoid
275 345
        # 'Unhandled error in Deferred'.
276 -
        def catch(err):
346 +
        def catch(err: Failure) -> None:
277 347
            return None
278 348
279 349
        defr2.addErrback(catch)
@@ -304,89 +374,93 @@
Loading
304 374
        self.assertEqual(firstError.subFailure.value.args, ("from def2",))
305 375
        self.assertEqual(firstError.index, 1)
306 376
307 -
    def testDeferredListDontConsumeErrors(self):
308 -
        d1 = defer.Deferred()
309 -
        dl = defer.DeferredList([d1])
377 +
    def testDeferredListDontConsumeErrors(self) -> None:
378 +
        d1: Deferred[None] = Deferred()
379 +
        dl = DeferredList([d1])
310 380
311 -
        errorTrap = []
381 +
        errorTrap: List[Failure] = []
312 382
        d1.addErrback(errorTrap.append)
313 383
314 -
        result = []
315 -
        dl.addCallback(result.append)
384 +
        resultLists: List[_DeferredListResultListT] = []
385 +
        dl.addCallback(resultLists.append)
316 386
317 387
        d1.errback(GenericError("Bang"))
318 388
        self.assertEqual("Bang", errorTrap[0].value.args[0])
319 -
        self.assertEqual(1, len(result))
320 -
        self.assertEqual("Bang", result[0][0][1].value.args[0])
389 +
        self.assertEqual(1, len(resultLists))
390 +
        firstResult = resultLists[0][0]
391 +
        assert firstResult is not None
392 +
        self.assertEqual("Bang", firstResult[1].value.args[0])
321 393
322 -
    def testDeferredListConsumeErrors(self):
323 -
        d1 = defer.Deferred()
324 -
        dl = defer.DeferredList([d1], consumeErrors=True)
394 +
    def testDeferredListConsumeErrors(self) -> None:
395 +
        d1: Deferred[None] = Deferred()
396 +
        dl = DeferredList([d1], consumeErrors=True)
325 397
326 -
        errorTrap = []
398 +
        errorTrap: List[Failure] = []
327 399
        d1.addErrback(errorTrap.append)
328 400
329 -
        result = []
330 -
        dl.addCallback(result.append)
401 +
        resultLists: List[_DeferredListResultListT] = []
402 +
        dl.addCallback(resultLists.append)
331 403
332 404
        d1.errback(GenericError("Bang"))
333 405
        self.assertEqual([], errorTrap)
334 -
        self.assertEqual(1, len(result))
335 -
        self.assertEqual("Bang", result[0][0][1].value.args[0])
406 +
        self.assertEqual(1, len(resultLists))
407 +
        firstResult = resultLists[0][0]
408 +
        assert firstResult is not None
409 +
        self.assertEqual("Bang", firstResult[1].value.args[0])
336 410
337 -
    def testDeferredListFireOnOneErrorWithAlreadyFiredDeferreds(self):
411 +
    def testDeferredListFireOnOneErrorWithAlreadyFiredDeferreds(self) -> None:
338 412
        # Create some deferreds, and errback one
339 -
        d1 = defer.Deferred()
340 -
        d2 = defer.Deferred()
413 +
        d1: Deferred[None] = Deferred()
414 +
        d2: Deferred[None] = Deferred()
341 415
        d1.errback(GenericError("Bang"))
342 416
343 417
        # *Then* build the DeferredList, with fireOnOneErrback=True
344 -
        dl = defer.DeferredList([d1, d2], fireOnOneErrback=True)
345 -
        result = []
418 +
        dl = DeferredList([d1, d2], fireOnOneErrback=True)
419 +
        result: List[Failure] = []
346 420
        dl.addErrback(result.append)
347 421
        self.assertEqual(1, len(result))
348 422
349 423
        d1.addErrback(lambda e: None)  # Swallow error
350 424
351 -
    def testDeferredListWithAlreadyFiredDeferreds(self):
425 +
    def testDeferredListWithAlreadyFiredDeferreds(self) -> None:
352 426
        # Create some deferreds, and err one, call the other
353 -
        d1 = defer.Deferred()
354 -
        d2 = defer.Deferred()
427 +
        d1: Deferred[int] = Deferred()
428 +
        d2: Deferred[int] = Deferred()
355 429
        d1.errback(GenericError("Bang"))
356 430
        d2.callback(2)
357 431
358 432
        # *Then* build the DeferredList
359 -
        dl = defer.DeferredList([d1, d2])
433 +
        dl = DeferredList([d1, d2])
360 434
361 -
        result = []
435 +
        result: List[int] = []
362 436
        dl.addCallback(result.append)
363 437
364 438
        self.assertEqual(1, len(result))
365 439
366 440
        d1.addErrback(lambda e: None)  # Swallow error
367 441
368 -
    def test_cancelDeferredList(self):
442 +
    def test_cancelDeferredList(self) -> None:
369 443
        """
370 -
        When cancelling an unfired L{defer.DeferredList}, cancel every
371 -
        L{defer.Deferred} in the list.
444 +
        When cancelling an unfired L{DeferredList}, cancel every
445 +
        L{Deferred} in the list.
372 446
        """
373 -
        deferredOne = defer.Deferred()
374 -
        deferredTwo = defer.Deferred()
375 -
        deferredList = defer.DeferredList([deferredOne, deferredTwo])
447 +
        deferredOne: Deferred[None] = Deferred()
448 +
        deferredTwo: Deferred[None] = Deferred()
449 +
        deferredList = DeferredList([deferredOne, deferredTwo])
376 450
        deferredList.cancel()
377 451
        self.failureResultOf(deferredOne, defer.CancelledError)
378 452
        self.failureResultOf(deferredTwo, defer.CancelledError)
379 453
380 -
    def test_cancelDeferredListCallback(self):
454 +
    def test_cancelDeferredListCallback(self) -> None:
381 455
        """
382 -
        When cancelling an unfired L{defer.DeferredList} without the
456 +
        When cancelling an unfired L{DeferredList} without the
383 457
        C{fireOnOneCallback} and C{fireOnOneErrback} flags set, the
384 -
        L{defer.DeferredList} will be callback with a C{list} of
458 +
        L{DeferredList} will be callback with a C{list} of
385 459
        (success, result) C{tuple}s.
386 460
        """
387 -
        deferredOne = defer.Deferred(fakeCallbackCanceller)
388 -
        deferredTwo = defer.Deferred()
389 -
        deferredList = defer.DeferredList([deferredOne, deferredTwo])
461 +
        deferredOne: Deferred[str] = Deferred(fakeCallbackCanceller)
462 +
        deferredTwo: Deferred[str] = Deferred()
463 +
        deferredList = DeferredList([deferredOne, deferredTwo])
390 464
        deferredList.cancel()
391 465
        self.failureResultOf(deferredTwo, defer.CancelledError)
392 466
        result = self.successResultOf(deferredList)
@@ -395,47 +469,41 @@
Loading
395 469
        self.assertFalse(result[1][0])
396 470
        self.assertTrue(result[1][1].check(defer.CancelledError))
397 471
398 -
    def test_cancelDeferredListWithFireOnOneCallback(self):
472 +
    def test_cancelDeferredListWithFireOnOneCallback(self) -> None:
399 473
        """
400 -
        When cancelling an unfired L{defer.DeferredList} with the flag
401 -
        C{fireOnOneCallback} set, cancel every L{defer.Deferred} in the list.
474 +
        When cancelling an unfired L{DeferredList} with the flag
475 +
        C{fireOnOneCallback} set, cancel every L{Deferred} in the list.
402 476
        """
403 -
        deferredOne = defer.Deferred()
404 -
        deferredTwo = defer.Deferred()
405 -
        deferredList = defer.DeferredList(
406 -
            [deferredOne, deferredTwo], fireOnOneCallback=True
407 -
        )
477 +
        deferredOne: Deferred[None] = Deferred()
478 +
        deferredTwo: Deferred[None] = Deferred()
479 +
        deferredList = DeferredList([deferredOne, deferredTwo], fireOnOneCallback=True)
408 480
        deferredList.cancel()
409 481
        self.failureResultOf(deferredOne, defer.CancelledError)
410 482
        self.failureResultOf(deferredTwo, defer.CancelledError)
411 483
412 -
    def test_cancelDeferredListWithFireOnOneCallbackAndDeferredCallback(self):
484 +
    def test_cancelDeferredListWithFireOnOneCallbackAndDeferredCallback(self) -> None:
413 485
        """
414 -
        When cancelling an unfired L{defer.DeferredList} with the flag
415 -
        C{fireOnOneCallback} set, if one of the L{defer.Deferred} callbacks
416 -
        in its canceller, the L{defer.DeferredList} will callback with the
417 -
        result and the index of the L{defer.Deferred} in a C{tuple}.
486 +
        When cancelling an unfired L{DeferredList} with the flag
487 +
        C{fireOnOneCallback} set, if one of the L{Deferred} callbacks
488 +
        in its canceller, the L{DeferredList} will callback with the
489 +
        result and the index of the L{Deferred} in a C{tuple}.
418 490
        """
419 -
        deferredOne = defer.Deferred(fakeCallbackCanceller)
420 -
        deferredTwo = defer.Deferred()
421 -
        deferredList = defer.DeferredList(
422 -
            [deferredOne, deferredTwo], fireOnOneCallback=True
423 -
        )
491 +
        deferredOne: Deferred[str] = Deferred(fakeCallbackCanceller)
492 +
        deferredTwo: Deferred[str] = Deferred()
493 +
        deferredList = DeferredList([deferredOne, deferredTwo], fireOnOneCallback=True)
424 494
        deferredList.cancel()
425 495
        self.failureResultOf(deferredTwo, defer.CancelledError)
426 496
        result = self.successResultOf(deferredList)
427 497
        self.assertEqual(result, ("Callback Result", 0))
428 498
429 -
    def test_cancelDeferredListWithFireOnOneErrback(self):
499 +
    def test_cancelDeferredListWithFireOnOneErrback(self) -> None:
430 500
        """
431 -
        When cancelling an unfired L{defer.DeferredList} with the flag
432 -
        C{fireOnOneErrback} set, cancel every L{defer.Deferred} in the list.
501 +
        When cancelling an unfired L{DeferredList} with the flag
502 +
        C{fireOnOneErrback} set, cancel every L{Deferred} in the list.
433 503
        """
434 -
        deferredOne = defer.Deferred()
435 -
        deferredTwo = defer.Deferred()
436 -
        deferredList = defer.DeferredList(
437 -
            [deferredOne, deferredTwo], fireOnOneErrback=True
438 -
        )
504 +
        deferredOne: Deferred[None] = Deferred()
505 +
        deferredTwo: Deferred[None] = Deferred()
506 +
        deferredList = DeferredList([deferredOne, deferredTwo], fireOnOneErrback=True)
439 507
        deferredList.cancel()
440 508
        self.failureResultOf(deferredOne, defer.CancelledError)
441 509
        self.failureResultOf(deferredTwo, defer.CancelledError)
@@ -443,18 +511,16 @@
Loading
443 511
        firstError = deferredListFailure.value
444 512
        self.assertTrue(firstError.subFailure.check(defer.CancelledError))
445 513
446 -
    def test_cancelDeferredListWithFireOnOneErrbackAllDeferredsCallback(self):
514 +
    def test_cancelDeferredListWithFireOnOneErrbackAllDeferredsCallback(self) -> None:
447 515
        """
448 -
        When cancelling an unfired L{defer.DeferredList} with the flag
449 -
        C{fireOnOneErrback} set, if all the L{defer.Deferred} callbacks
450 -
        in its canceller, the L{defer.DeferredList} will callback with a
516 +
        When cancelling an unfired L{DeferredList} with the flag
517 +
        C{fireOnOneErrback} set, if all the L{Deferred} callbacks
518 +
        in its canceller, the L{DeferredList} will callback with a
451 519
        C{list} of (success, result) C{tuple}s.
452 520
        """
453 -
        deferredOne = defer.Deferred(fakeCallbackCanceller)
454 -
        deferredTwo = defer.Deferred(fakeCallbackCanceller)
455 -
        deferredList = defer.DeferredList(
456 -
            [deferredOne, deferredTwo], fireOnOneErrback=True
457 -
        )
521 +
        deferredOne: Deferred[str] = Deferred(fakeCallbackCanceller)
522 +
        deferredTwo: Deferred[str] = Deferred(fakeCallbackCanceller)
523 +
        deferredList = DeferredList([deferredOne, deferredTwo], fireOnOneErrback=True)
458 524
        deferredList.cancel()
459 525
        result = self.successResultOf(deferredList)
460 526
        self.assertTrue(result[0][0])
@@ -462,91 +528,87 @@
Loading
462 528
        self.assertTrue(result[1][0])
463 529
        self.assertEqual(result[1][1], "Callback Result")
464 530
465 -
    def test_cancelDeferredListWithOriginalDeferreds(self):
531 +
    def test_cancelDeferredListWithOriginalDeferreds(self) -> None:
466 532
        """
467 -
        Cancelling a L{defer.DeferredList} will cancel the original
468 -
        L{defer.Deferred}s passed in.
533 +
        Cancelling a L{DeferredList} will cancel the original
534 +
        L{Deferred}s passed in.
469 535
        """
470 -
        deferredOne = defer.Deferred()
471 -
        deferredTwo = defer.Deferred()
536 +
        deferredOne: Deferred[None] = Deferred()
537 +
        deferredTwo: Deferred[None] = Deferred()
472 538
        argumentList = [deferredOne, deferredTwo]
473 -
        deferredList = defer.DeferredList(argumentList)
474 -
        deferredThree = defer.Deferred()
539 +
        deferredList = DeferredList(argumentList)
540 +
        deferredThree: Deferred[None] = Deferred()
475 541
        argumentList.append(deferredThree)
476 542
        deferredList.cancel()
477 543
        self.failureResultOf(deferredOne, defer.CancelledError)
478 544
        self.failureResultOf(deferredTwo, defer.CancelledError)
479 545
        self.assertNoResult(deferredThree)
480 546
481 -
    def test_cancelDeferredListWithException(self):
547 +
    def test_cancelDeferredListWithException(self) -> None:
482 548
        """
483 -
        Cancelling a L{defer.DeferredList} will cancel every L{defer.Deferred}
549 +
        Cancelling a L{DeferredList} will cancel every L{Deferred}
484 550
        in the list even exceptions raised from the C{cancel} method of the
485 -
        L{defer.Deferred}s.
551 +
        L{Deferred}s.
486 552
        """
487 553
488 -
        def cancellerRaisesException(deferred):
554 +
        def cancellerRaisesException(deferred: Deferred[object]) -> None:
489 555
            """
490 -
            A L{defer.Deferred} canceller that raises an exception.
556 +
            A L{Deferred} canceller that raises an exception.
491 557
492 -
            @param deferred: The cancelled L{defer.Deferred}.
558 +
            @param deferred: The cancelled L{Deferred}.
493 559
            """
494 560
            raise RuntimeError("test")
495 561
496 -
        deferredOne = defer.Deferred(cancellerRaisesException)
497 -
        deferredTwo = defer.Deferred()
498 -
        deferredList = defer.DeferredList([deferredOne, deferredTwo])
562 +
        deferredOne: Deferred[None] = Deferred(cancellerRaisesException)
563 +
        deferredTwo: Deferred[None] = Deferred()
564 +
        deferredList = DeferredList([deferredOne, deferredTwo])
499 565
        deferredList.cancel()
500 566
        self.failureResultOf(deferredTwo, defer.CancelledError)
501 567
        errors = self.flushLoggedErrors(RuntimeError)
502 568
        self.assertEqual(len(errors), 1)
503 569
504 -
    def test_cancelFiredOnOneCallbackDeferredList(self):
570 +
    def test_cancelFiredOnOneCallbackDeferredList(self) -> None:
505 571
        """
506 -
        When a L{defer.DeferredList} has fired because one L{defer.Deferred} in
572 +
        When a L{DeferredList} has fired because one L{Deferred} in
507 573
        the list fired with a non-failure result, the cancellation will do
508 -
        nothing instead of cancelling the rest of the L{defer.Deferred}s.
574 +
        nothing instead of cancelling the rest of the L{Deferred}s.
509 575
        """
510 -
        deferredOne = defer.Deferred()
511 -
        deferredTwo = defer.Deferred()
512 -
        deferredList = defer.DeferredList(
513 -
            [deferredOne, deferredTwo], fireOnOneCallback=True
514 -
        )
576 +
        deferredOne: Deferred[None] = Deferred()
577 +
        deferredTwo: Deferred[None] = Deferred()
578 +
        deferredList = DeferredList([deferredOne, deferredTwo], fireOnOneCallback=True)
515 579
        deferredOne.callback(None)
516 580
        deferredList.cancel()
517 581
        self.assertNoResult(deferredTwo)
518 582
519 -
    def test_cancelFiredOnOneErrbackDeferredList(self):
583 +
    def test_cancelFiredOnOneErrbackDeferredList(self) -> None:
520 584
        """
521 -
        When a L{defer.DeferredList} has fired because one L{defer.Deferred} in
585 +
        When a L{DeferredList} has fired because one L{Deferred} in
522 586
        the list fired with a failure result, the cancellation will do
523 -
        nothing instead of cancelling the rest of the L{defer.Deferred}s.
587 +
        nothing instead of cancelling the rest of the L{Deferred}s.
524 588
        """
525 -
        deferredOne = defer.Deferred()
526 -
        deferredTwo = defer.Deferred()
527 -
        deferredList = defer.DeferredList(
528 -
            [deferredOne, deferredTwo], fireOnOneErrback=True
529 -
        )
589 +
        deferredOne: Deferred[None] = Deferred()
590 +
        deferredTwo: Deferred[None] = Deferred()
591 +
        deferredList = DeferredList([deferredOne, deferredTwo], fireOnOneErrback=True)
530 592
        deferredOne.errback(GenericError("test"))
531 593
        deferredList.cancel()
532 594
        self.assertNoResult(deferredTwo)
533 595
        self.failureResultOf(deferredOne, GenericError)
534 596
        self.failureResultOf(deferredList, defer.FirstError)
535 597
536 -
    def testImmediateSuccess(self):
537 -
        l = []
538 -
        d = defer.succeed("success")
598 +
    def testImmediateSuccess(self) -> None:
599 +
        l: List[str] = []
600 +
        d: Deferred[str] = defer.succeed("success")
539 601
        d.addCallback(l.append)
540 602
        self.assertEqual(l, ["success"])
541 603
542 -
    def testImmediateFailure(self):
543 -
        l = []
544 -
        d = defer.fail(GenericError("fail"))
604 +
    def testImmediateFailure(self) -> None:
605 +
        l: List[Failure] = []
606 +
        d: Deferred[None] = defer.fail(GenericError("fail"))
545 607
        d.addErrback(l.append)
546 608
        self.assertEqual(str(l[0].value), "fail")
547 609
548 -
    def testPausedFailure(self):
549 -
        l = []
610 +
    def testPausedFailure(self) -> None:
611 +
        l: List[Failure] = []
550 612
        d = defer.fail(GenericError("fail"))
551 613
        d.pause()
552 614
        d.addErrback(l.append)
@@ -554,94 +616,97 @@
Loading
554 616
        d.unpause()
555 617
        self.assertEqual(str(l[0].value), "fail")
556 618
557 -
    def testCallbackErrors(self):
558 -
        l = []
559 -
        d = defer.Deferred().addCallback(lambda _: 1 // 0).addErrback(l.append)
619 +
    def testCallbackErrors(self) -> None:
620 +
        l: List[Failure] = []
621 +
        d = Deferred().addCallback(lambda _: 1 // 0).addErrback(l.append)
560 622
        d.callback(1)
561 623
        self.assertIsInstance(l[0].value, ZeroDivisionError)
562 624
        l = []
563 625
        d = (
564 -
            defer.Deferred()
565 -
            .addCallback(lambda _: failure.Failure(ZeroDivisionError()))
626 +
            Deferred()
627 +
            .addCallback(lambda _: Failure(ZeroDivisionError()))
566 628
            .addErrback(l.append)
567 629
        )
568 630
        d.callback(1)
569 631
        self.assertIsInstance(l[0].value, ZeroDivisionError)
570 632
571 -
    def testUnpauseBeforeCallback(self):
572 -
        d = defer.Deferred()
633 +
    def testUnpauseBeforeCallback(self) -> None:
634 +
        d: Deferred[None] = Deferred()
573 635
        d.pause()
574 636
        d.addCallback(self._callback)
575 637
        d.unpause()
576 638
577 -
    def testReturnDeferred(self):
578 -
        d = defer.Deferred()
579 -
        d2 = defer.Deferred()
639 +
    def testReturnDeferred(self) -> None:
640 +
        d1: Deferred[int] = Deferred()
641 +
        d2: Deferred[int] = Deferred()
580 642
        d2.pause()
581 -
        d.addCallback(lambda r, d2=d2: d2)
582 -
        d.addCallback(self._callback)
583 -
        d.callback(1)
643 +
        d1.addCallback(lambda r, d2=d2: cast(int, d2))
644 +
        d1.addCallback(self._callback)
645 +
        d1.callback(1)
584 646
        assert self.callbackResults is None, "Should not have been called yet."
585 647
        d2.callback(2)
586 648
        assert self.callbackResults is None, "Still should not have been called yet."
587 649
        d2.unpause()
588 -
        assert (
650 +
        assert self.callbackResults is not None
651 +
        assert (  # type: ignore[unreachable]
589 652
            self.callbackResults[0][0] == 2
590 653
        ), "Result should have been from second deferred:{}".format(
591 654
            self.callbackResults
592 655
        )
593 656
594 -
    def test_chainedPausedDeferredWithResult(self):
657 +
    def test_chainedPausedDeferredWithResult(self) -> None:
595 658
        """
596 659
        When a paused Deferred with a result is returned from a callback on
597 660
        another Deferred, the other Deferred is chained to the first and waits
598 661
        for it to be unpaused.
599 662
        """
600 663
        expected = object()
601 -
        paused = defer.Deferred()
664 +
        paused: Deferred[object] = Deferred()
602 665
        paused.callback(expected)
603 666
        paused.pause()
604 -
        chained = defer.Deferred()
667 +
        chained: Deferred[None] = Deferred()
605 668
        chained.addCallback(lambda ignored: paused)
606 669
        chained.callback(None)
607 670
608 -
        result = []
671 +
        result: List[object] = []
609 672
        chained.addCallback(result.append)
610 673
        self.assertEqual(result, [])
611 674
        paused.unpause()
612 675
        self.assertEqual(result, [expected])
613 676
614 -
    def test_pausedDeferredChained(self):
677 +
    def test_pausedDeferredChained(self) -> None:
615 678
        """
616 679
        A paused Deferred encountered while pushing a result forward through a
617 680
        chain does not prevent earlier Deferreds from continuing to execute
618 681
        their callbacks.
619 682
        """
620 -
        first = defer.Deferred()
621 -
        second = defer.Deferred()
683 +
        first: Deferred[None] = Deferred()
684 +
        second: Deferred[None] = Deferred()
622 685
        first.addCallback(lambda ignored: second)
623 686
        first.callback(None)
624 687
        first.pause()
625 688
        second.callback(None)
626 -
        result = []
689 +
        result: List[None] = []
627 690
        second.addCallback(result.append)
628 691
        self.assertEqual(result, [None])
629 692
630 -
    def test_gatherResults(self):
693 +
    def test_gatherResults(self) -> None:
631 694
        # test successful list of deferreds
632 -
        l = []
633 -
        defer.gatherResults([defer.succeed(1), defer.succeed(2)]).addCallback(l.append)
634 -
        self.assertEqual(l, [[1, 2]])
695 +
        results: List[List[int]] = []
696 +
        defer.gatherResults([defer.succeed(1), defer.succeed(2)]).addCallback(
697 +
            results.append
698 +
        )
699 +
        self.assertEqual(results, [[1, 2]])
635 700
        # test failing list of deferreds
636 -
        l = []
701 +
        errors: List[Failure] = []
637 702
        dl = [defer.succeed(1), defer.fail(ValueError())]
638 -
        defer.gatherResults(dl).addErrback(l.append)
639 -
        self.assertEqual(len(l), 1)
640 -
        self.assertIsInstance(l[0], failure.Failure)
703 +
        defer.gatherResults(dl).addErrback(errors.append)
704 +
        self.assertEqual(len(errors), 1)
705 +
        self.assertIsInstance(errors[0], Failure)
641 706
        # get rid of error
642 707
        dl[1].addErrback(lambda e: 1)
643 708
644 -
    def test_gatherResultsWithConsumeErrors(self):
709 +
    def test_gatherResultsWithConsumeErrors(self) -> None:
645 710
        """
646 711
        If a L{Deferred} in the list passed to L{gatherResults} fires with a
647 712
        failure and C{consumerErrors} is C{True}, the failure is converted to a
@@ -651,9 +716,9 @@
Loading
651 716
        dgood = defer.succeed(1)
652 717
        dbad = defer.fail(RuntimeError("oh noes"))
653 718
        d = defer.gatherResults([dgood, dbad], consumeErrors=True)
654 -
        unconsumedErrors = []
719 +
        unconsumedErrors: List[Failure] = []
655 720
        dbad.addErrback(unconsumedErrors.append)
656 -
        gatheredErrors = []
721 +
        gatheredErrors: List[Failure] = []
657 722
        d.addErrback(gatheredErrors.append)
658 723
659 724
        self.assertEqual((len(unconsumedErrors), len(gatheredErrors)), (0, 1))
@@ -661,13 +726,13 @@
Loading
661 726
        firstError = gatheredErrors[0].value.subFailure
662 727
        self.assertIsInstance(firstError.value, RuntimeError)
663 728
664 -
    def test_cancelGatherResults(self):
729 +
    def test_cancelGatherResults(self) -> None:
665 730
        """
666 731
        When cancelling the L{defer.gatherResults} call, all the
667 -
        L{defer.Deferred}s in the list will be cancelled.
732 +
        L{Deferred}s in the list will be cancelled.
668 733
        """
669 -
        deferredOne = defer.Deferred()
670 -
        deferredTwo = defer.Deferred()
734 +
        deferredOne: Deferred[None] = Deferred()
735 +
        deferredTwo: Deferred[None] = Deferred()
671 736
        result = defer.gatherResults([deferredOne, deferredTwo])
672 737
        result.cancel()
673 738
        self.failureResultOf(deferredOne, defer.CancelledError)
@@ -676,119 +741,134 @@
Loading
676 741
        firstError = gatherResultsFailure.value
677 742
        self.assertTrue(firstError.subFailure.check(defer.CancelledError))
678 743
679 -
    def test_cancelGatherResultsWithAllDeferredsCallback(self):
744 +
    def test_cancelGatherResultsWithAllDeferredsCallback(self) -> None:
680 745
        """
681 746
        When cancelling the L{defer.gatherResults} call, if all the
682 -
        L{defer.Deferred}s callback in their canceller, the L{defer.Deferred}
747 +
        L{Deferred}s callback in their canceller, the L{Deferred}
683 748
        returned by L{defer.gatherResults} will be callbacked with the C{list}
684 749
        of the results.
685 750
        """
686 -
        deferredOne = defer.Deferred(fakeCallbackCanceller)
687 -
        deferredTwo = defer.Deferred(fakeCallbackCanceller)
751 +
        deferredOne: Deferred[str] = Deferred(fakeCallbackCanceller)
752 +
        deferredTwo: Deferred[str] = Deferred(fakeCallbackCanceller)
688 753
        result = defer.gatherResults([deferredOne, deferredTwo])
689 754
        result.cancel()
690 755
        callbackResult = self.successResultOf(result)
691 756
        self.assertEqual(callbackResult[0], "Callback Result")
692 757
        self.assertEqual(callbackResult[1], "Callback Result")
693 758
694 -
    def test_maybeDeferredSync(self):
759 +
    def test_maybeDeferredSync(self) -> None:
695 760
        """
696 761
        L{defer.maybeDeferred} should retrieve the result of a synchronous
697 -
        function and pass it to its resulting L{defer.Deferred}.
762 +
        function and pass it to its resulting L{Deferred}.
698 763
        """
699 764
        result = object()
700 -
        S, E = [], []
765 +
        results: List[object] = []
766 +
        errors: List[Failure] = []
701 767
        d = defer.maybeDeferred(lambda: result)
702 -
        d.addCallbacks(S.append, E.append)
703 -
        self.assertEqual(E, [])
704 -
        self.assertEqual(len(S), 1)
705 -
        self.assertIdentical(S[0], result)
768 +
        d.addCallbacks(results.append, errors.append)
769 +
        self.assertEqual(errors, [])
770 +
        self.assertEqual(len(results), 1)
771 +
        self.assertIdentical(results[0], result)
706 772
707 -
    def test_maybeDeferredSyncWithArgs(self):
773 +
    def test_maybeDeferredSyncWithArgs(self) -> None:
708 774
        """
709 775
        L{defer.maybeDeferred} should pass arguments to the called function.
710 776
        """
711 -
        S, E = [], []
712 -
        d = defer.maybeDeferred((lambda x: x + 5), 10)
713 -
        d.addCallbacks(S.append, E.append)
714 -
        self.assertEqual(E, [])
715 -
        self.assertEqual(S, [15])
716 777
717 -
    def test_maybeDeferredSyncException(self):
778 +
        def plusFive(x: int) -> int:
779 +
            return x + 5
780 +
781 +
        results: List[int] = []
782 +
        errors: List[Failure] = []
783 +
        d = defer.maybeDeferred(plusFive, 10)
784 +
        d.addCallbacks(results.append, errors.append)
785 +
        self.assertEqual(errors, [])
786 +
        self.assertEqual(results, [15])
787 +
788 +
    def test_maybeDeferredSyncException(self) -> None:
718 789
        """
719 790
        L{defer.maybeDeferred} should catch an exception raised by a synchronous
720 -
        function and errback its resulting L{defer.Deferred} with it.
791 +
        function and errback its resulting L{Deferred} with it.
721 792
        """
722 -
        S, E = [], []
723 793
        try:
724 -
            "10" + 5
794 +
            "10" + 5  # type: ignore[operator]
725 795
        except TypeError as e:
726 796
            expected = str(e)
727 -
        d = defer.maybeDeferred((lambda x: x + 5), "10")
728 -
        d.addCallbacks(S.append, E.append)
729 -
        self.assertEqual(S, [])
730 -
        self.assertEqual(len(E), 1)
731 -
        self.assertEqual(str(E[0].value), expected)
732 797
733 -
    def test_maybeDeferredSyncFailure(self):
798 +
        def plusFive(x: int) -> int:
799 +
            return x + 5
800 +
801 +
        results: List[int] = []
802 +
        errors: List[Failure] = []
803 +
        d = defer.maybeDeferred(plusFive, "10")
804 +
        d.addCallbacks(results.append, errors.append)
805 +
        self.assertEqual(results, [])
806 +
        self.assertEqual(len(errors), 1)
807 +
        self.assertEqual(str(errors[0].value), expected)
808 +
809 +
    def test_maybeDeferredSyncFailure(self) -> None:
734 810
        """
735 -
        L{defer.maybeDeferred} should handle a L{failure.Failure} returned by a
811 +
        L{defer.maybeDeferred} should handle a L{Failure} returned by a
736 812
        function and errback with it.
737 813
        """
738 -
        S, E = [], []
739 814
        try:
740 -
            "10" + 5
815 +
            "10" + 5  # type: ignore[operator]
741 816
        except TypeError:
742 -
            expected = failure.Failure()
817 +
            expected = Failure()
818 +
819 +
        results: List[int] = []
820 +
        errors: List[Failure] = []
743 821
        d = defer.maybeDeferred(lambda: expected)
744 -
        d.addCallbacks(S.append, E.append)
745 -
        self.assertEqual(S, [])
746 -
        self.assertEqual(len(E), 1)
747 -
        self.assertIdentical(E[0], expected)
822 +
        d.addCallbacks(results.append, errors.append)
823 +
        self.assertEqual(results, [])
824 +
        self.assertEqual(len(errors), 1)
825 +
        self.assertIdentical(errors[0], expected)
748 826
749 -
    def test_maybeDeferredAsync(self):
827 +
    def test_maybeDeferredAsync(self) -> None:
750 828
        """
751 -
        L{defer.maybeDeferred} should let L{defer.Deferred} instance pass by
829 +
        L{defer.maybeDeferred} should let L{Deferred} instance pass by
752 830
        so that original result is the same.
753 831
        """
754 -
        d = defer.Deferred()
755 -
        d2 = defer.maybeDeferred(lambda: d)
756 -
        d.callback("Success")
757 -
        result = []
832 +
        d1: Deferred[str] = Deferred()
833 +
        d2 = defer.maybeDeferred(lambda: d1)
834 +
        d1.callback("Success")
835 +
        result: List[str] = []
758 836
        d2.addCallback(result.append)
759 837
        self.assertEqual(result, ["Success"])
760 838
761 -
    def test_maybeDeferredAsyncError(self):
839 +
    def test_maybeDeferredAsyncError(self) -> None:
762 840
        """
763 -
        L{defer.maybeDeferred} should let L{defer.Deferred} instance pass by
764 -
        so that L{failure.Failure} returned by the original instance is the
841 +
        L{defer.maybeDeferred} should let L{Deferred} instance pass by
842 +
        so that L{Failure} returned by the original instance is the
765 843
        same.
766 844
        """
767 -
        d = defer.Deferred()
768 -
        d2 = defer.maybeDeferred(lambda: d)
769 -
        d.errback(failure.Failure(RuntimeError()))
845 +
        d1: Deferred[None] = Deferred()
846 +
        d2: Deferred[None] = defer.maybeDeferred(
847 +
            lambda: d1  # type: ignore[arg-type]  # because nested Deferred
848 +
        )
849 +
        d1.errback(Failure(RuntimeError()))
770 850
        self.assertImmediateFailure(d2, RuntimeError)
771 851
772 -
    def test_innerCallbacksPreserved(self):
852 +
    def test_innerCallbacksPreserved(self) -> None:
773 853
        """
774 854
        When a L{Deferred} encounters a result which is another L{Deferred}
775 855
        which is waiting on a third L{Deferred}, the middle L{Deferred}'s
776 856
        callbacks are executed after the third L{Deferred} fires and before the
777 857
        first receives a result.
778 858
        """
779 -
        results = []
780 -
        failures = []
781 -
        inner = defer.Deferred()
859 +
        results: List[Tuple[str, str]] = []
860 +
        failures: List[Failure] = []
861 +
        inner: Deferred[str] = Deferred()
782 862
783 -
        def cb(result):
863 +
        def cb(result: str) -> Deferred[str]:
784 864
            results.append(("start-of-cb", result))
785 865
            d = defer.succeed("inner")
786 866
787 -
            def firstCallback(result):
867 +
            def firstCallback(result: str) -> Deferred[str]:
788 868
                results.append(("firstCallback", "inner"))
789 869
                return inner
790 870
791 -
            def secondCallback(result):
871 +
            def secondCallback(result: str) -> str:
792 872
                results.append(("secondCallback", result))
793 873
                return result * 2
794 874
@@ -813,26 +893,26 @@
Loading
813 893
            ],
814 894
        )
815 895
816 -
    def test_continueCallbackNotFirst(self):
896 +
    def test_continueCallbackNotFirst(self) -> None:
817 897
        """
818 898
        The continue callback of a L{Deferred} waiting for another L{Deferred}
819 899
        is not necessarily the first one. This is somewhat a whitebox test
820 900
        checking that we search for that callback among the whole list of
821 901
        callbacks.
822 902
        """
823 -
        results = []
824 -
        failures = []
825 -
        a = defer.Deferred()
903 +
        results: List[Tuple[str, Optional[str]]] = []
904 +
        failures: List[Failure] = []
905 +
        a: Deferred[str] = Deferred()
826 906
827 -
        def cb(result):
907 +
        def cb(result: str) -> Deferred[Optional[str]]:
828 908
            results.append(("cb", result))
829 -
            d = defer.Deferred()
909 +
            d: Deferred[Optional[str]] = Deferred()
830 910
831 -
            def firstCallback(ignored):
832 -
                results.append(("firstCallback", ignored))
911 +
            def firstCallback(result: str) -> Deferred[List[str]]:
912 +
                results.append(("firstCallback", result))
833 913
                return defer.gatherResults([a])
834 914
835 -
            def secondCallback(result):
915 +
            def secondCallback(result: str) -> None:
836 916
                results.append(("secondCallback", result))
837 917
838 918
            d.addCallback(firstCallback)
@@ -852,25 +932,25 @@
Loading
852 932
            [("cb", "outer"), ("firstCallback", None), ("secondCallback", ["withers"])],
853 933
        )
854 934
855 -
    def test_callbackOrderPreserved(self):
935 +
    def test_callbackOrderPreserved(self) -> None:
856 936
        """
857 937
        A callback added to a L{Deferred} after a previous callback attached
858 938
        another L{Deferred} as a result is run after the callbacks of the other
859 939
        L{Deferred} are run.
860 940
        """
861 -
        results = []
862 -
        failures = []
863 -
        a = defer.Deferred()
941 +
        results: List[Tuple[str, Optional[str]]] = []
942 +
        failures: List[Failure] = []
943 +
        a: Deferred[Optional[str]] = Deferred()
864 944
865 -
        def cb(result):
945 +
        def cb(result: str) -> Deferred[Optional[str]]:
866 946
            results.append(("cb", result))
867 -
            d = defer.Deferred()
947 +
            d: Deferred[Optional[str]] = Deferred()
868 948
869 -
            def firstCallback(ignored):
870 -
                results.append(("firstCallback", ignored))
949 +
            def firstCallback(result: str) -> Deferred[List[str]]:
950 +
                results.append(("firstCallback", result))
871 951
                return defer.gatherResults([a])
872 952
873 -
            def secondCallback(result):
953 +
            def secondCallback(result: str) -> None:
874 954
                results.append(("secondCallback", result))
875 955
876 956
            d.addCallback(firstCallback)
@@ -879,9 +959,9 @@
Loading
879 959
            d.callback(None)
880 960
            return d
881 961
882 -
        outer = defer.Deferred()
962 +
        outer: Deferred[str] = Deferred()
883 963
        outer.addCallback(cb)
884 -
        outer.addCallback(lambda x: results.append("final"))
964 +
        outer.addCallback(lambda x: results.append(("final", None)))
885 965
        outer.addErrback(failures.append)
886 966
        outer.callback("outer")
887 967
        self.assertEqual([("cb", "outer"), ("firstCallback", None)], results)
@@ -893,25 +973,25 @@
Loading
893 973
                ("cb", "outer"),
894 974
                ("firstCallback", None),
895 975
                ("secondCallback", ["withers"]),
896 -
                "final",
976 +
                ("final", None),
897 977
            ],
898 978
        )
899 979
900 -
    def test_reentrantRunCallbacks(self):
980 +
    def test_reentrantRunCallbacks(self) -> None:
901 981
        """
902 982
        A callback added to a L{Deferred} by a callback on that L{Deferred}
903 983
        should be added to the end of the callback chain.
904 984
        """
905 -
        deferred = defer.Deferred()
985 +
        deferred: Deferred[None] = Deferred()
906 986
        called = []
907 987
908 -
        def callback3(result):
988 +
        def callback3(result: None) -> None:
909 989
            called.append(3)
910 990
911 -
        def callback2(result):
991 +
        def callback2(result: None) -> None:
912 992
            called.append(2)
913 993
914 -
        def callback1(result):
994 +
        def callback1(result: None) -> None:
915 995
            called.append(1)
916 996
            deferred.addCallback(callback3)
917 997
@@ -920,18 +1000,18 @@
Loading
920 1000
        deferred.callback(None)
921 1001
        self.assertEqual(called, [1, 2, 3])
922 1002
923 -
    def test_nonReentrantCallbacks(self):
1003 +
    def test_nonReentrantCallbacks(self) -> None:
924 1004
        """
925 1005
        A callback added to a L{Deferred} by a callback on that L{Deferred}
926 1006
        should not be executed until the running callback returns.
927 1007
        """
928 -
        deferred = defer.Deferred()
1008 +
        deferred: Deferred[None] = Deferred()
929 1009
        called = []
930 1010
931 -
        def callback2(result):
1011 +
        def callback2(result: None) -> None:
932 1012
            called.append(2)
933 1013
934 -
        def callback1(result):
1014 +
        def callback1(result: None) -> None:
935 1015
            called.append(1)
936 1016
            deferred.addCallback(callback2)
937 1017
            self.assertEqual(called, [1])
@@ -940,19 +1020,19 @@
Loading
940 1020
        deferred.callback(None)
941 1021
        self.assertEqual(called, [1, 2])
942 1022
943 -
    def test_reentrantRunCallbacksWithFailure(self):
1023 +
    def test_reentrantRunCallbacksWithFailure(self) -> None:
944 1024
        """
945 1025
        After an exception is raised by a callback which was added to a
946 1026
        L{Deferred} by a callback on that L{Deferred}, the L{Deferred} should
947 1027
        call the first errback with a L{Failure} wrapping that exception.
948 1028
        """
949 1029
        exceptionMessage = "callback raised exception"
950 -
        deferred = defer.Deferred()
1030 +
        deferred: Deferred[None] = Deferred()
951 1031
952 -
        def callback2(result):
1032 +
        def callback2(result: object) -> None:
953 1033
            raise Exception(exceptionMessage)
954 1034
955 -
        def callback1(result):
1035 +
        def callback1(result: object) -> None:
956 1036
            deferred.addCallback(callback2)
957 1037
958 1038
        deferred.addCallback(callback1)
@@ -960,7 +1040,7 @@
Loading
960 1040
        exception = self.assertImmediateFailure(deferred, Exception)
961 1041
        self.assertEqual(exception.args, (exceptionMessage,))
962 1042
963 -
    def test_synchronousImplicitChain(self):
1043 +
    def test_synchronousImplicitChain(self) -> None:
964 1044
        """
965 1045
        If a first L{Deferred} with a result is returned from a callback on a
966 1046
        second L{Deferred}, the result of the second L{Deferred} becomes the
@@ -969,31 +1049,31 @@
Loading
969 1049
        """
970 1050
        result = object()
971 1051
        first = defer.succeed(result)
972 -
        second = defer.Deferred()
1052 +
        second: Deferred[None] = Deferred()
973 1053
        second.addCallback(lambda ign: first)
974 1054
        second.callback(None)
975 1055
976 -
        results = []
1056 +
        results: List[Optional[object]] = []
977 1057
        first.addCallback(results.append)
978 1058
        self.assertIsNone(results[0])
979 1059
        second.addCallback(results.append)
980 1060
        self.assertIs(results[1], result)
981 1061
982 -
    def test_asynchronousImplicitChain(self):
1062 +
    def test_asynchronousImplicitChain(self) -> None:
983 1063
        """
984 1064
        If a first L{Deferred} without a result is returned from a callback on
985 1065
        a second L{Deferred}, the result of the second L{Deferred} becomes the
986 1066
        result of the first L{Deferred} as soon as the first L{Deferred} has
987 1067
        one and the result of the first L{Deferred} becomes L{None}.
988 1068
        """
989 -
        first = defer.Deferred()
990 -
        second = defer.Deferred()
1069 +
        first: Deferred[object] = Deferred()
1070 +
        second: Deferred[object] = Deferred()
991 1071
        second.addCallback(lambda ign: first)
992 1072
        second.callback(None)
993 1073
994 -
        firstResult = []
1074 +
        firstResult: List[object] = []
995 1075
        first.addCallback(firstResult.append)
996 -
        secondResult = []
1076 +
        secondResult: List[object] = []
997 1077
        second.addCallback(secondResult.append)
998 1078
999 1079
        self.assertEqual(firstResult, [])
@@ -1005,7 +1085,7 @@
Loading
1005 1085
        self.assertEqual(firstResult, [None])
1006 1086
        self.assertEqual(secondResult, [result])
1007 1087
1008 -
    def test_synchronousImplicitErrorChain(self):
1088 +
    def test_synchronousImplicitErrorChain(self) -> None:
1009 1089
        """
1010 1090
        If a first L{Deferred} with a L{Failure} result is returned from a
1011 1091
        callback on a second L{Deferred}, the first L{Deferred}'s result is
@@ -1013,15 +1093,19 @@
Loading
1013 1093
        garbage collected.
1014 1094
        """
1015 1095
        first = defer.fail(RuntimeError("First Deferred's Failure"))
1016 -
        second = defer.Deferred()
1017 -
        second.addCallback(lambda ign, first=first: first)
1096 +
1097 +
        def cb(_: None, first: Deferred[None] = first) -> Deferred[None]:
1098 +
            return first
1099 +
1100 +
        second: Deferred[None] = Deferred()
1101 +
        second.addCallback(cb)
1018 1102
        second.callback(None)
1019 -
        firstResult = []
1103 +
        firstResult: List[None] = []
1020 1104
        first.addCallback(firstResult.append)
1021 1105
        self.assertIsNone(firstResult[0])
1022 1106
        self.assertImmediateFailure(second, RuntimeError)
1023 1107
1024 -
    def test_asynchronousImplicitErrorChain(self):
1108 +
    def test_asynchronousImplicitErrorChain(self) -> None:
1025 1109
        """
1026 1110
        Let C{a} and C{b} be two L{Deferred}s.
1027 1111
@@ -1030,16 +1114,16 @@
Loading
1030 1114
        the result of C{a} becomes L{None} so that no unhandled error is logged
1031 1115
        when it is garbage collected.
1032 1116
        """
1033 -
        first = defer.Deferred()
1034 -
        second = defer.Deferred()
1117 +
        first: Deferred[None] = Deferred()
1118 +
        second: Deferred[None] = Deferred()
1035 1119
        second.addCallback(lambda ign: first)
1036 1120
        second.callback(None)
1037 -
        secondError = []
1121 +
        secondError: List[Failure] = []
1038 1122
        second.addErrback(secondError.append)
1039 1123
1040 -
        firstResult = []
1124 +
        firstResult: List[None] = []
1041 1125
        first.addCallback(firstResult.append)
1042 -
        secondResult = []
1126 +
        secondResult: List[None] = []
1043 1127
        second.addCallback(secondResult.append)
1044 1128
1045 1129
        self.assertEqual(firstResult, [])
@@ -1050,7 +1134,7 @@
Loading
1050 1134
        self.assertEqual(firstResult, [None])
1051 1135
        self.assertEqual(len(secondResult), 1)
1052 1136
1053 -
    def test_doubleAsynchronousImplicitChaining(self):
1137 +
    def test_doubleAsynchronousImplicitChaining(self) -> None:
1054 1138
        """
1055 1139
        L{Deferred} chaining is transitive.
1056 1140
@@ -1058,13 +1142,13 @@
Loading
1058 1142
        callback on B and B is returned from a callback on A then when C fires,
1059 1143
        A fires.
1060 1144
        """
1061 -
        first = defer.Deferred()
1062 -
        second = defer.Deferred()
1145 +
        first: Deferred[object] = Deferred()
1146 +
        second: Deferred[object] = Deferred()
1063 1147
        second.addCallback(lambda ign: first)
1064 -
        third = defer.Deferred()
1148 +
        third: Deferred[object] = Deferred()
1065 1149
        third.addCallback(lambda ign: second)
1066 1150
1067 -
        thirdResult = []
1151 +
        thirdResult: List[object] = []
1068 1152
        third.addCallback(thirdResult.append)
1069 1153
1070 1154
        result = object()
@@ -1081,29 +1165,29 @@
Loading
1081 1165
1082 1166
        self.assertEqual(thirdResult, [result])
1083 1167
1084 -
    def test_nestedAsynchronousChainedDeferreds(self):
1168 +
    def test_nestedAsynchronousChainedDeferreds(self) -> None:
1085 1169
        """
1086 1170
        L{Deferred}s can have callbacks that themselves return L{Deferred}s.
1087 1171
        When these "inner" L{Deferred}s fire (even asynchronously), the
1088 1172
        callback chain continues.
1089 1173
        """
1090 -
        results = []
1091 -
        failures = []
1174 +
        results: List[Tuple[str, str]] = []
1175 +
        failures: List[Failure] = []
1092 1176
1093 1177
        # A Deferred returned in the inner callback.
1094 -
        inner = defer.Deferred()
1178 +
        inner: Deferred[str] = Deferred()
1095 1179
1096 -
        def cb(result):
1180 +
        def cb(result: str) -> Deferred[str]:
1097 1181
            results.append(("start-of-cb", result))
1098 1182
            d = defer.succeed("inner")
1099 1183
1100 -
            def firstCallback(result):
1184 +
            def firstCallback(result: str) -> Deferred[str]:
1101 1185
                results.append(("firstCallback", "inner"))
1102 1186
                # Return a Deferred that definitely has not fired yet, so we
1103 1187
                # can fire the Deferreds out of order.
1104 1188
                return inner
1105 1189
1106 -
            def secondCallback(result):
1190 +
            def secondCallback(result: str) -> str:
1107 1191
                results.append(("secondCallback", result))
1108 1192
                return result * 2
1109 1193
@@ -1142,7 +1226,7 @@
Loading
1142 1226
            ],
1143 1227
        )
1144 1228
1145 -
    def test_nestedAsynchronousChainedDeferredsWithExtraCallbacks(self):
1229 +
    def test_nestedAsynchronousChainedDeferredsWithExtraCallbacks(self) -> None:
1146 1230
        """
1147 1231
        L{Deferred}s can have callbacks that themselves return L{Deferred}s.
1148 1232
        These L{Deferred}s can have other callbacks added before they are
@@ -1150,26 +1234,30 @@
Loading
1150 1234
        L{Deferred}s fire (even asynchronously), the outer callback chain
1151 1235
        continues.
1152 1236
        """
1153 -
        results = []
1154 -
        failures = []
1237 +
        results: List[Any] = []
1238 +
        failures: List[Failure] = []
1155 1239
1156 1240
        # A Deferred returned in the inner callback after a callback is
1157 1241
        # added explicitly and directly to it.
1158 -
        inner = defer.Deferred()
1242 +
        inner: Deferred[Union[str, List[str]]] = Deferred()
1159 1243
1160 -
        def cb(result):
1244 +
        def cb(result: str) -> Deferred[str]:
1161 1245
            results.append(("start-of-cb", result))
1162 1246
            d = defer.succeed("inner")
1163 1247
1164 -
            def firstCallback(ignored):
1165 -
                results.append(("firstCallback", ignored))
1248 +
            def firstCallback(result: str) -> Deferred[List[str]]:
1249 +
                results.append(("firstCallback", result))
1166 1250
                # Return a Deferred that definitely has not fired yet with a
1167 1251
                # result-transforming callback so we can fire the Deferreds
1168 1252
                # out of order and see how the callback affects the ultimate
1169 1253
                # results.
1170 -
                return inner.addCallback(lambda x: [x])
1171 1254
1172 -
            def secondCallback(result):
1255 +
                def transform(result: str) -> List[str]:
1256 +
                    return [result]
1257 +
1258 +
                return inner.addCallback(transform)
1259 +
1260 +
            def secondCallback(result: List[str]) -> List[str]:
1173 1261
                results.append(("secondCallback", result))
1174 1262
                return result * 2
1175 1263
@@ -1209,16 +1297,16 @@
Loading
1209 1297
            ],
1210 1298
        )
1211 1299
1212 -
    def test_chainDeferredRecordsExplicitChain(self):
1300 +
    def test_chainDeferredRecordsExplicitChain(self) -> None:
1213 1301
        """
1214 1302
        When we chain a L{Deferred}, that chaining is recorded explicitly.
1215 1303
        """
1216 -
        a = defer.Deferred()
1217 -
        b = defer.Deferred()
1304 +
        a: Deferred[None] = Deferred()
1305 +
        b: Deferred[None] = Deferred()
1218 1306
        b.chainDeferred(a)
1219 1307
        self.assertIs(a._chainedTo, b)
1220 1308
1221 -
    def test_explicitChainClearedWhenResolved(self):
1309 +
    def test_explicitChainClearedWhenResolved(self) -> None:
1222 1310
        """
1223 1311
        Any recorded chaining is cleared once the chaining is resolved, since
1224 1312
        it no longer exists.
@@ -1227,32 +1315,32 @@
Loading
1227 1315
        result of another, and I{that} L{Deferred} has fired, then the
1228 1316
        dependency is resolved and we no longer benefit from recording it.
1229 1317
        """
1230 -
        a = defer.Deferred()
1231 -
        b = defer.Deferred()
1318 +
        a: Deferred[None] = Deferred()
1319 +
        b: Deferred[None] = Deferred()
1232 1320
        b.chainDeferred(a)
1233 1321
        b.callback(None)
1234 1322
        self.assertIsNone(a._chainedTo)
1235 1323
1236 -
    def test_chainDeferredRecordsImplicitChain(self):
1324 +
    def test_chainDeferredRecordsImplicitChain(self) -> None:
1237 1325
        """
1238 1326
        We can chain L{Deferred}s implicitly by adding callbacks that return
1239 1327
        L{Deferred}s. When this chaining happens, we record it explicitly as
1240 1328
        soon as we can find out about it.
1241 1329
        """
1242 -
        a = defer.Deferred()
1243 -
        b = defer.Deferred()
1330 +
        a: Deferred[None] = Deferred()
1331 +
        b: Deferred[None] = Deferred()
1244 1332
        a.addCallback(lambda ignored: b)
1245 1333
        a.callback(None)
1246 1334
        self.assertIs(a._chainedTo, b)
1247 1335
1248 -
    def test_circularChainWarning(self):
1336 +
    def test_circularChainWarning(self) -> None:
1249 1337
        """
1250 1338
        When a Deferred is returned from a callback directly attached to that
1251 1339
        same Deferred, a warning is emitted.
1252 1340
        """
1253 -
        d = defer.Deferred()
1341 +
        d: Deferred[str] = Deferred()
1254 1342
1255 -
        def circularCallback(result):
1343 +
        def circularCallback(result: str) -> Deferred[str]:
1256 1344
            return d
1257 1345
1258 1346
        d.addCallback(circularCallback)
@@ -1268,17 +1356,22 @@
Loading
1268 1356
            "\nExpected match: {!r}\nGot: {!r}".format(pattern, warning["message"]),
1269 1357
        )
1270 1358
1271 -
    def test_circularChainException(self):
1359 +
    def test_circularChainException(self) -> None:
1272 1360
        """
1273 1361
        If the deprecation warning for circular deferred callbacks is
1274 1362
        configured to be an error, the exception will become the failure
1275 1363
        result of the Deferred.
1276 1364
        """
1277 -
        self.addCleanup(setattr, warnings, "filters", warnings.filters)
1365 +
        self.addCleanup(
1366 +
            setattr,
1367 +
            warnings,
1368 +
            "filters",
1369 +
            warnings.filters,  # type: ignore[attr-defined]
1370 +
        )
1278 1371
        warnings.filterwarnings("error", category=DeprecationWarning)
1279 -
        d = defer.Deferred()
1372 +
        d: Deferred[str] = Deferred()
1280 1373
1281 -
        def circularCallback(result):
1374 +
        def circularCallback(result: str) -> Deferred[str]:
1282 1375
            return d
1283 1376
1284 1377
        d.addCallback(circularCallback)
@@ -1286,65 +1379,80 @@
Loading
1286 1379
        failure = self.failureResultOf(d)
1287 1380
        failure.trap(DeprecationWarning)
1288 1381
1289 -
    def test_repr(self):
1382 +
    def test_repr(self) -> None:
1290 1383
        """
1291 1384
        The C{repr()} of a L{Deferred} contains the class name and a
1292 1385
        representation of the internal Python ID.
1293 1386
        """
1294 -
        d = defer.Deferred()
1387 +
        d: Deferred[None] = Deferred()
1295 1388
        address = id(d)
1296 1389
        self.assertEqual(repr(d), f"<Deferred at 0x{address:x}>")
1297 1390
1298 -
    def test_reprWithResult(self):
1391 +
    def test_reprWithResult(self) -> None:
1299 1392
        """
1300 1393
        If a L{Deferred} has been fired, then its C{repr()} contains its
1301 1394
        result.
1302 1395
        """
1303 -
        d = defer.Deferred()
1396 +
        d: Deferred[str] = Deferred()
1304 1397
        d.callback("orange")
1305 1398
        self.assertEqual(
1306 1399
            repr(d), "<Deferred at 0x{:x} current result: 'orange'>".format(id(d))
1307 1400
        )
1308 1401
1309 -
    def test_reprWithChaining(self):
1402 +
    def test_reprWithChaining(self) -> None:
1310 1403
        """
1311 1404
        If a L{Deferred} C{a} has been fired, but is waiting on another
1312 1405
        L{Deferred} C{b} that appears in its callback chain, then C{repr(a)}
1313 1406
        says that it is waiting on C{b}.
1314 1407
        """
1315 -
        a = defer.Deferred()
1316 -
        b = defer.Deferred()
1408 +
        a: Deferred[None] = Deferred()
1409 +
        b: Deferred[None] = Deferred()
1317 1410
        b.chainDeferred(a)
1318 1411
        self.assertEqual(
1319 1412
            repr(a),
1320 1413
            "<Deferred at 0x{:x} waiting on Deferred at 0x{:x}>".format(id(a), id(b)),
1321 1414
        )
1322 1415
1323 -
    def test_boundedStackDepth(self):
1416 +
    def test_boundedStackDepth(self) -> None:
1324 1417
        """
1325 1418
        The depth of the call stack does not grow as more L{Deferred} instances
1326 1419
        are chained together.
1327 1420
        """
1328 1421
1329 -
        def chainDeferreds(howMany):
1422 +
        def chainDeferreds(howMany: int) -> int:
1330 1423
            stack = []
1331 1424
1332 -
            def recordStackDepth(ignored):
1425 +
            def recordStackDepth(ignored: object) -> None:
1333 1426
                stack.append(len(traceback.extract_stack()))
1334 1427
1335 -
            top = defer.Deferred()
1336 -
            innerDeferreds = [defer.Deferred() for ignored in range(howMany)]
1428 +
            top: Deferred[None] = Deferred()
1429 +
            innerDeferreds: List[Deferred[None]] = [
1430 +
                Deferred() for ignored in range(howMany)
1431 +
            ]
1337 1432
            originalInners = innerDeferreds[:]
1338 -
            last = defer.Deferred()
1433 +
            last: Deferred[None] = Deferred()
1339 1434
1340 1435
            inner = innerDeferreds.pop()
1341 -
            top.addCallback(lambda ign, inner=inner: inner)
1436 +
1437 +
            def cbInner(
1438 +
                ignored: object, inner: Deferred[None] = inner
1439 +
            ) -> Deferred[None]:
1440 +
                return inner
1441 +
1442 +
            top.addCallback(cbInner)
1342 1443
            top.addCallback(recordStackDepth)
1343 1444
1344 1445
            while innerDeferreds:
1345 1446
                newInner = innerDeferreds.pop()
1346 -
                inner.addCallback(lambda ign, inner=newInner: inner)
1447 +
1448 +
                def cbNewInner(
1449 +
                    ignored: object, inner: Deferred[None] = newInner
1450 +
                ) -> Deferred[None]:
1451 +
                    return inner
1452 +
1453 +
                inner.addCallback(cbNewInner)
1347 1454
                inner = newInner
1455 +
1348 1456
            inner.addCallback(lambda ign: last)
1349 1457
1350 1458
            top.callback(None)
@@ -1364,7 +1472,7 @@
Loading
1364 1472
        # how many Deferreds are chained.
1365 1473
        self.assertEqual(chainDeferreds(1), chainDeferreds(2))
1366 1474
1367 -
    def test_resultOfDeferredResultOfDeferredOfFiredDeferredCalled(self):
1475 +
    def test_resultOfDeferredResultOfDeferredOfFiredDeferredCalled(self) -> None:
1368 1476
        """
1369 1477
        Given three Deferreds, one chained to the next chained to the next,
1370 1478
        callbacks on the middle Deferred which are added after the chain is
@@ -1375,27 +1483,27 @@
Loading
1375 1483
        it does exercise a broken codepath through one of the variations of the
1376 1484
        implementation proposed as a resolution to ticket #411.
1377 1485
        """
1378 -
        first = defer.Deferred()
1379 -
        second = defer.Deferred()
1380 -
        third = defer.Deferred()
1486 +
        first: Deferred[None] = Deferred()
1487 +
        second: Deferred[None] = Deferred()
1488 +
        third: Deferred[None] = Deferred()
1381 1489
        first.addCallback(lambda ignored: second)
1382 1490
        second.addCallback(lambda ignored: third)
1383 1491
        second.callback(None)
1384 1492
        first.callback(None)
1385 1493
        third.callback(None)
1386 -
        L = []
1387 -
        second.addCallback(L.append)
1388 -
        self.assertEqual(L, [None])
1494 +
        results: List[None] = []
1495 +
        second.addCallback(results.append)
1496 +
        self.assertEqual(results, [None])
1389 1497
1390 -
    def test_errbackWithNoArgsNoDebug(self):
1498 +
    def test_errbackWithNoArgsNoDebug(self) -> None:
1391 1499
        """
1392 1500
        C{Deferred.errback()} creates a failure from the current Python
1393 1501
        exception.  When Deferred.debug is not set no globals or locals are
1394 1502
        captured in that failure.
1395 1503
        """
1396 1504
        defer.setDebugging(False)
1397 -
        d = defer.Deferred()
1398 -
        l = []
1505 +
        d: Deferred[None] = Deferred()
1506 +
        l: List[Failure] = []
1399 1507
        exc = GenericError("Bang")
1400 1508
        try:
1401 1509
            raise exc
@@ -1408,15 +1516,15 @@
Loading
1408 1516
        self.assertEqual([], localz)
1409 1517
        self.assertEqual([], globalz)
1410 1518
1411 -
    def test_errbackWithNoArgs(self):
1519 +
    def test_errbackWithNoArgs(self) -> None:
1412 1520
        """
1413 1521
        C{Deferred.errback()} creates a failure from the current Python
1414 1522
        exception.  When Deferred.debug is set globals and locals are captured
1415 1523
        in that failure.
1416 1524
        """
1417 1525
        defer.setDebugging(True)
1418 -
        d = defer.Deferred()
1419 -
        l = []
1526 +
        d: Deferred[None] = Deferred()
1527 +
        l: List[Failure] = []
1420 1528
        exc = GenericError("Bang")
1421 1529
        try:
1422 1530
            raise exc
@@ -1429,62 +1537,62 @@
Loading
1429 1537
        self.assertNotEqual([], localz)
1430 1538
        self.assertNotEqual([], globalz)
1431 1539
1432 -
    def test_errorInCallbackDoesNotCaptureVars(self):
1540 +
    def test_errorInCallbackDoesNotCaptureVars(self) -> None:
1433 1541
        """
1434 1542
        An error raised by a callback creates a Failure.  The Failure captures
1435 1543
        locals and globals if and only if C{Deferred.debug} is set.
1436 1544
        """
1437 -
        d = defer.Deferred()
1545 +
        d: Deferred[None] = Deferred()
1438 1546
        d.callback(None)
1439 1547
        defer.setDebugging(False)
1440 1548
1441 -
        def raiseError(ignored):
1549 +
        def raiseError(ignored: object) -> None:
1442 1550
            raise GenericError("Bang")
1443 1551
1444 1552
        d.addCallback(raiseError)
1445 -
        l = []
1553 +
        l: List[Failure] = []
1446 1554
        d.addErrback(l.append)
1447 1555
        fail = l[0]
1448 1556
        localz, globalz = fail.frames[0][-2:]
1449 1557
        self.assertEqual([], localz)
1450 1558
        self.assertEqual([], globalz)
1451 1559
1452 -
    def test_errorInCallbackCapturesVarsWhenDebugging(self):
1560 +
    def test_errorInCallbackCapturesVarsWhenDebugging(self) -> None:
1453 1561
        """
1454 1562
        An error raised by a callback creates a Failure.  The Failure captures
1455 1563
        locals and globals if and only if C{Deferred.debug} is set.
1456 1564
        """
1457 -
        d = defer.Deferred()
1565 +
        d: Deferred[None] = Deferred()
1458 1566
        d.callback(None)
1459 1567
        defer.setDebugging(True)
1460 1568
1461 -
        def raiseError(ignored):
1569 +
        def raiseError(ignored: object) -> None:
1462 1570
            raise GenericError("Bang")
1463 1571
1464 1572
        d.addCallback(raiseError)
1465 -
        l = []
1573 +
        l: List[Failure] = []
1466 1574
        d.addErrback(l.append)
1467 1575
        fail = l[0]
1468 1576
        localz, globalz = fail.frames[0][-2:]
1469 1577
        self.assertNotEqual([], localz)
1470 1578
        self.assertNotEqual([], globalz)
1471 1579
1472 -
    def test_inlineCallbacksTracebacks(self):
1580 +
    def test_inlineCallbacksTracebacks(self) -> None:
1473 1581
        """
1474 1582
        L{defer.inlineCallbacks} that re-raise tracebacks into their deferred
1475 1583
        should not lose their tracebacks.
1476 1584
        """
1477 1585
        f = getDivisionFailure()
1478 -
        d = defer.Deferred()
1586 +
        d: Deferred[None] = Deferred()
1479 1587
        try:
1480 1588
            f.raiseException()
1481 1589
        except BaseException:
1482 1590
            d.errback()
1483 1591
1484 -
        def ic(d):
1592 +
        def ic(d: object) -> Generator[Any, Any, None]:
1485 1593
            yield d
1486 1594
1487 -
        ic = defer.inlineCallbacks(ic)
1595 +
        defer.inlineCallbacks(ic)
1488 1596
        newFailure = self.failureResultOf(d)
1489 1597
        tb = traceback.extract_tb(newFailure.getTracebackObject())
1490 1598
@@ -1497,7 +1605,7 @@
Loading
1497 1605
        self.assertEqual("test_inlineCallbacksTracebacks", tb[0][2])
1498 1606
        self.assertEqual("f.raiseException()", tb[0][3])
1499 1607
1500 -
    def test_fromCoroutineRequiresCoroutine(self):
1608 +
    def test_fromCoroutineRequiresCoroutine(self) -> None:
1501 1609
        """
1502 1610
        L{Deferred.fromCoroutine} requires a coroutine object or a generator,
1503 1611
        and will reject things that are not that.
@@ -1518,9 +1626,7 @@
Loading
1518 1626
        ]
1519 1627
1520 1628
        for thing in thingsThatAreNotCoroutines:
1521 -
            self.assertRaises(
1522 -
                defer.NotACoroutineError, defer.Deferred.fromCoroutine, thing
1523 -
            )
1629 +
            self.assertRaises(defer.NotACoroutineError, Deferred.fromCoroutine, thing)
1524 1630
1525 1631
1526 1632
class FirstErrorTests(unittest.SynchronousTestCase):
@@ -1528,7 +1634,7 @@
Loading
1528 1634
    Tests for L{FirstError}.
1529 1635
    """
1530 1636
1531 -
    def test_repr(self):
1637 +
    def test_repr(self) -> None:
1532 1638
        """
1533 1639
        The repr of a L{FirstError} instance includes the repr of the value of
1534 1640
        the sub-failure and the index which corresponds to the L{FirstError}.
@@ -1537,12 +1643,12 @@
Loading
1537 1643
        try:
1538 1644
            raise exc
1539 1645
        except BaseException:
1540 -
            f = failure.Failure()
1646 +
            f = Failure()
1541 1647
1542 1648
        error = defer.FirstError(f, 3)
1543 1649
        self.assertEqual(repr(error), "FirstError[#3, {}]".format(repr(exc)))
1544 1650
1545 -
    def test_str(self):
1651 +
    def test_str(self) -> None:
1546 1652
        """
1547 1653
        The str of a L{FirstError} instance includes the str of the
1548 1654
        sub-failure and the index which corresponds to the L{FirstError}.
@@ -1551,12 +1657,12 @@
Loading
1551 1657
        try:
1552 1658
            raise exc
1553 1659
        except BaseException:
1554 -
            f = failure.Failure()
1660 +
            f = Failure()
1555 1661
1556 1662
        error = defer.FirstError(f, 5)
1557 1663
        self.assertEqual(str(error), "FirstError[#5, {}]".format(str(f)))
1558 1664
1559 -
    def test_comparison(self):
1665 +
    def test_comparison(self) -> None:
1560 1666
        """
1561 1667
        L{FirstError} instances compare equal to each other if and only if
1562 1668
        their failure and index compare equal.  L{FirstError} instances do not
@@ -1565,7 +1671,7 @@
Loading
1565 1671
        try:
1566 1672
            1 // 0
1567 1673
        except BaseException:
1568 -
            firstFailure = failure.Failure()
1674 +
            firstFailure = Failure()
1569 1675
1570 1676
        one = defer.FirstError(firstFailure, 13)
1571 1677
        anotherOne = defer.FirstError(firstFailure, 13)
@@ -1573,7 +1679,7 @@
Loading
1573 1679
        try:
1574 1680
            raise ValueError("bar")
1575 1681
        except BaseException:
1576 -
            secondFailure = failure.Failure()
1682 +
            secondFailure = Failure()
1577 1683
1578 1684
        another = defer.FirstError(secondFailure, 9)
1579 1685
@@ -1586,63 +1692,63 @@
Loading
1586 1692
1587 1693
1588 1694
class AlreadyCalledTests(unittest.SynchronousTestCase):
1589 -
    def setUp(self):
1695 +
    def setUp(self) -> None:
1590 1696
        self._deferredWasDebugging = defer.getDebugging()
1591 1697
        defer.setDebugging(True)
1592 1698
1593 -
    def tearDown(self):
1699 +
    def tearDown(self) -> None:
1594 1700
        defer.setDebugging(self._deferredWasDebugging)
1595 1701
1596 -
    def _callback(self, *args, **kw):
1702 +
    def _callback(self, *args: object, **kwargs: object) -> None:
1597 1703
        pass
1598 1704
1599 -
    def _errback(self, *args, **kw):
1705 +
    def _errback(self, *args: object, **kwargs: object) -> None:
1600 1706
        pass
1601 1707
1602 -
    def _call_1(self, d):
1708 +
    def _call_1(self, d: Deferred[str]) -> None:
1603 1709
        d.callback("hello")
1604 1710
1605 -
    def _call_2(self, d):
1711 +
    def _call_2(self, d: Deferred[str]) -> None:
1606 1712
        d.callback("twice")
1607 1713
1608 -
    def _err_1(self, d):
1609 -
        d.errback(failure.Failure(RuntimeError()))
1714 +
    def _err_1(self, d: Deferred[str]) -> None:
1715 +
        d.errback(Failure(RuntimeError()))
1610 1716
1611 -
    def _err_2(self, d):
1612 -
        d.errback(failure.Failure(RuntimeError()))
1717 +
    def _err_2(self, d: Deferred[str]) -> None:
1718 +
        d.errback(Failure(RuntimeError()))
1613 1719
1614 -
    def testAlreadyCalled_CC(self):
1615 -
        d = defer.Deferred()
1720 +
    def testAlreadyCalled_CC(self) -> None:
1721 +
        d: Deferred[str] = Deferred()
1616 1722
        d.addCallbacks(self._callback, self._errback)
1617 1723
        self._call_1(d)
1618 1724
        self.assertRaises(defer.AlreadyCalledError, self._call_2, d)
1619 1725
1620 -
    def testAlreadyCalled_CE(self):
1621 -
        d = defer.Deferred()
1726 +
    def testAlreadyCalled_CE(self) -> None:
1727 +
        d: Deferred[str] = Deferred()
1622 1728
        d.addCallbacks(self._callback, self._errback)
1623 1729
        self._call_1(d)
1624 1730
        self.assertRaises(defer.AlreadyCalledError, self._err_2, d)
1625 1731
1626 -
    def testAlreadyCalled_EE(self):
1627 -
        d = defer.Deferred()
1732 +
    def testAlreadyCalled_EE(self) -> None:
1733 +
        d: Deferred[str] = Deferred()
1628 1734
        d.addCallbacks(self._callback, self._errback)
1629 1735
        self._err_1(d)
1630 1736
        self.assertRaises(defer.AlreadyCalledError, self._err_2, d)
1631 1737
1632 -
    def testAlreadyCalled_EC(self):
1633 -
        d = defer.Deferred()
1738 +
    def testAlreadyCalled_EC(self) -> None:
1739 +
        d: Deferred[str] = Deferred()
1634 1740
        d.addCallbacks(self._callback, self._errback)
1635 1741
        self._err_1(d)
1636 1742
        self.assertRaises(defer.AlreadyCalledError, self._call_2, d)
1637 1743
1638 -
    def _count(self, linetype, func, lines, expected):
1744 +
    def _count(self, linetype: str, func: str, lines: List[str], expected: int) -> None:
1639 1745
        count = 0
1640 1746
        for line in lines:
1641 1747
            if line.startswith(" %s:" % linetype) and line.endswith(" %s" % func):
1642 1748
                count += 1
1643 1749
        self.assertTrue(count == expected)
1644 1750
1645 -
    def _check(self, e, caller, invoker1, invoker2):
1751 +
    def _check(self, e: Exception, caller: str, invoker1: str, invoker2: str) -> None:
1646 1752
        # make sure the debugging information is vaguely correct
1647 1753
        lines = e.args[0].split("\n")
1648 1754
        # the creator should list the creator (testAlreadyCalledDebug) but not
@@ -1656,8 +1762,8 @@
Loading
1656 1762
        self._count("I", invoker1, lines, 1)
1657 1763
        self._count("I", invoker2, lines, 0)
1658 1764
1659 -
    def testAlreadyCalledDebug_CC(self):
1660 -
        d = defer.Deferred()
1765 +
    def testAlreadyCalledDebug_CC(self) -> None:
1766 +
        d: Deferred[str] = Deferred()
1661 1767
        d.addCallbacks(self._callback, self._errback)
1662 1768
        self._call_1(d)
1663 1769
        try:
@@ -1667,8 +1773,8 @@
Loading
1667 1773
        else:
1668 1774
            self.fail("second callback failed to raise AlreadyCalledError")
1669 1775
1670 -
    def testAlreadyCalledDebug_CE(self):
1671 -
        d = defer.Deferred()
1776 +
    def testAlreadyCalledDebug_CE(self) -> None:
1777 +
        d: Deferred[str] = Deferred()
1672 1778
        d.addCallbacks(self._callback, self._errback)
1673 1779
        self._call_1(d)
1674 1780
        try:
@@ -1678,8 +1784,8 @@
Loading
1678 1784
        else:
1679 1785
            self.fail("second errback failed to raise AlreadyCalledError")
1680 1786
1681 -
    def testAlreadyCalledDebug_EC(self):
1682 -
        d = defer.Deferred()
1787 +
    def testAlreadyCalledDebug_EC(self) -> None:
1788 +
        d: Deferred[str] = Deferred()
1683 1789
        d.addCallbacks(self._callback, self._errback)
1684 1790
        self._err_1(d)
1685 1791
        try:
@@ -1689,8 +1795,8 @@
Loading
1689 1795
        else:
1690 1796
            self.fail("second callback failed to raise AlreadyCalledError")
1691 1797
1692 -
    def testAlreadyCalledDebug_EE(self):
1693 -
        d = defer.Deferred()
1798 +
    def testAlreadyCalledDebug_EE(self) -> None:
1799 +
        d: Deferred[str] = Deferred()
1694 1800
        d.addCallbacks(self._callback, self._errback)
1695 1801
        self._err_1(d)
1696 1802
        try:
@@ -1700,9 +1806,9 @@
Loading
1700 1806
        else:
1701 1807
            self.fail("second errback failed to raise AlreadyCalledError")
1702 1808
1703 -
    def testNoDebugging(self):
1809 +
    def testNoDebugging(self) -> None:
1704 1810
        defer.setDebugging(False)
1705 -
        d = defer.Deferred()
1811 +
        d: Deferred[str] = Deferred()
1706 1812
        d.addCallbacks(self._callback, self._errback)
1707 1813
        self._call_1(d)
1708 1814
        try:
@@ -1712,61 +1818,62 @@
Loading
1712 1818
        else:
1713 1819
            self.fail("second callback failed to raise AlreadyCalledError")
1714 1820
1715 -
    def testSwitchDebugging(self):
1821 +
    def testSwitchDebugging(self) -> None:
1716 1822
        # Make sure Deferreds can deal with debug state flipping
1717 1823
        # around randomly.  This is covering a particular fixed bug.
1718 1824
        defer.setDebugging(False)
1719 -
        d = defer.Deferred()
1825 +
        d: Deferred[None] = Deferred()
1720 1826
        d.addBoth(lambda ign: None)
1721 1827
        defer.setDebugging(True)
1722 1828
        d.callback(None)
1723 1829
1724 1830
        defer.setDebugging(False)
1725 -
        d = defer.Deferred()
1831 +
        d = Deferred()
1726 1832
        d.callback(None)
1727 1833
        defer.setDebugging(True)
1728 1834
        d.addBoth(lambda ign: None)
1729 1835
1730 1836
1731 1837
class DeferredCancellerTests(unittest.SynchronousTestCase):
1732 -
    def setUp(self):
1733 -
        self.callbackResults = None
1734 -
        self.errbackResults = None
1735 -
        self.callback2Results = None
1838 +
    def setUp(self) -> None:
1839 +
        self.callbackResults: Optional[str] = None
1840 +
        self.errbackResults: Optional[Failure] = None
1841 +
        self.callback2Results: Optional[str] = None
1736 1842
        self.cancellerCallCount = 0
1737 1843
1738 -
    def tearDown(self):
1844 +
    def tearDown(self) -> None:
1739 1845
        # Sanity check that the canceller was called at most once.
1740 1846
        self.assertIn(self.cancellerCallCount, (0, 1))
1741 1847
1742 -
    def _callback(self, data):
1848 +
    def _callback(self, data: str) -> str:
1743 1849
        self.callbackResults = data
1744 1850
        return data
1745 1851
1746 -
    def _callback2(self, data):
1852 +
    def _callback2(self, data: str) -> None:
1747 1853
        self.callback2Results = data
1748 1854
1749 -
    def _errback(self, data):
1750 -
        self.errbackResults = data
1855 +
    def _errback(self, error: Failure) -> None:
1856 +
        self.errbackResults = error
1751 1857
1752 -
    def test_noCanceller(self):
1858 +
    def test_noCanceller(self) -> None:
1753 1859
        """
1754 -
        A L{defer.Deferred} without a canceller must errback with a
1860 +
        A L{Deferred} without a canceller must errback with a
1755 1861
        L{defer.CancelledError} and not callback.
1756 1862
        """
1757 -
        d = defer.Deferred()
1863 +
        d: Deferred[None] = Deferred()
1758 1864
        d.addCallbacks(self._callback, self._errback)
1759 1865
        d.cancel()
1866 +
        assert self.errbackResults is not None
1760 1867
        self.assertEqual(self.errbackResults.type, defer.CancelledError)
1761 1868
        self.assertIsNone(self.callbackResults)
1762 1869
1763 -
    def test_raisesAfterCancelAndCallback(self):
1870 +
    def test_raisesAfterCancelAndCallback(self) -> None:
1764 1871
        """
1765 -
        A L{defer.Deferred} without a canceller, when cancelled must allow
1872 +
        A L{Deferred} without a canceller, when cancelled must allow
1766 1873
        a single extra call to callback, and raise
1767 1874
        L{defer.AlreadyCalledError} if callbacked or errbacked thereafter.
1768 1875
        """
1769 -
        d = defer.Deferred()
1876 +
        d: Deferred[None] = Deferred()
1770 1877
        d.addCallbacks(self._callback, self._errback)
1771 1878
        d.cancel()
1772 1879
@@ -1777,13 +1884,13 @@
Loading
1777 1884
        self.assertRaises(defer.AlreadyCalledError, d.callback, None)
1778 1885
        self.assertRaises(defer.AlreadyCalledError, d.errback, Exception())
1779 1886
1780 -
    def test_raisesAfterCancelAndErrback(self):
1887 +
    def test_raisesAfterCancelAndErrback(self) -> None:
1781 1888
        """
1782 -
        A L{defer.Deferred} without a canceller, when cancelled must allow
1889 +
        A L{Deferred} without a canceller, when cancelled must allow
1783 1890
        a single extra call to errback, and raise
1784 1891
        L{defer.AlreadyCalledError} if callbacked or errbacked thereafter.
1785 1892
        """
1786 -
        d = defer.Deferred()
1893 +
        d: Deferred[None] = Deferred()
1787 1894
        d.addCallbacks(self._callback, self._errback)
1788 1895
        d.cancel()
1789 1896
@@ -1794,12 +1901,12 @@
Loading
1794 1901
        self.assertRaises(defer.AlreadyCalledError, d.callback, None)
1795 1902
        self.assertRaises(defer.AlreadyCalledError, d.errback, Exception())
1796 1903
1797 -
    def test_noCancellerMultipleCancelsAfterCancelAndCallback(self):
1904 +
    def test_noCancellerMultipleCancelsAfterCancelAndCallback(self) -> None:
1798 1905
        """
1799 1906
        A L{Deferred} without a canceller, when cancelled and then
1800 1907
        callbacked, ignores multiple cancels thereafter.
1801 1908
        """
1802 -
        d = defer.Deferred()
1909 +
        d: Deferred[None] = Deferred()
1803 1910
        d.addCallbacks(self._callback, self._errback)
1804 1911
        d.cancel()
1805 1912
        currentFailure = self.errbackResults
@@ -1809,14 +1916,15 @@
Loading
1809 1916
        d.cancel()
1810 1917
        self.assertIs(currentFailure, self.errbackResults)
1811 1918
1812 -
    def test_noCancellerMultipleCancelsAfterCancelAndErrback(self):
1919 +
    def test_noCancellerMultipleCancelsAfterCancelAndErrback(self) -> None:
1813 1920
        """
1814 -
        A L{defer.Deferred} without a canceller, when cancelled and then
1921 +
        A L{Deferred} without a canceller, when cancelled and then
1815 1922
        errbacked, ignores multiple cancels thereafter.
1816 1923
        """
1817 -
        d = defer.Deferred()
1924 +
        d: Deferred[None] = Deferred()
1818 1925
        d.addCallbacks(self._callback, self._errback)
1819 1926
        d.cancel()
1927 +
        assert self.errbackResults is not None
1820 1928
        self.assertEqual(self.errbackResults.type, defer.CancelledError)
1821 1929
        currentFailure = self.errbackResults
1822 1930
        # One errback will be ignored
@@ -1826,21 +1934,22 @@
Loading
1826 1934
        d.cancel()
1827 1935
        self.assertIs(currentFailure, self.errbackResults)
1828 1936
1829 -
    def test_noCancellerMultipleCancel(self):
1937 +
    def test_noCancellerMultipleCancel(self) -> None:
1830 1938
        """
1831 1939
        Calling cancel multiple times on a deferred with no canceller
1832 1940
        results in a L{defer.CancelledError}. Subsequent calls to cancel
1833 1941
        do not cause an error.
1834 1942
        """
1835 -
        d = defer.Deferred()
1943 +
        d: Deferred[None] = Deferred()
1836 1944
        d.addCallbacks(self._callback, self._errback)
1837 1945
        d.cancel()
1946 +
        assert self.errbackResults is not None
1838 1947
        self.assertEqual(self.errbackResults.type, defer.CancelledError)
1839 1948
        currentFailure = self.errbackResults
1840 1949
        d.cancel()
1841 1950
        self.assertIs(currentFailure, self.errbackResults)
1842 1951
1843 -
    def test_cancellerMultipleCancel(self):
1952 +
    def test_cancellerMultipleCancel(self) -> None:
1844 1953
        """
1845 1954
        Verify that calling cancel multiple times on a deferred with a
1846 1955
        canceller that does not errback results in a
@@ -1849,61 +1958,63 @@
Loading
1849 1958
        called once.
1850 1959
        """
1851 1960
1852 -
        def cancel(d):
1961 +
        def cancel(d: Deferred[object]) -> None:
1853 1962
            self.cancellerCallCount += 1
1854 1963
1855 -
        d = defer.Deferred(canceller=cancel)
1964 +
        d: Deferred[None] = Deferred(canceller=cancel)
1856 1965
        d.addCallbacks(self._callback, self._errback)
1857 1966
        d.cancel()
1967 +
        assert self.errbackResults is not None
1858 1968
        self.assertEqual(self.errbackResults.type, defer.CancelledError)
1859 1969
        currentFailure = self.errbackResults
1860 1970
        d.cancel()
1861 1971
        self.assertIs(currentFailure, self.errbackResults)
1862 1972
        self.assertEqual(self.cancellerCallCount, 1)
1863 1973
1864 -
    def test_simpleCanceller(self):
1974 +
    def test_simpleCanceller(self) -> None:
1865 1975
        """
1866 -
        Verify that a L{defer.Deferred} calls its specified canceller when
1976 +
        Verify that a L{Deferred} calls its specified canceller when
1867 1977
        it is cancelled, and that further call/errbacks raise
1868 1978
        L{defer.AlreadyCalledError}.
1869 1979
        """
1870 1980
1871 -
        def cancel(d):
1981 +
        def cancel(d: Deferred[object]) -> None:
1872 1982
            self.cancellerCallCount += 1
1873 1983
1874 -
        d = defer.Deferred(canceller=cancel)
1984 +
        d: Deferred[None] = Deferred(canceller=cancel)
1875 1985
        d.addCallbacks(self._callback, self._errback)
1876 1986
        d.cancel()
1877 1987
        self.assertEqual(self.cancellerCallCount, 1)
1988 +
        assert self.errbackResults is not None
1878 1989
        self.assertEqual(self.errbackResults.type, defer.CancelledError)
1879 1990
1880 1991
        # Test that further call/errbacks are *not* swallowed
1881 1992
        self.assertRaises(defer.AlreadyCalledError, d.callback, None)
1882 1993
        self.assertRaises(defer.AlreadyCalledError, d.errback, Exception())
1883 1994
1884 -
    def test_cancellerArg(self):
1995 +
    def test_cancellerArg(self) -> None:
1885 1996
        """
1886 1997
        Verify that a canceller is given the correct deferred argument.
1887 1998
        """
1888 1999
1889 -
        def cancel(d1):
2000 +
        def cancel(d1: Deferred[object]) -> None:
1890 2001
            self.assertIs(d1, d)
1891 2002
1892 -
        d = defer.Deferred(canceller=cancel)
2003 +
        d: Deferred[None] = Deferred(canceller=cancel)
1893 2004
        d.addCallbacks(self._callback, self._errback)
1894 2005
        d.cancel()
1895 2006
1896 -
    def test_cancelAfterCallback(self):
2007 +
    def test_cancelAfterCallback(self) -> None:
1897 2008
        """
1898 2009
        Test that cancelling a deferred after it has been callbacked does
1899 2010
        not cause an error.
1900 2011
        """
1901 2012
1902 -
        def cancel(d):
2013 +
        def cancel(d: Deferred[object]) -> None:
1903 2014
            self.cancellerCallCount += 1
1904 2015
            d.errback(GenericError())
1905 2016
1906 -
        d = defer.Deferred(canceller=cancel)
2017 +
        d: Deferred[str] = Deferred(canceller=cancel)
1907 2018
        d.addCallbacks(self._callback, self._errback)
1908 2019
        d.callback("biff!")
1909 2020
        d.cancel()
@@ -1911,70 +2022,72 @@
Loading
1911 2022
        self.assertIsNone(self.errbackResults)
1912 2023
        self.assertEqual(self.callbackResults, "biff!")
1913 2024
1914 -
    def test_cancelAfterErrback(self):
2025 +
    def test_cancelAfterErrback(self) -> None:
1915 2026
        """
1916 2027
        Test that cancelling a L{Deferred} after it has been errbacked does
1917 2028
        not result in a L{defer.CancelledError}.
1918 2029
        """
1919 2030
1920 -
        def cancel(d):
2031 +
        def cancel(d: Deferred[object]) -> None:
1921 2032
            self.cancellerCallCount += 1
1922 2033
            d.errback(GenericError())
1923 2034
1924 -
        d = defer.Deferred(canceller=cancel)
2035 +
        d: Deferred[None] = Deferred(canceller=cancel)
1925 2036
        d.addCallbacks(self._callback, self._errback)
1926 2037
        d.errback(GenericError())
1927 2038
        d.cancel()
1928 2039
        self.assertEqual(self.cancellerCallCount, 0)
2040 +
        assert self.errbackResults is not None
1929 2041
        self.assertEqual(self.errbackResults.type, GenericError)
1930 2042
        self.assertIsNone(self.callbackResults)
1931 2043
1932 -
    def test_cancellerThatErrbacks(self):
2044 +
    def test_cancellerThatErrbacks(self) -> None:
1933 2045
        """
1934 2046
        Test a canceller which errbacks its deferred.
1935 2047
        """
1936 2048
1937 -
        def cancel(d):
2049 +
        def cancel(d: Deferred[object]) -> None:
1938 2050
            self.cancellerCallCount += 1
1939 2051
            d.errback(GenericError())
1940 2052
1941 -
        d = defer.Deferred(canceller=cancel)
2053 +
        d: Deferred[None] = Deferred(canceller=cancel)
1942 2054
        d.addCallbacks(self._callback, self._errback)
1943 2055
        d.cancel()
1944 2056
        self.assertEqual(self.cancellerCallCount, 1)
2057 +
        assert self.errbackResults is not None
1945 2058
        self.assertEqual(self.errbackResults.type, GenericError)
1946 2059
1947 -
    def test_cancellerThatCallbacks(self):
2060 +
    def test_cancellerThatCallbacks(self) -> None:
1948 2061
        """
1949 2062
        Test a canceller which calls its deferred.
1950 2063
        """
1951 2064
1952 -
        def cancel(d):
2065 +
        def cancel(d: Deferred[object]) -> None:
1953 2066
            self.cancellerCallCount += 1
1954 2067
            d.callback("hello!")
1955 2068
1956 -
        d = defer.Deferred(canceller=cancel)
2069 +
        d: Deferred[None] = Deferred(canceller=cancel)
1957 2070
        d.addCallbacks(self._callback, self._errback)
1958 2071
        d.cancel()
1959 2072
        self.assertEqual(self.cancellerCallCount, 1)
1960 2073
        self.assertEqual(self.callbackResults, "hello!")
1961 2074
        self.assertIsNone(self.errbackResults)
1962 2075
1963 -
    def test_cancelNestedDeferred(self):
2076 +
    def test_cancelNestedDeferred(self) -> None:
1964 2077
        """
1965 2078
        Verify that a Deferred, a, which is waiting on another Deferred, b,
1966 2079
        returned from one of its callbacks, will propagate
1967 2080
        L{defer.CancelledError} when a is cancelled.
1968 2081
        """
1969 2082
1970 -
        def innerCancel(d):
2083 +
        def innerCancel(d: Deferred[object]) -> None:
1971 2084
            self.cancellerCallCount += 1
1972 2085
1973 -
        def cancel(d):
2086 +
        def cancel(d: Deferred[object]) -> None:
1974 2087
            self.assertTrue(False)
1975 2088
1976 -
        b = defer.Deferred(canceller=innerCancel)
1977 -
        a = defer.Deferred(canceller=cancel)
2089 +
        b: Deferred[None] = Deferred(canceller=innerCancel)
2090 +
        a: Deferred[None] = Deferred(canceller=cancel)
1978 2091
        a.callback(None)
1979 2092
        a.addCallback(lambda data: b)
1980 2093
        a.cancel()
@@ -1983,6 +2096,7 @@
Loading
1983 2096
        self.assertEqual(self.cancellerCallCount, 1)
1984 2097
        # B's canceller didn't errback, so defer.py will have called errback
1985 2098
        # with a CancelledError.
2099 +
        assert self.errbackResults is not None
1986 2100
        self.assertEqual(self.errbackResults.type, defer.CancelledError)
1987 2101
1988 2102
@@ -1991,23 +2105,23 @@
Loading
1991 2105
    Test logging of unhandled errors.
1992 2106
    """
1993 2107
1994 -
    def setUp(self):
2108 +
    def setUp(self) -> None:
1995 2109
        """
1996 2110
        Add a custom observer to observer logging.
1997 2111
        """
1998 -
        self.c = []
2112 +
        self.c: List[Dict[str, Any]] = []
1999 2113
        log.addObserver(self.c.append)
2000 2114
2001 -
    def tearDown(self):
2115 +
    def tearDown(self) -> None:
2002 2116
        """
2003 2117
        Remove the observer.
2004 2118
        """
2005 2119
        log.removeObserver(self.c.append)
2006 2120
2007 -
    def _loggedErrors(self):
2121 +
    def _loggedErrors(self) -> List[Dict[str, Any]]:
2008 2122
        return [e for e in self.c if e["isError"]]
2009 2123
2010 -
    def _check(self):
2124 +
    def _check(self) -> None:
2011 2125
        """
2012 2126
        Check the output of the log observer to see if the error is present.
2013 2127
        """
@@ -2016,23 +2130,23 @@
Loading
2016 2130
        c2[1]["failure"].trap(ZeroDivisionError)
2017 2131
        self.flushLoggedErrors(ZeroDivisionError)
2018 2132
2019 -
    def test_errorLog(self):
2133 +
    def test_errorLog(self) -> None:
2020 2134
        """
2021 2135
        Verify that when a L{Deferred} with no references to it is fired,
2022 2136
        and its final result (the one not handled by any callback) is an
2023 2137
        exception, that exception will be logged immediately.
2024 2138
        """
2025 -
        defer.Deferred().addCallback(lambda x: 1 // 0).callback(1)
2139 +
        Deferred().addCallback(lambda x: 1 // 0).callback(1)
2026 2140
        gc.collect()
2027 2141
        self._check()
2028 2142
2029 -
    def test_errorLogWithInnerFrameRef(self):
2143 +
    def test_errorLogWithInnerFrameRef(self) -> None:
2030 2144
        """
2031 2145
        Same as L{test_errorLog}, but with an inner frame.
2032 2146
        """
2033 2147
2034 -
        def _subErrorLogWithInnerFrameRef():
2035 -
            d = defer.Deferred()
2148 +
        def _subErrorLogWithInnerFrameRef() -> None:
2149 +
            d: Deferred[int] = Deferred()
2036 2150
            d.addCallback(lambda x: 1 // 0)
2037 2151
            d.callback(1)
2038 2152
@@ -2040,48 +2154,50 @@
Loading
2040 2154
        gc.collect()
2041 2155
        self._check()
2042 2156
2043 -
    def test_errorLogWithInnerFrameCycle(self):
2157 +
    def test_errorLogWithInnerFrameCycle(self) -> None:
2044 2158
        """
2045 2159
        Same as L{test_errorLogWithInnerFrameRef}, plus create a cycle.
2046 2160
        """
2047 2161
2048 -
        def _subErrorLogWithInnerFrameCycle():
2049 -
            d = defer.Deferred()
2162 +
        def _subErrorLogWithInnerFrameCycle() -> None:
2163 +
            d: Deferred[int] = Deferred()
2050 2164
            d.addCallback(lambda x, d=d: 1 // 0)
2051 -
            d._d = d
2165 +
            # Set a self deference on to create a cycle
2166 +
            d._d = d  # type: ignore[attr-defined]
2052 2167
            d.callback(1)
2053 2168
2054 2169
        _subErrorLogWithInnerFrameCycle()
2055 2170
        gc.collect()
2056 2171
        self._check()
2057 2172
2058 -
    def test_errorLogNoRepr(self):
2173 +
    def test_errorLogNoRepr(self) -> None:
2059 2174
        """
2060 2175
        Verify that when a L{Deferred} with no references to it is fired,
2061 2176
        the logged message does not contain a repr of the failure object.
2062 2177
        """
2063 -
        defer.Deferred().addCallback(lambda x: 1 // 0).callback(1)
2178 +
        Deferred().addCallback(lambda x: 1 // 0).callback(1)
2064 2179
2065 2180
        gc.collect()
2066 2181
        self._check()
2067 2182
2068 2183
        self.assertEqual(2, len(self.c))
2069 2184
        msg = log.textFromEventDict(self.c[-1])
2185 +
        assert msg is not None
2070 2186
        expected = "Unhandled Error\nTraceback "
2071 2187
        self.assertTrue(
2072 2188
            msg.startswith(expected),
2073 2189
            f"Expected message starting with: {expected!r}",
2074 2190
        )
2075 2191
2076 -
    def test_errorLogDebugInfo(self):
2192 +
    def test_errorLogDebugInfo(self) -> None:
2077 2193
        """
2078 2194
        Verify that when a L{Deferred} with no references to it is fired,
2079 2195
        the logged message includes debug info if debugging on the deferred
2080 2196
        is enabled.
2081 2197
        """
2082 2198
2083 -
        def doit():
2084 -
            d = defer.Deferred()
2199 +
        def doit() -> None:
2200 +
            d: Deferred[int] = Deferred()
2085 2201
            d.debug = True
2086 2202
            d.addCallback(lambda x: 1 // 0)
2087 2203
            d.callback(1)
@@ -2092,26 +2208,27 @@
Loading
2092 2208
2093 2209
        self.assertEqual(2, len(self.c))
2094 2210
        msg = log.textFromEventDict(self.c[-1])
2211 +
        assert msg is not None
2095 2212
        expected = "(debug:  I"
2096 2213
        self.assertTrue(
2097 2214
            msg.startswith(expected),
2098 2215
            f"Expected message starting with: {expected!r}",
2099 2216
        )
2100 2217
2101 -
    def test_chainedErrorCleanup(self):
2218 +
    def test_chainedErrorCleanup(self) -> None:
2102 2219
        """
2103 2220
        If one Deferred with an error result is returned from a callback on
2104 2221
        another Deferred, when the first Deferred is garbage collected it does
2105 2222
        not log its error.
2106 2223
        """
2107 -
        d = defer.Deferred()
2224 +
        d: Deferred[None] = Deferred()
2108 2225
        d.addCallback(lambda ign: defer.fail(RuntimeError("zoop")))
2109 2226
        d.callback(None)
2110 2227
2111 2228
        # Sanity check - this isn't too interesting, but we do want the original
2112 2229
        # Deferred to have gotten the failure.
2113 -
        results = []
2114 -
        errors = []
2230 +
        results: List[None] = []
2231 +
        errors: List[Failure] = []
2115 2232
        d.addCallbacks(results.append, errors.append)
2116 2233
        self.assertEqual(results, [])
2117 2234
        self.assertEqual(len(errors), 1)
@@ -2126,16 +2243,17 @@
Loading
2126 2243
        # And make sure it is not.
2127 2244
        self.assertEqual(self._loggedErrors(), [])
2128 2245
2129 -
    def test_errorClearedByChaining(self):
2246 +
    def test_errorClearedByChaining(self) -> None:
2130 2247
        """
2131 2248
        If a Deferred with a failure result has an errback which chains it to
2132 2249
        another Deferred, the initial failure is cleared by the errback so it is
2133 2250
        not logged.
2134 2251
        """
2135 2252
        # Start off with a Deferred with a failure for a result
2136 -
        bad = defer.fail(Exception("oh no"))
2137 -
        good = defer.Deferred()
2253 +
        bad: Optional[Deferred[None]] = defer.fail(Exception("oh no"))
2254 +
        good: Optional[Deferred[None]] = Deferred()
2138 2255
        # Give it a callback that chains it to another Deferred
2256 +
        assert bad is not None
2139 2257
        bad.addErrback(lambda ignored: good)
2140 2258
        # That's all, clean it up.  No Deferred here still has a failure result,
2141 2259
        # so nothing should be logged.
@@ -2145,31 +2263,31 @@
Loading
2145 2263
2146 2264
2147 2265
class DeferredListEmptyTests(unittest.SynchronousTestCase):
2148 -
    def setUp(self):
2266 +
    def setUp(self) -> None:
2149 2267
        self.callbackRan = 0
2150 2268
2151 -
    def testDeferredListEmpty(self):
2269 +
    def testDeferredListEmpty(self) -> None:
2152 2270
        """Testing empty DeferredList."""
2153 -
        dl = defer.DeferredList([])
2271 +
        dl = DeferredList([])
2154 2272
        dl.addCallback(self.cb_empty)
2155 2273
2156 -
    def cb_empty(self, res):
2274 +
    def cb_empty(self, res: List[object]) -> None:
2157 2275
        self.callbackRan = 1
2158 2276
        self.assertEqual([], res)
2159 2277
2160 -
    def tearDown(self):
2278 +
    def tearDown(self) -> None:
2161 2279
        self.assertTrue(self.callbackRan, "Callback was never run.")
2162 2280
2163 2281
2164 2282
class OtherPrimitivesTests(unittest.SynchronousTestCase, ImmediateFailureMixin):
2165 -
    def _incr(self, result):
2283 +
    def _incr(self, result: object) -> None:
2166 2284
        self.counter += 1
2167 2285
2168 -
    def setUp(self):
2286 +
    def setUp(self) -> None:
2169 2287
        self.counter = 0
2170 2288
2171 -
    def testLock(self):
2172 -
        lock = defer.DeferredLock()
2289 +
    def testLock(self) -> None:
2290 +
        lock = DeferredLock()
2173 2291
        lock.acquire().addCallback(self._incr)
2174 2292
        self.assertTrue(lock.locked)
2175 2293
        self.assertEqual(self.counter, 1)
@@ -2191,77 +2309,86 @@
Loading
2191 2309
        firstUnique = object()
2192 2310
        secondUnique = object()
2193 2311
2194 -
        controlDeferred = defer.Deferred()
2312 +
        controlDeferred: Deferred[object] = Deferred()
2195 2313
2196 -
        def helper(self, b):
2197 -
            self.b = b
2198 -
            return controlDeferred
2314 +
        result: Optional[object] = None
2315 +
2316 +
        def helper(resultValue: object, returnValue: object = None) -> object:
2317 +
            nonlocal result
2318 +
            result = resultValue
2319 +
            return returnValue
2199 2320
2200 -
        resultDeferred = lock.run(helper, self=self, b=firstUnique)
2321 +
        resultDeferred = lock.run(
2322 +
            helper, resultValue=firstUnique, returnValue=controlDeferred
2323 +
        )
2201 2324
        self.assertTrue(lock.locked)
2202 -
        self.assertEqual(self.b, firstUnique)
2325 +
        self.assertEqual(result, firstUnique)
2203 2326
2204 -
        resultDeferred.addCallback(lambda x: setattr(self, "result", x))
2327 +
        resultDeferred.addCallback(helper)
2205 2328
2206 2329
        lock.acquire().addCallback(self._incr)
2207 2330
        self.assertTrue(lock.locked)
2208 2331
        self.assertEqual(self.counter, 2)
2209 2332
2210 2333
        controlDeferred.callback(secondUnique)
2211 -
        self.assertEqual(self.result, secondUnique)
2334 +
        self.assertEqual(result, secondUnique)
2212 2335
        self.assertTrue(lock.locked)
2213 2336
        self.assertEqual(self.counter, 3)
2214 2337
2215 -
        d = lock.acquire().addBoth(lambda x: setattr(self, "result", x))
2338 +
        d = lock.acquire().addBoth(helper)
2216 2339
        d.cancel()
2217 -
        self.assertEqual(self.result.type, defer.CancelledError)
2340 +
        self.assertIsInstance(result, Failure)
2341 +
        self.assertEqual(cast(Failure, result).type, defer.CancelledError)
2218 2342
2219 2343
        lock.release()
2220 2344
        self.assertFalse(lock.locked)
2221 2345
2222 -
    def test_cancelLockAfterAcquired(self):
2346 +
    def test_cancelLockAfterAcquired(self) -> None:
2223 2347
        """
2224 2348
        When canceling a L{Deferred} from a L{DeferredLock} that already
2225 2349
        has the lock, the cancel should have no effect.
2226 2350
        """
2227 2351
2228 -
        def _failOnErrback(_):
2352 +
        def failOnErrback(f: Failure) -> None:
2229 2353
            self.fail("Unexpected errback call!")
2230 2354
2231 -
        lock = defer.DeferredLock()
2355 +
        lock = DeferredLock()
2232 2356
        d = lock.acquire()
2233 -
        d.addErrback(_failOnErrback)
2357 +
        d.addErrback(failOnErrback)
2234 2358
        d.cancel()
2235 2359
2236 -
    def test_cancelLockBeforeAcquired(self):
2360 +
    def test_cancelLockBeforeAcquired(self) -> None:
2237 2361
        """
2238 2362
        When canceling a L{Deferred} from a L{DeferredLock} that does not
2239 2363
        yet have the lock (i.e., the L{Deferred} has not fired), the cancel
2240 2364
        should cause a L{defer.CancelledError} failure.
2241 2365
        """
2242 -
        lock = defer.DeferredLock()
2366 +
        lock = DeferredLock()
2243 2367
        lock.acquire()
2244 2368
        d = lock.acquire()
2245 2369
        d.cancel()
2246 2370
        self.assertImmediateFailure(d, defer.CancelledError)
2247 2371
2248 -
    def testSemaphore(self):
2372 +
    def testSemaphore(self) -> None:
2249 2373
        N = 13
2250 -
        sem = defer.DeferredSemaphore(N)
2374 +
        sem = DeferredSemaphore(N)
2375 +
2376 +
        controlDeferred: Deferred[None] = Deferred()
2251 2377
2252 -
        controlDeferred = defer.Deferred()
2378 +
        helperArg: object = None
2253 2379
2254 -
        def helper(self, arg):
2255 -
            self.arg = arg
2380 +
        def helper(arg: object) -> Deferred[None]:
2381 +
            nonlocal helperArg
2382 +
            helperArg = arg
2256 2383
            return controlDeferred
2257 2384
2258 -
        results = []
2385 +
        results: List[object] = []
2259 2386
        uniqueObject = object()
2260 -
        resultDeferred = sem.run(helper, self=self, arg=uniqueObject)
2387 +
        resultDeferred = sem.run(helper, arg=uniqueObject)
2261 2388
        resultDeferred.addCallback(results.append)
2262 2389
        resultDeferred.addCallback(self._incr)
2263 2390
        self.assertEqual(results, [])
2264 -
        self.assertEqual(self.arg, uniqueObject)
2391 +
        self.assertEqual(helperArg, uniqueObject)
2265 2392
        controlDeferred.callback(None)
2266 2393
        self.assertIsNone(results.pop())
2267 2394
        self.assertEqual(self.counter, 1)
@@ -2273,10 +2400,10 @@
Loading
2273 2400
2274 2401
        success = []
2275 2402
2276 -
        def fail(r):
2403 +
        def fail(r: object) -> None:
2277 2404
            success.append(False)
2278 2405
2279 -
        def succeed(r):
2406 +
        def succeed(r: object) -> None:
2280 2407
            success.append(True)
2281 2408
2282 2409
        d = sem.acquire().addCallbacks(fail, succeed)
@@ -2293,45 +2420,45 @@
Loading
2293 2420
            sem.release()
2294 2421
            self.assertEqual(self.counter, N + 1)
2295 2422
2296 -
    def test_semaphoreInvalidTokens(self):
2423 +
    def test_semaphoreInvalidTokens(self) -> None:
2297 2424
        """
2298 2425
        If the token count passed to L{DeferredSemaphore} is less than one
2299 2426
        then L{ValueError} is raised.
2300 2427
        """
2301 -
        self.assertRaises(ValueError, defer.DeferredSemaphore, 0)
2302 -
        self.assertRaises(ValueError, defer.DeferredSemaphore, -1)
2428 +
        self.assertRaises(ValueError, DeferredSemaphore, 0)
2429 +
        self.assertRaises(ValueError, DeferredSemaphore, -1)
2303 2430
2304 -
    def test_cancelSemaphoreAfterAcquired(self):
2431 +
    def test_cancelSemaphoreAfterAcquired(self) -> None:
2305 2432
        """
2306 2433
        When canceling a L{Deferred} from a L{DeferredSemaphore} that
2307 2434
        already has the semaphore, the cancel should have no effect.
2308 2435
        """
2309 2436
2310 -
        def _failOnErrback(_):
2437 +
        def failOnErrback(f: Failure) -> None:
2311 2438
            self.fail("Unexpected errback call!")
2312 2439
2313 -
        sem = defer.DeferredSemaphore(1)
2440 +
        sem = DeferredSemaphore(1)
2314 2441
        d = sem.acquire()
2315 -
        d.addErrback(_failOnErrback)
2442 +
        d.addErrback(failOnErrback)
2316 2443
        d.cancel()
2317 2444
2318 -
    def test_cancelSemaphoreBeforeAcquired(self):
2445 +
    def test_cancelSemaphoreBeforeAcquired(self) -> None:
2319 2446
        """
2320 2447
        When canceling a L{Deferred} from a L{DeferredSemaphore} that does
2321 2448
        not yet have the semaphore (i.e., the L{Deferred} has not fired),
2322 2449
        the cancel should cause a L{defer.CancelledError} failure.
2323 2450
        """
2324 -
        sem = defer.DeferredSemaphore(1)
2451 +
        sem = DeferredSemaphore(1)
2325 2452
        sem.acquire()
2326 2453
        d = sem.acquire()
2327 2454
        d.cancel()
2328 2455
        self.assertImmediateFailure(d, defer.CancelledError)
2329 2456
2330 -
    def testQueue(self):
2457 +
    def testQueue(self) -> None:
2331 2458
        N, M = 2, 2
2332 -
        queue = defer.DeferredQueue(N, M)
2459 +
        queue: DeferredQueue[int] = DeferredQueue(N, M)
2333 2460
2334 -
        gotten = []
2461 +
        gotten: List[int] = []
2335 2462
2336 2463
        for i in range(M):
2337 2464
            queue.get().addCallback(gotten.append)
@@ -2350,7 +2477,7 @@
Loading
2350 2477
            queue.get().addCallback(gotten.append)
2351 2478
            self.assertEqual(gotten, list(range(N, N + i + 1)))
2352 2479
2353 -
        queue = defer.DeferredQueue()
2480 +
        queue = DeferredQueue()
2354 2481
        gotten = []
2355 2482
        for i in range(N):
2356 2483
            queue.get().addCallback(gotten.append)
@@ -2358,47 +2485,47 @@
Loading
2358 2485
            queue.put(i)
2359 2486
        self.assertEqual(gotten, list(range(N)))
2360 2487
2361 -
        queue = defer.DeferredQueue(size=0)
2488 +
        queue = DeferredQueue(size=0)
2362 2489
        self.assertRaises(defer.QueueOverflow, queue.put, None)
2363 2490
2364 -
        queue = defer.DeferredQueue(backlog=0)
2491 +
        queue = DeferredQueue(backlog=0)
2365 2492
        self.assertRaises(defer.QueueUnderflow, queue.get)
2366 2493
2367 -
    def test_cancelQueueAfterSynchronousGet(self):
2494 +
    def test_cancelQueueAfterSynchronousGet(self) -> None:
2368 2495
        """
2369 2496
        When canceling a L{Deferred} from a L{DeferredQueue} that already has
2370 2497
        a result, the cancel should have no effect.
2371 2498
        """
2372 2499
2373 -
        def _failOnErrback(_):
2500 +
        def failOnErrback(f: Failure) -> None:
2374 2501
            self.fail("Unexpected errback call!")
2375 2502
2376 -
        queue = defer.DeferredQueue()
2503 +
        queue: DeferredQueue[None] = DeferredQueue()
2377 2504
        d = queue.get()
2378 -
        d.addErrback(_failOnErrback)
2505 +
        d.addErrback(failOnErrback)
2379 2506
        queue.put(None)
2380 2507
        d.cancel()
2381 2508
2382 -
    def test_cancelQueueAfterGet(self):
2509 +
    def test_cancelQueueAfterGet(self) -> None:
2383 2510
        """
2384 2511
        When canceling a L{Deferred} from a L{DeferredQueue} that does not
2385 2512
        have a result (i.e., the L{Deferred} has not fired), the cancel
2386 2513
        causes a L{defer.CancelledError} failure. If the queue has a result
2387 2514
        later on, it doesn't try to fire the deferred.
2388 2515
        """
2389 -
        queue = defer.DeferredQueue()
2516 +
        queue: DeferredQueue[None] = DeferredQueue()
2390 2517
        d = queue.get()
2391 2518
        d.cancel()
2392 2519
        self.assertImmediateFailure(d, defer.CancelledError)
2393 2520
2394 -
        def cb(ignore):
2521 +
        def cb(ignore: object) -> Deferred[None]:
2395 2522
            # If the deferred is still linked with the deferred queue, it will
2396 2523
            # fail with an AlreadyCalledError
2397 2524
            queue.put(None)
2398 2525
            return queue.get().addCallback(self.assertIs, None)
2399 2526
2400 2527
        d.addCallback(cb)
2401 -
        done = []
2528 +
        done: List[None] = []
2402 2529
        d.addCallback(done.append)
2403 2530
        self.assertEqual(len(done), 1)
2404 2531
@@ -2408,19 +2535,17 @@
Loading
2408 2535
    Test the behavior of L{DeferredFilesystemLock}
2409 2536
    """
2410 2537
2411 -
    def setUp(self):
2538 +
    def setUp(self) -> None:
2412 2539
        self.clock = Clock()
2413 -
        self.lock = defer.DeferredFilesystemLock(self.mktemp(), scheduler=self.clock)
2540 +
        self.lock = DeferredFilesystemLock(self.mktemp(), scheduler=self.clock)
2414 2541
2415 -
    def test_waitUntilLockedWithNoLock(self):
2542 +
    def test_waitUntilLockedWithNoLock(self) -> Deferred[None]:
2416 2543
        """
2417 2544
        Test that the lock can be acquired when no lock is held
2418 2545
        """
2419 -
        d = self.lock.deferUntilLocked(timeout=1)
2420 -
2421 -
        return d
2546 +
        return self.lock.deferUntilLocked(timeout=1)
2422 2547
2423 -
    def test_waitUntilLockedWithTimeoutLocked(self):
2548 +
    def test_waitUntilLockedWithTimeoutLocked(self) -> Deferred[None]:
2424 2549
        """
2425 2550
        Test that the lock can not be acquired when the lock is held
2426 2551
        for longer than the timeout.
@@ -2434,13 +2559,13 @@
Loading
2434 2559
2435 2560
        return d
2436 2561
2437 -
    def test_waitUntilLockedWithTimeoutUnlocked(self):
2562 +
    def test_waitUntilLockedWithTimeoutUnlocked(self) -> Deferred[None]:
2438 2563
        """
2439 2564
        Test that a lock can be acquired while a lock is held
2440 2565
        but the lock is unlocked before our timeout.
2441 2566
        """
2442 2567
2443 -
        def onTimeout(f):
2568 +
        def onTimeout(f: Failure) -> None:
2444 2569
            f.trap(defer.TimeoutError)
2445 2570
            self.fail("Should not have timed out")
2446 2571
@@ -2454,15 +2579,15 @@
Loading
2454 2579
2455 2580
        return d
2456 2581
2457 -
    def test_defaultScheduler(self):
2582 +
    def test_defaultScheduler(self) -> None:
2458 2583
        """
2459 2584
        Test that the default scheduler is set up properly.
2460 2585
        """
2461 -
        lock = defer.DeferredFilesystemLock(self.mktemp())
2586 +
        lock = DeferredFilesystemLock(self.mktemp())
2462 2587
2463 2588
        self.assertEqual(lock._scheduler, reactor)
2464 2589
2465 -
    def test_concurrentUsage(self):
2590 +
    def test_concurrentUsage(self) -> Deferred[None]:
2466 2591
        """
2467 2592
        Test that an appropriate exception is raised when attempting
2468 2593
        to use deferUntilLocked concurrently.
@@ -2470,21 +2595,21 @@
Loading
2470 2595
        self.lock.lock()
2471 2596
        self.clock.callLater(1, self.lock.unlock)
2472 2597
2473 -
        d = self.lock.deferUntilLocked()
2598 +
        d1 = self.lock.deferUntilLocked()
2474 2599
        d2 = self.lock.deferUntilLocked()
2475 2600
2476 2601
        self.assertFailure(d2, defer.AlreadyTryingToLockError)
2477 2602
2478 2603
        self.clock.advance(1)
2479 2604
2480 -
        return d
2605 +
        return d1
2481 2606
2482 -
    def test_multipleUsages(self):
2607 +
    def test_multipleUsages(self) -> Deferred[None]:
2483 2608
        """
2484 2609
        Test that a DeferredFilesystemLock can be used multiple times
2485 2610
        """
2486 2611
2487 -
        def lockAquired(ign):
2612 +
        def lockAquired(ign: object) -> Deferred[None]:
2488 2613
            self.lock.unlock()
2489 2614
            d = self.lock.deferUntilLocked()
2490 2615
            return d
@@ -2499,36 +2624,38 @@
Loading
2499 2624
2500 2625
        return d
2501 2626
2502 -
    def test_cancelDeferUntilLocked(self):
2627 +
    def test_cancelDeferUntilLocked(self) -> None:
2503 2628
        """
2504 -
        When cancelling a L{defer.Deferred} returned by
2505 -
        L{defer.DeferredFilesystemLock.deferUntilLocked}, the
2506 -
        L{defer.DeferredFilesystemLock._tryLockCall} is cancelled.
2629 +
        When cancelling a L{Deferred} returned by
2630 +
        L{DeferredFilesystemLock.deferUntilLocked}, the
2631 +
        L{DeferredFilesystemLock._tryLockCall} is cancelled.
2507 2632
        """
2508 2633
        self.lock.lock()
2509 2634
        deferred = self.lock.deferUntilLocked()
2510 2635
        tryLockCall = self.lock._tryLockCall
2636 +
        assert tryLockCall is not None
2511 2637
        deferred.cancel()
2512 2638
        self.assertFalse(tryLockCall.active())
2513 2639
        self.assertIsNone(self.lock._tryLockCall)
2514 2640
        self.failureResultOf(deferred, defer.CancelledError)
2515 2641
2516 -
    def test_cancelDeferUntilLockedWithTimeout(self):
2642 +
    def test_cancelDeferUntilLockedWithTimeout(self) -> None:
2517 2643
        """
2518 -
        When cancel a L{defer.Deferred} returned by
2519 -
        L{defer.DeferredFilesystemLock.deferUntilLocked}, if the timeout is
2644 +
        When cancel a L{Deferred} returned by
2645 +
        L{DeferredFilesystemLock.deferUntilLocked}, if the timeout is
2520 2646
        set, the timeout call will be cancelled.
2521 2647
        """
2522 2648
        self.lock.lock()
2523 2649
        deferred = self.lock.deferUntilLocked(timeout=1)
2524 2650
        timeoutCall = self.lock._timeoutCall
2651 +
        assert timeoutCall is not None
2525 2652
        deferred.cancel()
2526 2653
        self.assertFalse(timeoutCall.active())
2527 2654
        self.assertIsNone(self.lock._timeoutCall)
2528 2655
        self.failureResultOf(deferred, defer.CancelledError)
2529 2656
2530 2657
2531 -
def _overrideFunc(v, t):
2658 +
def _overrideFunc(v: object, t: float) -> str:
2532 2659
    """
2533 2660
    Private function to be used to pass as an alternate onTimeoutCancel value
2534 2661
    to timeoutDeferred
@@ -2541,32 +2668,35 @@
Loading
2541 2668
    Tests for the function L{Deferred.addTimeout}
2542 2669
    """
2543 2670
2544 -
    def test_timeoutChainable(self):
2671 +
    def test_timeoutChainable(self) -> None:
2545 2672
        """
2546 -
        L{defer.Deferred.addTimeout} returns its own L{defer.Deferred} so it
2673 +
        L{Deferred.addTimeout} returns its own L{Deferred} so it
2547 2674
        can be called in a callback chain.
2548 2675
        """
2549 -
        d = defer.Deferred().addTimeout(5, Clock()).addCallback(lambda _: "done")
2676 +
        d: Deferred[None] = Deferred()
2677 +
        d.addTimeout(5, Clock())
2678 +
        d.addCallback(lambda _: "done")
2550 2679
        d.callback(None)
2551 2680
        self.assertEqual("done", self.successResultOf(d))
2552 2681
2553 -
    def test_successResultBeforeTimeout(self):
2682 +
    def test_successResultBeforeTimeout(self) -> None:
2554 2683
        """
2555 -
        The L{defer.Deferred} callbacks with the result if it succeeds before
2684 +
        The L{Deferred} callbacks with the result if it succeeds before
2556 2685
        the timeout. No cancellation happens after the callback either,
2557 2686
        which could also cancel inner deferreds.
2558 2687
        """
2559 2688
        clock = Clock()
2560 -
        d = defer.Deferred()
2689 +
        d: Deferred[str] = Deferred()
2561 2690
        d.addTimeout(10, clock)
2562 2691
2563 2692
        # addTimeout is added first so that if d is timed out, d would be
2564 2693
        # canceled before innerDeferred gets returned from an callback on d
2565 -
        innerDeferred = defer.Deferred()
2566 -
        dCallbacked = [None]
2694 +
        innerDeferred: Deferred[None] = Deferred()
2695 +
        dCallbacked: Optional[str] = None
2567 2696
2568 -
        def onCallback(results):
2569 -
            dCallbacked[0] = results
2697 +
        def onCallback(results: str) -> Deferred[None]:
2698 +
            nonlocal dCallbacked
2699 +
            dCallbacked = results
2570 2700
            return innerDeferred
2571 2701
2572 2702
        d.addCallback(onCallback)
@@ -2574,32 +2704,33 @@
Loading
2574 2704
2575 2705
        # d is callbacked immediately, before innerDeferred is returned from
2576 2706
        # the callback on d
2577 -
        self.assertIsNot(None, dCallbacked[0])
2578 -
        self.assertEqual(dCallbacked[0], "results")
2707 +
        self.assertIsNot(None, dCallbacked)
2708 +
        self.assertEqual(dCallbacked, "results")
2579 2709
2580 2710
        # The timeout never happens - if it did, d would have been cancelled,
2581 2711
        # which would cancel innerDeferred too.
2582 2712
        clock.advance(15)
2583 2713
        self.assertNoResult(innerDeferred)
2584 2714
2585 -
    def test_successResultBeforeTimeoutCustom(self):
2715 +
    def test_successResultBeforeTimeoutCustom(self) -> None:
2586 2716
        """
2587 -
        The L{defer.Deferred} callbacks with the result if it succeeds before
2717 +
        The L{Deferred} callbacks with the result if it succeeds before
2588 2718
        the timeout, even if a custom C{onTimeoutCancel} function is provided.
2589 2719
        No cancellation happens after the callback either, which could also
2590 2720
        cancel inner deferreds.
2591 2721
        """
2592 2722
        clock = Clock()
2593 -
        d = defer.Deferred()
2723 +
        d: Deferred[str] = Deferred()
2594 2724
        d.addTimeout(10, clock, onTimeoutCancel=_overrideFunc)
2595 2725
2596 2726
        # addTimeout is added first so that if d is timed out, d would be
2597 2727
        # canceled before innerDeferred gets returned from an callback on d
2598 -
        innerDeferred = defer.Deferred()
2599 -
        dCallbacked = [None]
2728 +
        innerDeferred: Deferred[None] = Deferred()
2729 +
        dCallbacked: Optional[str] = None
2600 2730
2601 -
        def onCallback(results):
2602 -
            dCallbacked[0] = results
2731 +
        def onCallback(results: str) -> Deferred[None]:
2732 +
            nonlocal dCallbacked
2733 +
            dCallbacked = results
2603 2734
            return innerDeferred
2604 2735
2605 2736
        d.addCallback(onCallback)
@@ -2607,32 +2738,33 @@
Loading
2607 2738
2608 2739
        # d is callbacked immediately, before innerDeferred is returned from
2609 2740
        # the callback on d
2610 -
        self.assertIsNot(None, dCallbacked[0])
2611 -
        self.assertEqual(dCallbacked[0], "results")
2741 +
        self.assertIsNot(None, dCallbacked)
2742 +
        self.assertEqual(dCallbacked, "results")
2612 2743
2613 2744
        # The timeout never happens - if it did, d would have been cancelled,
2614 2745
        # which would cancel innerDeferred too
2615 2746
        clock.advance(15)
2616 2747
        self.assertNoResult(innerDeferred)
2617 2748
2618 -
    def test_failureBeforeTimeout(self):
2749 +
    def test_failureBeforeTimeout(self) -> None:
2619 2750
        """
2620 -
        The L{defer.Deferred} errbacks with the failure if it fails before the
2751 +
        The L{Deferred} errbacks with the failure if it fails before the
2621 2752
        timeout. No cancellation happens after the errback either, which
2622 2753
        could also cancel inner deferreds.
2623 2754
        """
2624 2755
        clock = Clock()
2625 -
        d = defer.Deferred()
2756 +
        d: Deferred[None] = Deferred()
2626 2757
        d.addTimeout(10, clock)
2627 2758
2628 2759
        # addTimeout is added first so that if d is timed out, d would be
2629 2760
        # canceled before innerDeferred gets returned from an errback on d
2630 -
        innerDeferred = defer.Deferred()
2631 -
        dErrbacked = [None]
2761 +
        innerDeferred: Deferred[None] = Deferred()
2762 +
        dErrbacked: Optional[Failure] = None
2632 2763
        error = ValueError("fail")
2633 2764
2634 -
        def onErrback(f):
2635 -
            dErrbacked[0] = f
2765 +
        def onErrback(f: Failure) -> Deferred[None]:
2766 +
            nonlocal dErrbacked
2767 +
            dErrbacked = f
2636 2768
            return innerDeferred
2637 2769
2638 2770
        d.addErrback(onErrback)
@@ -2640,33 +2772,35 @@
Loading
2640 2772
2641 2773
        # d is errbacked immediately, before innerDeferred is returned from the
2642 2774
        # errback on d
2643 -
        self.assertIsInstance(dErrbacked[0], failure.Failure)
2644 -
        self.assertIs(dErrbacked[0].value, error)
2775 +
        assert dErrbacked is not None
2776 +
        self.assertIsInstance(dErrbacked, Failure)
2777 +
        self.assertIs(dErrbacked.value, error)
2645 2778
2646 2779
        # The timeout never happens - if it did, d would have been cancelled,
2647 2780
        # which would cancel innerDeferred too
2648 2781
        clock.advance(15)
2649 2782
        self.assertNoResult(innerDeferred)
2650 2783
2651 -
    def test_failureBeforeTimeoutCustom(self):
2784 +
    def test_failureBeforeTimeoutCustom(self) -> None:
2652 2785
        """
2653 -
        The L{defer.Deferred} errbacks with the failure if it fails before the
2786 +
        The L{Deferred} errbacks with the failure if it fails before the
2654 2787
        timeout, even if using a custom C{onTimeoutCancel} function.
2655 2788
        No cancellation happens after the errback either, which could also
2656 2789
        cancel inner deferreds.
2657 2790
        """
2658 2791
        clock = Clock()
2659 -
        d = defer.Deferred()
2792 +
        d: Deferred[None] = Deferred()
2660 2793
        d.addTimeout(10, clock, onTimeoutCancel=_overrideFunc)
2661 2794
2662 2795
        # addTimeout is added first so that if d is timed out, d would be
2663 2796
        # canceled before innerDeferred gets returned from an errback on d
2664 -
        innerDeferred = defer.Deferred()
2665 -
        dErrbacked = [None]
2797 +
        innerDeferred: Deferred[None] = Deferred()
2798 +
        dErrbacked: Optional[Failure] = None
2666 2799
        error = ValueError("fail")
2667 2800
2668 -
        def onErrback(f):
2669 -
            dErrbacked[0] = f
2801 +
        def onErrback(f: Failure) -> Deferred[None]:
2802 +
            nonlocal dErrbacked
2803 +
            dErrbacked = f
2670 2804
            return innerDeferred
2671 2805
2672 2806
        d.addErrback(onErrback)
@@ -2674,21 +2808,22 @@
Loading
2674 2808
2675 2809
        # d is errbacked immediately, before innerDeferred is returned from the
2676 2810
        # errback on d
2677 -
        self.assertIsInstance(dErrbacked[0], failure.Failure)
2678 -
        self.assertIs(dErrbacked[0].value, error)
2811 +
        assert dErrbacked is not None
2812 +
        self.assertIsInstance(dErrbacked, Failure)
2813 +
        self.assertIs(dErrbacked.value, error)
2679 2814
2680 2815
        # The timeout never happens - if it did, d would have been cancelled,
2681 2816
        # which would cancel innerDeferred too
2682 2817
        clock.advance(15)
2683 2818
        self.assertNoResult(innerDeferred)
2684 2819
2685 -
    def test_timedOut(self):
2820 +
    def test_timedOut(self) -> None:
2686 2821
        """
2687 -
        The L{defer.Deferred} by default errbacks with a L{defer.TimeoutError}
2822 +
        The L{Deferred} by default errbacks with a L{defer.TimeoutError}
2688 2823
        if it times out before callbacking or errbacking.
2689 2824
        """
2690 2825
        clock = Clock()
2691 -
        d = defer.Deferred()
2826 +
        d: Deferred[None] = Deferred()
2692 2827
        d.addTimeout(10, clock)
2693 2828
        self.assertNoResult(d)
2694 2829
@@ -2696,16 +2831,16 @@
Loading
2696 2831
2697 2832
        self.failureResultOf(d, defer.TimeoutError)
2698 2833
2699 -
    def test_timedOutCustom(self):
2834 +
    def test_timedOutCustom(self) -> None:
2700 2835
        """
2701 2836
        If a custom C{onTimeoutCancel] function is provided, the
2702 -
        L{defer.Deferred} returns the custom function's return value if the
2703 -
        L{defer.Deferred} times out before callbacking or errbacking.
2837 +
        L{Deferred} returns the custom function's return value if the
2838 +
        L{Deferred} times out before callbacking or errbacking.
2704 2839
        The custom C{onTimeoutCancel} function can return a result instead of
2705 2840
        a failure.
2706 2841
        """
2707 2842
        clock = Clock()
2708 -
        d = defer.Deferred()
2843 +
        d: Deferred[None] = Deferred()
2709 2844
        d.addTimeout(10, clock, onTimeoutCancel=_overrideFunc)
2710 2845
        self.assertNoResult(d)
2711 2846
@@ -2713,14 +2848,14 @@
Loading
<
2713 2848
2714 2849
        self.assertEqual("OVERRIDDEN", self.successResultOf(d))
2715 2850
2716 -
    def test_timedOutProvidedCancelSuccess(self):
2851 +
    def test_timedOutProvidedCancelSuccess(self) -> None:
2717 2852
        """
2718 -
        If a cancellation function is provided when the L{defer.Deferred} is
2719 -
        initialized, the L{defer.Deferred} returns the cancellation value's
2720 -
        non-failure return value when the L{defer.Deferred} times out.