Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_defer.py 124KB

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