test_weakref.py 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233
  1. import gc
  2. import sys
  3. import doctest
  4. import unittest
  5. import collections
  6. import weakref
  7. import operator
  8. import contextlib
  9. import copy
  10. import threading
  11. import time
  12. import random
  13. from test import support
  14. from test.support import script_helper, ALWAYS_EQ
  15. from test.support import gc_collect
  16. from test.support import threading_helper
  17. # Used in ReferencesTestCase.test_ref_created_during_del() .
  18. ref_from_del = None
  19. # Used by FinalizeTestCase as a global that may be replaced by None
  20. # when the interpreter shuts down.
  21. _global_var = 'foobar'
  22. class C:
  23. def method(self):
  24. pass
  25. class Callable:
  26. bar = None
  27. def __call__(self, x):
  28. self.bar = x
  29. def create_function():
  30. def f(): pass
  31. return f
  32. def create_bound_method():
  33. return C().method
  34. class Object:
  35. def __init__(self, arg):
  36. self.arg = arg
  37. def __repr__(self):
  38. return "<Object %r>" % self.arg
  39. def __eq__(self, other):
  40. if isinstance(other, Object):
  41. return self.arg == other.arg
  42. return NotImplemented
  43. def __lt__(self, other):
  44. if isinstance(other, Object):
  45. return self.arg < other.arg
  46. return NotImplemented
  47. def __hash__(self):
  48. return hash(self.arg)
  49. def some_method(self):
  50. return 4
  51. def other_method(self):
  52. return 5
  53. class RefCycle:
  54. def __init__(self):
  55. self.cycle = self
  56. class TestBase(unittest.TestCase):
  57. def setUp(self):
  58. self.cbcalled = 0
  59. def callback(self, ref):
  60. self.cbcalled += 1
  61. @contextlib.contextmanager
  62. def collect_in_thread(period=0.0001):
  63. """
  64. Ensure GC collections happen in a different thread, at a high frequency.
  65. """
  66. please_stop = False
  67. def collect():
  68. while not please_stop:
  69. time.sleep(period)
  70. gc.collect()
  71. with support.disable_gc():
  72. t = threading.Thread(target=collect)
  73. t.start()
  74. try:
  75. yield
  76. finally:
  77. please_stop = True
  78. t.join()
  79. class ReferencesTestCase(TestBase):
  80. def test_basic_ref(self):
  81. self.check_basic_ref(C)
  82. self.check_basic_ref(create_function)
  83. self.check_basic_ref(create_bound_method)
  84. # Just make sure the tp_repr handler doesn't raise an exception.
  85. # Live reference:
  86. o = C()
  87. wr = weakref.ref(o)
  88. repr(wr)
  89. # Dead reference:
  90. del o
  91. repr(wr)
  92. def test_basic_callback(self):
  93. self.check_basic_callback(C)
  94. self.check_basic_callback(create_function)
  95. self.check_basic_callback(create_bound_method)
  96. @support.cpython_only
  97. def test_cfunction(self):
  98. import _testcapi
  99. create_cfunction = _testcapi.create_cfunction
  100. f = create_cfunction()
  101. wr = weakref.ref(f)
  102. self.assertIs(wr(), f)
  103. del f
  104. self.assertIsNone(wr())
  105. self.check_basic_ref(create_cfunction)
  106. self.check_basic_callback(create_cfunction)
  107. def test_multiple_callbacks(self):
  108. o = C()
  109. ref1 = weakref.ref(o, self.callback)
  110. ref2 = weakref.ref(o, self.callback)
  111. del o
  112. gc_collect() # For PyPy or other GCs.
  113. self.assertIsNone(ref1(), "expected reference to be invalidated")
  114. self.assertIsNone(ref2(), "expected reference to be invalidated")
  115. self.assertEqual(self.cbcalled, 2,
  116. "callback not called the right number of times")
  117. def test_multiple_selfref_callbacks(self):
  118. # Make sure all references are invalidated before callbacks are called
  119. #
  120. # What's important here is that we're using the first
  121. # reference in the callback invoked on the second reference
  122. # (the most recently created ref is cleaned up first). This
  123. # tests that all references to the object are invalidated
  124. # before any of the callbacks are invoked, so that we only
  125. # have one invocation of _weakref.c:cleanup_helper() active
  126. # for a particular object at a time.
  127. #
  128. def callback(object, self=self):
  129. self.ref()
  130. c = C()
  131. self.ref = weakref.ref(c, callback)
  132. ref1 = weakref.ref(c, callback)
  133. del c
  134. def test_constructor_kwargs(self):
  135. c = C()
  136. self.assertRaises(TypeError, weakref.ref, c, callback=None)
  137. def test_proxy_ref(self):
  138. o = C()
  139. o.bar = 1
  140. ref1 = weakref.proxy(o, self.callback)
  141. ref2 = weakref.proxy(o, self.callback)
  142. del o
  143. gc_collect() # For PyPy or other GCs.
  144. def check(proxy):
  145. proxy.bar
  146. self.assertRaises(ReferenceError, check, ref1)
  147. self.assertRaises(ReferenceError, check, ref2)
  148. ref3 = weakref.proxy(C())
  149. gc_collect() # For PyPy or other GCs.
  150. self.assertRaises(ReferenceError, bool, ref3)
  151. self.assertEqual(self.cbcalled, 2)
  152. def check_basic_ref(self, factory):
  153. o = factory()
  154. ref = weakref.ref(o)
  155. self.assertIsNotNone(ref(),
  156. "weak reference to live object should be live")
  157. o2 = ref()
  158. self.assertIs(o, o2,
  159. "<ref>() should return original object if live")
  160. def check_basic_callback(self, factory):
  161. self.cbcalled = 0
  162. o = factory()
  163. ref = weakref.ref(o, self.callback)
  164. del o
  165. gc_collect() # For PyPy or other GCs.
  166. self.assertEqual(self.cbcalled, 1,
  167. "callback did not properly set 'cbcalled'")
  168. self.assertIsNone(ref(),
  169. "ref2 should be dead after deleting object reference")
  170. def test_ref_reuse(self):
  171. o = C()
  172. ref1 = weakref.ref(o)
  173. # create a proxy to make sure that there's an intervening creation
  174. # between these two; it should make no difference
  175. proxy = weakref.proxy(o)
  176. ref2 = weakref.ref(o)
  177. self.assertIs(ref1, ref2,
  178. "reference object w/out callback should be re-used")
  179. o = C()
  180. proxy = weakref.proxy(o)
  181. ref1 = weakref.ref(o)
  182. ref2 = weakref.ref(o)
  183. self.assertIs(ref1, ref2,
  184. "reference object w/out callback should be re-used")
  185. self.assertEqual(weakref.getweakrefcount(o), 2,
  186. "wrong weak ref count for object")
  187. del proxy
  188. gc_collect() # For PyPy or other GCs.
  189. self.assertEqual(weakref.getweakrefcount(o), 1,
  190. "wrong weak ref count for object after deleting proxy")
  191. def test_proxy_reuse(self):
  192. o = C()
  193. proxy1 = weakref.proxy(o)
  194. ref = weakref.ref(o)
  195. proxy2 = weakref.proxy(o)
  196. self.assertIs(proxy1, proxy2,
  197. "proxy object w/out callback should have been re-used")
  198. def test_basic_proxy(self):
  199. o = C()
  200. self.check_proxy(o, weakref.proxy(o))
  201. L = collections.UserList()
  202. p = weakref.proxy(L)
  203. self.assertFalse(p, "proxy for empty UserList should be false")
  204. p.append(12)
  205. self.assertEqual(len(L), 1)
  206. self.assertTrue(p, "proxy for non-empty UserList should be true")
  207. p[:] = [2, 3]
  208. self.assertEqual(len(L), 2)
  209. self.assertEqual(len(p), 2)
  210. self.assertIn(3, p, "proxy didn't support __contains__() properly")
  211. p[1] = 5
  212. self.assertEqual(L[1], 5)
  213. self.assertEqual(p[1], 5)
  214. L2 = collections.UserList(L)
  215. p2 = weakref.proxy(L2)
  216. self.assertEqual(p, p2)
  217. ## self.assertEqual(repr(L2), repr(p2))
  218. L3 = collections.UserList(range(10))
  219. p3 = weakref.proxy(L3)
  220. self.assertEqual(L3[:], p3[:])
  221. self.assertEqual(L3[5:], p3[5:])
  222. self.assertEqual(L3[:5], p3[:5])
  223. self.assertEqual(L3[2:5], p3[2:5])
  224. def test_proxy_unicode(self):
  225. # See bug 5037
  226. class C(object):
  227. def __str__(self):
  228. return "string"
  229. def __bytes__(self):
  230. return b"bytes"
  231. instance = C()
  232. self.assertIn("__bytes__", dir(weakref.proxy(instance)))
  233. self.assertEqual(bytes(weakref.proxy(instance)), b"bytes")
  234. def test_proxy_index(self):
  235. class C:
  236. def __index__(self):
  237. return 10
  238. o = C()
  239. p = weakref.proxy(o)
  240. self.assertEqual(operator.index(p), 10)
  241. def test_proxy_div(self):
  242. class C:
  243. def __floordiv__(self, other):
  244. return 42
  245. def __ifloordiv__(self, other):
  246. return 21
  247. o = C()
  248. p = weakref.proxy(o)
  249. self.assertEqual(p // 5, 42)
  250. p //= 5
  251. self.assertEqual(p, 21)
  252. def test_proxy_matmul(self):
  253. class C:
  254. def __matmul__(self, other):
  255. return 1729
  256. def __rmatmul__(self, other):
  257. return -163
  258. def __imatmul__(self, other):
  259. return 561
  260. o = C()
  261. p = weakref.proxy(o)
  262. self.assertEqual(p @ 5, 1729)
  263. self.assertEqual(5 @ p, -163)
  264. p @= 5
  265. self.assertEqual(p, 561)
  266. # The PyWeakref_* C API is documented as allowing either NULL or
  267. # None as the value for the callback, where either means "no
  268. # callback". The "no callback" ref and proxy objects are supposed
  269. # to be shared so long as they exist by all callers so long as
  270. # they are active. In Python 2.3.3 and earlier, this guarantee
  271. # was not honored, and was broken in different ways for
  272. # PyWeakref_NewRef() and PyWeakref_NewProxy(). (Two tests.)
  273. def test_shared_ref_without_callback(self):
  274. self.check_shared_without_callback(weakref.ref)
  275. def test_shared_proxy_without_callback(self):
  276. self.check_shared_without_callback(weakref.proxy)
  277. def check_shared_without_callback(self, makeref):
  278. o = Object(1)
  279. p1 = makeref(o, None)
  280. p2 = makeref(o, None)
  281. self.assertIs(p1, p2, "both callbacks were None in the C API")
  282. del p1, p2
  283. p1 = makeref(o)
  284. p2 = makeref(o, None)
  285. self.assertIs(p1, p2, "callbacks were NULL, None in the C API")
  286. del p1, p2
  287. p1 = makeref(o)
  288. p2 = makeref(o)
  289. self.assertIs(p1, p2, "both callbacks were NULL in the C API")
  290. del p1, p2
  291. p1 = makeref(o, None)
  292. p2 = makeref(o)
  293. self.assertIs(p1, p2, "callbacks were None, NULL in the C API")
  294. def test_callable_proxy(self):
  295. o = Callable()
  296. ref1 = weakref.proxy(o)
  297. self.check_proxy(o, ref1)
  298. self.assertIs(type(ref1), weakref.CallableProxyType,
  299. "proxy is not of callable type")
  300. ref1('twinkies!')
  301. self.assertEqual(o.bar, 'twinkies!',
  302. "call through proxy not passed through to original")
  303. ref1(x='Splat.')
  304. self.assertEqual(o.bar, 'Splat.',
  305. "call through proxy not passed through to original")
  306. # expect due to too few args
  307. self.assertRaises(TypeError, ref1)
  308. # expect due to too many args
  309. self.assertRaises(TypeError, ref1, 1, 2, 3)
  310. def check_proxy(self, o, proxy):
  311. o.foo = 1
  312. self.assertEqual(proxy.foo, 1,
  313. "proxy does not reflect attribute addition")
  314. o.foo = 2
  315. self.assertEqual(proxy.foo, 2,
  316. "proxy does not reflect attribute modification")
  317. del o.foo
  318. self.assertFalse(hasattr(proxy, 'foo'),
  319. "proxy does not reflect attribute removal")
  320. proxy.foo = 1
  321. self.assertEqual(o.foo, 1,
  322. "object does not reflect attribute addition via proxy")
  323. proxy.foo = 2
  324. self.assertEqual(o.foo, 2,
  325. "object does not reflect attribute modification via proxy")
  326. del proxy.foo
  327. self.assertFalse(hasattr(o, 'foo'),
  328. "object does not reflect attribute removal via proxy")
  329. def test_proxy_deletion(self):
  330. # Test clearing of SF bug #762891
  331. class Foo:
  332. result = None
  333. def __delitem__(self, accessor):
  334. self.result = accessor
  335. g = Foo()
  336. f = weakref.proxy(g)
  337. del f[0]
  338. self.assertEqual(f.result, 0)
  339. def test_proxy_bool(self):
  340. # Test clearing of SF bug #1170766
  341. class List(list): pass
  342. lyst = List()
  343. self.assertEqual(bool(weakref.proxy(lyst)), bool(lyst))
  344. def test_proxy_iter(self):
  345. # Test fails with a debug build of the interpreter
  346. # (see bpo-38395).
  347. obj = None
  348. class MyObj:
  349. def __iter__(self):
  350. nonlocal obj
  351. del obj
  352. return NotImplemented
  353. obj = MyObj()
  354. p = weakref.proxy(obj)
  355. with self.assertRaises(TypeError):
  356. # "blech" in p calls MyObj.__iter__ through the proxy,
  357. # without keeping a reference to the real object, so it
  358. # can be killed in the middle of the call
  359. "blech" in p
  360. def test_proxy_next(self):
  361. arr = [4, 5, 6]
  362. def iterator_func():
  363. yield from arr
  364. it = iterator_func()
  365. class IteratesWeakly:
  366. def __iter__(self):
  367. return weakref.proxy(it)
  368. weak_it = IteratesWeakly()
  369. # Calls proxy.__next__
  370. self.assertEqual(list(weak_it), [4, 5, 6])
  371. def test_proxy_bad_next(self):
  372. # bpo-44720: PyIter_Next() shouldn't be called if the reference
  373. # isn't an iterator.
  374. not_an_iterator = lambda: 0
  375. class A:
  376. def __iter__(self):
  377. return weakref.proxy(not_an_iterator)
  378. a = A()
  379. msg = "Weakref proxy referenced a non-iterator"
  380. with self.assertRaisesRegex(TypeError, msg):
  381. list(a)
  382. def test_proxy_reversed(self):
  383. class MyObj:
  384. def __len__(self):
  385. return 3
  386. def __reversed__(self):
  387. return iter('cba')
  388. obj = MyObj()
  389. self.assertEqual("".join(reversed(weakref.proxy(obj))), "cba")
  390. def test_proxy_hash(self):
  391. class MyObj:
  392. def __hash__(self):
  393. return 42
  394. obj = MyObj()
  395. with self.assertRaises(TypeError):
  396. hash(weakref.proxy(obj))
  397. class MyObj:
  398. __hash__ = None
  399. obj = MyObj()
  400. with self.assertRaises(TypeError):
  401. hash(weakref.proxy(obj))
  402. def test_getweakrefcount(self):
  403. o = C()
  404. ref1 = weakref.ref(o)
  405. ref2 = weakref.ref(o, self.callback)
  406. self.assertEqual(weakref.getweakrefcount(o), 2,
  407. "got wrong number of weak reference objects")
  408. proxy1 = weakref.proxy(o)
  409. proxy2 = weakref.proxy(o, self.callback)
  410. self.assertEqual(weakref.getweakrefcount(o), 4,
  411. "got wrong number of weak reference objects")
  412. del ref1, ref2, proxy1, proxy2
  413. gc_collect() # For PyPy or other GCs.
  414. self.assertEqual(weakref.getweakrefcount(o), 0,
  415. "weak reference objects not unlinked from"
  416. " referent when discarded.")
  417. # assumes ints do not support weakrefs
  418. self.assertEqual(weakref.getweakrefcount(1), 0,
  419. "got wrong number of weak reference objects for int")
  420. def test_getweakrefs(self):
  421. o = C()
  422. ref1 = weakref.ref(o, self.callback)
  423. ref2 = weakref.ref(o, self.callback)
  424. del ref1
  425. gc_collect() # For PyPy or other GCs.
  426. self.assertEqual(weakref.getweakrefs(o), [ref2],
  427. "list of refs does not match")
  428. o = C()
  429. ref1 = weakref.ref(o, self.callback)
  430. ref2 = weakref.ref(o, self.callback)
  431. del ref2
  432. gc_collect() # For PyPy or other GCs.
  433. self.assertEqual(weakref.getweakrefs(o), [ref1],
  434. "list of refs does not match")
  435. del ref1
  436. gc_collect() # For PyPy or other GCs.
  437. self.assertEqual(weakref.getweakrefs(o), [],
  438. "list of refs not cleared")
  439. # assumes ints do not support weakrefs
  440. self.assertEqual(weakref.getweakrefs(1), [],
  441. "list of refs does not match for int")
  442. def test_newstyle_number_ops(self):
  443. class F(float):
  444. pass
  445. f = F(2.0)
  446. p = weakref.proxy(f)
  447. self.assertEqual(p + 1.0, 3.0)
  448. self.assertEqual(1.0 + p, 3.0) # this used to SEGV
  449. def test_callbacks_protected(self):
  450. # Callbacks protected from already-set exceptions?
  451. # Regression test for SF bug #478534.
  452. class BogusError(Exception):
  453. pass
  454. data = {}
  455. def remove(k):
  456. del data[k]
  457. def encapsulate():
  458. f = lambda : ()
  459. data[weakref.ref(f, remove)] = None
  460. raise BogusError
  461. try:
  462. encapsulate()
  463. except BogusError:
  464. pass
  465. else:
  466. self.fail("exception not properly restored")
  467. try:
  468. encapsulate()
  469. except BogusError:
  470. pass
  471. else:
  472. self.fail("exception not properly restored")
  473. def test_sf_bug_840829(self):
  474. # "weakref callbacks and gc corrupt memory"
  475. # subtype_dealloc erroneously exposed a new-style instance
  476. # already in the process of getting deallocated to gc,
  477. # causing double-deallocation if the instance had a weakref
  478. # callback that triggered gc.
  479. # If the bug exists, there probably won't be an obvious symptom
  480. # in a release build. In a debug build, a segfault will occur
  481. # when the second attempt to remove the instance from the "list
  482. # of all objects" occurs.
  483. import gc
  484. class C(object):
  485. pass
  486. c = C()
  487. wr = weakref.ref(c, lambda ignore: gc.collect())
  488. del c
  489. # There endeth the first part. It gets worse.
  490. del wr
  491. c1 = C()
  492. c1.i = C()
  493. wr = weakref.ref(c1.i, lambda ignore: gc.collect())
  494. c2 = C()
  495. c2.c1 = c1
  496. del c1 # still alive because c2 points to it
  497. # Now when subtype_dealloc gets called on c2, it's not enough just
  498. # that c2 is immune from gc while the weakref callbacks associated
  499. # with c2 execute (there are none in this 2nd half of the test, btw).
  500. # subtype_dealloc goes on to call the base classes' deallocs too,
  501. # so any gc triggered by weakref callbacks associated with anything
  502. # torn down by a base class dealloc can also trigger double
  503. # deallocation of c2.
  504. del c2
  505. def test_callback_in_cycle(self):
  506. import gc
  507. class J(object):
  508. pass
  509. class II(object):
  510. def acallback(self, ignore):
  511. self.J
  512. I = II()
  513. I.J = J
  514. I.wr = weakref.ref(J, I.acallback)
  515. # Now J and II are each in a self-cycle (as all new-style class
  516. # objects are, since their __mro__ points back to them). I holds
  517. # both a weak reference (I.wr) and a strong reference (I.J) to class
  518. # J. I is also in a cycle (I.wr points to a weakref that references
  519. # I.acallback). When we del these three, they all become trash, but
  520. # the cycles prevent any of them from getting cleaned up immediately.
  521. # Instead they have to wait for cyclic gc to deduce that they're
  522. # trash.
  523. #
  524. # gc used to call tp_clear on all of them, and the order in which
  525. # it does that is pretty accidental. The exact order in which we
  526. # built up these things manages to provoke gc into running tp_clear
  527. # in just the right order (I last). Calling tp_clear on II leaves
  528. # behind an insane class object (its __mro__ becomes NULL). Calling
  529. # tp_clear on J breaks its self-cycle, but J doesn't get deleted
  530. # just then because of the strong reference from I.J. Calling
  531. # tp_clear on I starts to clear I's __dict__, and just happens to
  532. # clear I.J first -- I.wr is still intact. That removes the last
  533. # reference to J, which triggers the weakref callback. The callback
  534. # tries to do "self.J", and instances of new-style classes look up
  535. # attributes ("J") in the class dict first. The class (II) wants to
  536. # search II.__mro__, but that's NULL. The result was a segfault in
  537. # a release build, and an assert failure in a debug build.
  538. del I, J, II
  539. gc.collect()
  540. def test_callback_reachable_one_way(self):
  541. import gc
  542. # This one broke the first patch that fixed the previous test. In this case,
  543. # the objects reachable from the callback aren't also reachable
  544. # from the object (c1) *triggering* the callback: you can get to
  545. # c1 from c2, but not vice-versa. The result was that c2's __dict__
  546. # got tp_clear'ed by the time the c2.cb callback got invoked.
  547. class C:
  548. def cb(self, ignore):
  549. self.me
  550. self.c1
  551. self.wr
  552. c1, c2 = C(), C()
  553. c2.me = c2
  554. c2.c1 = c1
  555. c2.wr = weakref.ref(c1, c2.cb)
  556. del c1, c2
  557. gc.collect()
  558. def test_callback_different_classes(self):
  559. import gc
  560. # Like test_callback_reachable_one_way, except c2 and c1 have different
  561. # classes. c2's class (C) isn't reachable from c1 then, so protecting
  562. # objects reachable from the dying object (c1) isn't enough to stop
  563. # c2's class (C) from getting tp_clear'ed before c2.cb is invoked.
  564. # The result was a segfault (C.__mro__ was NULL when the callback
  565. # tried to look up self.me).
  566. class C(object):
  567. def cb(self, ignore):
  568. self.me
  569. self.c1
  570. self.wr
  571. class D:
  572. pass
  573. c1, c2 = D(), C()
  574. c2.me = c2
  575. c2.c1 = c1
  576. c2.wr = weakref.ref(c1, c2.cb)
  577. del c1, c2, C, D
  578. gc.collect()
  579. def test_callback_in_cycle_resurrection(self):
  580. import gc
  581. # Do something nasty in a weakref callback: resurrect objects
  582. # from dead cycles. For this to be attempted, the weakref and
  583. # its callback must also be part of the cyclic trash (else the
  584. # objects reachable via the callback couldn't be in cyclic trash
  585. # to begin with -- the callback would act like an external root).
  586. # But gc clears trash weakrefs with callbacks early now, which
  587. # disables the callbacks, so the callbacks shouldn't get called
  588. # at all (and so nothing actually gets resurrected).
  589. alist = []
  590. class C(object):
  591. def __init__(self, value):
  592. self.attribute = value
  593. def acallback(self, ignore):
  594. alist.append(self.c)
  595. c1, c2 = C(1), C(2)
  596. c1.c = c2
  597. c2.c = c1
  598. c1.wr = weakref.ref(c2, c1.acallback)
  599. c2.wr = weakref.ref(c1, c2.acallback)
  600. def C_went_away(ignore):
  601. alist.append("C went away")
  602. wr = weakref.ref(C, C_went_away)
  603. del c1, c2, C # make them all trash
  604. self.assertEqual(alist, []) # del isn't enough to reclaim anything
  605. gc.collect()
  606. # c1.wr and c2.wr were part of the cyclic trash, so should have
  607. # been cleared without their callbacks executing. OTOH, the weakref
  608. # to C is bound to a function local (wr), and wasn't trash, so that
  609. # callback should have been invoked when C went away.
  610. self.assertEqual(alist, ["C went away"])
  611. # The remaining weakref should be dead now (its callback ran).
  612. self.assertEqual(wr(), None)
  613. del alist[:]
  614. gc.collect()
  615. self.assertEqual(alist, [])
  616. def test_callbacks_on_callback(self):
  617. import gc
  618. # Set up weakref callbacks *on* weakref callbacks.
  619. alist = []
  620. def safe_callback(ignore):
  621. alist.append("safe_callback called")
  622. class C(object):
  623. def cb(self, ignore):
  624. alist.append("cb called")
  625. c, d = C(), C()
  626. c.other = d
  627. d.other = c
  628. callback = c.cb
  629. c.wr = weakref.ref(d, callback) # this won't trigger
  630. d.wr = weakref.ref(callback, d.cb) # ditto
  631. external_wr = weakref.ref(callback, safe_callback) # but this will
  632. self.assertIs(external_wr(), callback)
  633. # The weakrefs attached to c and d should get cleared, so that
  634. # C.cb is never called. But external_wr isn't part of the cyclic
  635. # trash, and no cyclic trash is reachable from it, so safe_callback
  636. # should get invoked when the bound method object callback (c.cb)
  637. # -- which is itself a callback, and also part of the cyclic trash --
  638. # gets reclaimed at the end of gc.
  639. del callback, c, d, C
  640. self.assertEqual(alist, []) # del isn't enough to clean up cycles
  641. gc.collect()
  642. self.assertEqual(alist, ["safe_callback called"])
  643. self.assertEqual(external_wr(), None)
  644. del alist[:]
  645. gc.collect()
  646. self.assertEqual(alist, [])
  647. def test_gc_during_ref_creation(self):
  648. self.check_gc_during_creation(weakref.ref)
  649. def test_gc_during_proxy_creation(self):
  650. self.check_gc_during_creation(weakref.proxy)
  651. def check_gc_during_creation(self, makeref):
  652. thresholds = gc.get_threshold()
  653. gc.set_threshold(1, 1, 1)
  654. gc.collect()
  655. class A:
  656. pass
  657. def callback(*args):
  658. pass
  659. referenced = A()
  660. a = A()
  661. a.a = a
  662. a.wr = makeref(referenced)
  663. try:
  664. # now make sure the object and the ref get labeled as
  665. # cyclic trash:
  666. a = A()
  667. weakref.ref(referenced, callback)
  668. finally:
  669. gc.set_threshold(*thresholds)
  670. def test_ref_created_during_del(self):
  671. # Bug #1377858
  672. # A weakref created in an object's __del__() would crash the
  673. # interpreter when the weakref was cleaned up since it would refer to
  674. # non-existent memory. This test should not segfault the interpreter.
  675. class Target(object):
  676. def __del__(self):
  677. global ref_from_del
  678. ref_from_del = weakref.ref(self)
  679. w = Target()
  680. def test_init(self):
  681. # Issue 3634
  682. # <weakref to class>.__init__() doesn't check errors correctly
  683. r = weakref.ref(Exception)
  684. self.assertRaises(TypeError, r.__init__, 0, 0, 0, 0, 0)
  685. # No exception should be raised here
  686. gc.collect()
  687. def test_classes(self):
  688. # Check that classes are weakrefable.
  689. class A(object):
  690. pass
  691. l = []
  692. weakref.ref(int)
  693. a = weakref.ref(A, l.append)
  694. A = None
  695. gc.collect()
  696. self.assertEqual(a(), None)
  697. self.assertEqual(l, [a])
  698. def test_equality(self):
  699. # Alive weakrefs defer equality testing to their underlying object.
  700. x = Object(1)
  701. y = Object(1)
  702. z = Object(2)
  703. a = weakref.ref(x)
  704. b = weakref.ref(y)
  705. c = weakref.ref(z)
  706. d = weakref.ref(x)
  707. # Note how we directly test the operators here, to stress both
  708. # __eq__ and __ne__.
  709. self.assertTrue(a == b)
  710. self.assertFalse(a != b)
  711. self.assertFalse(a == c)
  712. self.assertTrue(a != c)
  713. self.assertTrue(a == d)
  714. self.assertFalse(a != d)
  715. self.assertFalse(a == x)
  716. self.assertTrue(a != x)
  717. self.assertTrue(a == ALWAYS_EQ)
  718. self.assertFalse(a != ALWAYS_EQ)
  719. del x, y, z
  720. gc.collect()
  721. for r in a, b, c:
  722. # Sanity check
  723. self.assertIs(r(), None)
  724. # Dead weakrefs compare by identity: whether `a` and `d` are the
  725. # same weakref object is an implementation detail, since they pointed
  726. # to the same original object and didn't have a callback.
  727. # (see issue #16453).
  728. self.assertFalse(a == b)
  729. self.assertTrue(a != b)
  730. self.assertFalse(a == c)
  731. self.assertTrue(a != c)
  732. self.assertEqual(a == d, a is d)
  733. self.assertEqual(a != d, a is not d)
  734. def test_ordering(self):
  735. # weakrefs cannot be ordered, even if the underlying objects can.
  736. ops = [operator.lt, operator.gt, operator.le, operator.ge]
  737. x = Object(1)
  738. y = Object(1)
  739. a = weakref.ref(x)
  740. b = weakref.ref(y)
  741. for op in ops:
  742. self.assertRaises(TypeError, op, a, b)
  743. # Same when dead.
  744. del x, y
  745. gc.collect()
  746. for op in ops:
  747. self.assertRaises(TypeError, op, a, b)
  748. def test_hashing(self):
  749. # Alive weakrefs hash the same as the underlying object
  750. x = Object(42)
  751. y = Object(42)
  752. a = weakref.ref(x)
  753. b = weakref.ref(y)
  754. self.assertEqual(hash(a), hash(42))
  755. del x, y
  756. gc.collect()
  757. # Dead weakrefs:
  758. # - retain their hash is they were hashed when alive;
  759. # - otherwise, cannot be hashed.
  760. self.assertEqual(hash(a), hash(42))
  761. self.assertRaises(TypeError, hash, b)
  762. def test_trashcan_16602(self):
  763. # Issue #16602: when a weakref's target was part of a long
  764. # deallocation chain, the trashcan mechanism could delay clearing
  765. # of the weakref and make the target object visible from outside
  766. # code even though its refcount had dropped to 0. A crash ensued.
  767. class C:
  768. def __init__(self, parent):
  769. if not parent:
  770. return
  771. wself = weakref.ref(self)
  772. def cb(wparent):
  773. o = wself()
  774. self.wparent = weakref.ref(parent, cb)
  775. d = weakref.WeakKeyDictionary()
  776. root = c = C(None)
  777. for n in range(100):
  778. d[c] = c = C(c)
  779. del root
  780. gc.collect()
  781. def test_callback_attribute(self):
  782. x = Object(1)
  783. callback = lambda ref: None
  784. ref1 = weakref.ref(x, callback)
  785. self.assertIs(ref1.__callback__, callback)
  786. ref2 = weakref.ref(x)
  787. self.assertIsNone(ref2.__callback__)
  788. def test_callback_attribute_after_deletion(self):
  789. x = Object(1)
  790. ref = weakref.ref(x, self.callback)
  791. self.assertIsNotNone(ref.__callback__)
  792. del x
  793. support.gc_collect()
  794. self.assertIsNone(ref.__callback__)
  795. def test_set_callback_attribute(self):
  796. x = Object(1)
  797. callback = lambda ref: None
  798. ref1 = weakref.ref(x, callback)
  799. with self.assertRaises(AttributeError):
  800. ref1.__callback__ = lambda ref: None
  801. def test_callback_gcs(self):
  802. class ObjectWithDel(Object):
  803. def __del__(self): pass
  804. x = ObjectWithDel(1)
  805. ref1 = weakref.ref(x, lambda ref: support.gc_collect())
  806. del x
  807. support.gc_collect()
  808. class SubclassableWeakrefTestCase(TestBase):
  809. def test_subclass_refs(self):
  810. class MyRef(weakref.ref):
  811. def __init__(self, ob, callback=None, value=42):
  812. self.value = value
  813. super().__init__(ob, callback)
  814. def __call__(self):
  815. self.called = True
  816. return super().__call__()
  817. o = Object("foo")
  818. mr = MyRef(o, value=24)
  819. self.assertIs(mr(), o)
  820. self.assertTrue(mr.called)
  821. self.assertEqual(mr.value, 24)
  822. del o
  823. gc_collect() # For PyPy or other GCs.
  824. self.assertIsNone(mr())
  825. self.assertTrue(mr.called)
  826. def test_subclass_refs_dont_replace_standard_refs(self):
  827. class MyRef(weakref.ref):
  828. pass
  829. o = Object(42)
  830. r1 = MyRef(o)
  831. r2 = weakref.ref(o)
  832. self.assertIsNot(r1, r2)
  833. self.assertEqual(weakref.getweakrefs(o), [r2, r1])
  834. self.assertEqual(weakref.getweakrefcount(o), 2)
  835. r3 = MyRef(o)
  836. self.assertEqual(weakref.getweakrefcount(o), 3)
  837. refs = weakref.getweakrefs(o)
  838. self.assertEqual(len(refs), 3)
  839. self.assertIs(r2, refs[0])
  840. self.assertIn(r1, refs[1:])
  841. self.assertIn(r3, refs[1:])
  842. def test_subclass_refs_dont_conflate_callbacks(self):
  843. class MyRef(weakref.ref):
  844. pass
  845. o = Object(42)
  846. r1 = MyRef(o, id)
  847. r2 = MyRef(o, str)
  848. self.assertIsNot(r1, r2)
  849. refs = weakref.getweakrefs(o)
  850. self.assertIn(r1, refs)
  851. self.assertIn(r2, refs)
  852. def test_subclass_refs_with_slots(self):
  853. class MyRef(weakref.ref):
  854. __slots__ = "slot1", "slot2"
  855. def __new__(type, ob, callback, slot1, slot2):
  856. return weakref.ref.__new__(type, ob, callback)
  857. def __init__(self, ob, callback, slot1, slot2):
  858. self.slot1 = slot1
  859. self.slot2 = slot2
  860. def meth(self):
  861. return self.slot1 + self.slot2
  862. o = Object(42)
  863. r = MyRef(o, None, "abc", "def")
  864. self.assertEqual(r.slot1, "abc")
  865. self.assertEqual(r.slot2, "def")
  866. self.assertEqual(r.meth(), "abcdef")
  867. self.assertFalse(hasattr(r, "__dict__"))
  868. def test_subclass_refs_with_cycle(self):
  869. """Confirm https://bugs.python.org/issue3100 is fixed."""
  870. # An instance of a weakref subclass can have attributes.
  871. # If such a weakref holds the only strong reference to the object,
  872. # deleting the weakref will delete the object. In this case,
  873. # the callback must not be called, because the ref object is
  874. # being deleted.
  875. class MyRef(weakref.ref):
  876. pass
  877. # Use a local callback, for "regrtest -R::"
  878. # to detect refcounting problems
  879. def callback(w):
  880. self.cbcalled += 1
  881. o = C()
  882. r1 = MyRef(o, callback)
  883. r1.o = o
  884. del o
  885. del r1 # Used to crash here
  886. self.assertEqual(self.cbcalled, 0)
  887. # Same test, with two weakrefs to the same object
  888. # (since code paths are different)
  889. o = C()
  890. r1 = MyRef(o, callback)
  891. r2 = MyRef(o, callback)
  892. r1.r = r2
  893. r2.o = o
  894. del o
  895. del r2
  896. del r1 # Used to crash here
  897. self.assertEqual(self.cbcalled, 0)
  898. class WeakMethodTestCase(unittest.TestCase):
  899. def _subclass(self):
  900. """Return an Object subclass overriding `some_method`."""
  901. class C(Object):
  902. def some_method(self):
  903. return 6
  904. return C
  905. def test_alive(self):
  906. o = Object(1)
  907. r = weakref.WeakMethod(o.some_method)
  908. self.assertIsInstance(r, weakref.ReferenceType)
  909. self.assertIsInstance(r(), type(o.some_method))
  910. self.assertIs(r().__self__, o)
  911. self.assertIs(r().__func__, o.some_method.__func__)
  912. self.assertEqual(r()(), 4)
  913. def test_object_dead(self):
  914. o = Object(1)
  915. r = weakref.WeakMethod(o.some_method)
  916. del o
  917. gc.collect()
  918. self.assertIs(r(), None)
  919. def test_method_dead(self):
  920. C = self._subclass()
  921. o = C(1)
  922. r = weakref.WeakMethod(o.some_method)
  923. del C.some_method
  924. gc.collect()
  925. self.assertIs(r(), None)
  926. def test_callback_when_object_dead(self):
  927. # Test callback behaviour when object dies first.
  928. C = self._subclass()
  929. calls = []
  930. def cb(arg):
  931. calls.append(arg)
  932. o = C(1)
  933. r = weakref.WeakMethod(o.some_method, cb)
  934. del o
  935. gc.collect()
  936. self.assertEqual(calls, [r])
  937. # Callback is only called once.
  938. C.some_method = Object.some_method
  939. gc.collect()
  940. self.assertEqual(calls, [r])
  941. def test_callback_when_method_dead(self):
  942. # Test callback behaviour when method dies first.
  943. C = self._subclass()
  944. calls = []
  945. def cb(arg):
  946. calls.append(arg)
  947. o = C(1)
  948. r = weakref.WeakMethod(o.some_method, cb)
  949. del C.some_method
  950. gc.collect()
  951. self.assertEqual(calls, [r])
  952. # Callback is only called once.
  953. del o
  954. gc.collect()
  955. self.assertEqual(calls, [r])
  956. @support.cpython_only
  957. def test_no_cycles(self):
  958. # A WeakMethod doesn't create any reference cycle to itself.
  959. o = Object(1)
  960. def cb(_):
  961. pass
  962. r = weakref.WeakMethod(o.some_method, cb)
  963. wr = weakref.ref(r)
  964. del r
  965. self.assertIs(wr(), None)
  966. def test_equality(self):
  967. def _eq(a, b):
  968. self.assertTrue(a == b)
  969. self.assertFalse(a != b)
  970. def _ne(a, b):
  971. self.assertTrue(a != b)
  972. self.assertFalse(a == b)
  973. x = Object(1)
  974. y = Object(1)
  975. a = weakref.WeakMethod(x.some_method)
  976. b = weakref.WeakMethod(y.some_method)
  977. c = weakref.WeakMethod(x.other_method)
  978. d = weakref.WeakMethod(y.other_method)
  979. # Objects equal, same method
  980. _eq(a, b)
  981. _eq(c, d)
  982. # Objects equal, different method
  983. _ne(a, c)
  984. _ne(a, d)
  985. _ne(b, c)
  986. _ne(b, d)
  987. # Objects unequal, same or different method
  988. z = Object(2)
  989. e = weakref.WeakMethod(z.some_method)
  990. f = weakref.WeakMethod(z.other_method)
  991. _ne(a, e)
  992. _ne(a, f)
  993. _ne(b, e)
  994. _ne(b, f)
  995. # Compare with different types
  996. _ne(a, x.some_method)
  997. _eq(a, ALWAYS_EQ)
  998. del x, y, z
  999. gc.collect()
  1000. # Dead WeakMethods compare by identity
  1001. refs = a, b, c, d, e, f
  1002. for q in refs:
  1003. for r in refs:
  1004. self.assertEqual(q == r, q is r)
  1005. self.assertEqual(q != r, q is not r)
  1006. def test_hashing(self):
  1007. # Alive WeakMethods are hashable if the underlying object is
  1008. # hashable.
  1009. x = Object(1)
  1010. y = Object(1)
  1011. a = weakref.WeakMethod(x.some_method)
  1012. b = weakref.WeakMethod(y.some_method)
  1013. c = weakref.WeakMethod(y.other_method)
  1014. # Since WeakMethod objects are equal, the hashes should be equal.
  1015. self.assertEqual(hash(a), hash(b))
  1016. ha = hash(a)
  1017. # Dead WeakMethods retain their old hash value
  1018. del x, y
  1019. gc.collect()
  1020. self.assertEqual(hash(a), ha)
  1021. self.assertEqual(hash(b), ha)
  1022. # If it wasn't hashed when alive, a dead WeakMethod cannot be hashed.
  1023. self.assertRaises(TypeError, hash, c)
  1024. class MappingTestCase(TestBase):
  1025. COUNT = 10
  1026. def check_len_cycles(self, dict_type, cons):
  1027. N = 20
  1028. items = [RefCycle() for i in range(N)]
  1029. dct = dict_type(cons(o) for o in items)
  1030. # Keep an iterator alive
  1031. it = dct.items()
  1032. try:
  1033. next(it)
  1034. except StopIteration:
  1035. pass
  1036. del items
  1037. gc.collect()
  1038. n1 = len(dct)
  1039. del it
  1040. gc.collect()
  1041. n2 = len(dct)
  1042. # one item may be kept alive inside the iterator
  1043. self.assertIn(n1, (0, 1))
  1044. self.assertEqual(n2, 0)
  1045. def test_weak_keyed_len_cycles(self):
  1046. self.check_len_cycles(weakref.WeakKeyDictionary, lambda k: (k, 1))
  1047. def test_weak_valued_len_cycles(self):
  1048. self.check_len_cycles(weakref.WeakValueDictionary, lambda k: (1, k))
  1049. def check_len_race(self, dict_type, cons):
  1050. # Extended sanity checks for len() in the face of cyclic collection
  1051. self.addCleanup(gc.set_threshold, *gc.get_threshold())
  1052. for th in range(1, 100):
  1053. N = 20
  1054. gc.collect(0)
  1055. gc.set_threshold(th, th, th)
  1056. items = [RefCycle() for i in range(N)]
  1057. dct = dict_type(cons(o) for o in items)
  1058. del items
  1059. # All items will be collected at next garbage collection pass
  1060. it = dct.items()
  1061. try:
  1062. next(it)
  1063. except StopIteration:
  1064. pass
  1065. n1 = len(dct)
  1066. del it
  1067. n2 = len(dct)
  1068. self.assertGreaterEqual(n1, 0)
  1069. self.assertLessEqual(n1, N)
  1070. self.assertGreaterEqual(n2, 0)
  1071. self.assertLessEqual(n2, n1)
  1072. def test_weak_keyed_len_race(self):
  1073. self.check_len_race(weakref.WeakKeyDictionary, lambda k: (k, 1))
  1074. def test_weak_valued_len_race(self):
  1075. self.check_len_race(weakref.WeakValueDictionary, lambda k: (1, k))
  1076. def test_weak_values(self):
  1077. #
  1078. # This exercises d.copy(), d.items(), d[], del d[], len(d).
  1079. #
  1080. dict, objects = self.make_weak_valued_dict()
  1081. for o in objects:
  1082. self.assertEqual(weakref.getweakrefcount(o), 1)
  1083. self.assertIs(o, dict[o.arg],
  1084. "wrong object returned by weak dict!")
  1085. items1 = list(dict.items())
  1086. items2 = list(dict.copy().items())
  1087. items1.sort()
  1088. items2.sort()
  1089. self.assertEqual(items1, items2,
  1090. "cloning of weak-valued dictionary did not work!")
  1091. del items1, items2
  1092. self.assertEqual(len(dict), self.COUNT)
  1093. del objects[0]
  1094. gc_collect() # For PyPy or other GCs.
  1095. self.assertEqual(len(dict), self.COUNT - 1,
  1096. "deleting object did not cause dictionary update")
  1097. del objects, o
  1098. gc_collect() # For PyPy or other GCs.
  1099. self.assertEqual(len(dict), 0,
  1100. "deleting the values did not clear the dictionary")
  1101. # regression on SF bug #447152:
  1102. dict = weakref.WeakValueDictionary()
  1103. self.assertRaises(KeyError, dict.__getitem__, 1)
  1104. dict[2] = C()
  1105. gc_collect() # For PyPy or other GCs.
  1106. self.assertRaises(KeyError, dict.__getitem__, 2)
  1107. def test_weak_keys(self):
  1108. #
  1109. # This exercises d.copy(), d.items(), d[] = v, d[], del d[],
  1110. # len(d), k in d.
  1111. #
  1112. dict, objects = self.make_weak_keyed_dict()
  1113. for o in objects:
  1114. self.assertEqual(weakref.getweakrefcount(o), 1,
  1115. "wrong number of weak references to %r!" % o)
  1116. self.assertIs(o.arg, dict[o],
  1117. "wrong object returned by weak dict!")
  1118. items1 = dict.items()
  1119. items2 = dict.copy().items()
  1120. self.assertEqual(set(items1), set(items2),
  1121. "cloning of weak-keyed dictionary did not work!")
  1122. del items1, items2
  1123. self.assertEqual(len(dict), self.COUNT)
  1124. del objects[0]
  1125. gc_collect() # For PyPy or other GCs.
  1126. self.assertEqual(len(dict), (self.COUNT - 1),
  1127. "deleting object did not cause dictionary update")
  1128. del objects, o
  1129. gc_collect() # For PyPy or other GCs.
  1130. self.assertEqual(len(dict), 0,
  1131. "deleting the keys did not clear the dictionary")
  1132. o = Object(42)
  1133. dict[o] = "What is the meaning of the universe?"
  1134. self.assertIn(o, dict)
  1135. self.assertNotIn(34, dict)
  1136. def test_weak_keyed_iters(self):
  1137. dict, objects = self.make_weak_keyed_dict()
  1138. self.check_iters(dict)
  1139. # Test keyrefs()
  1140. refs = dict.keyrefs()
  1141. self.assertEqual(len(refs), len(objects))
  1142. objects2 = list(objects)
  1143. for wr in refs:
  1144. ob = wr()
  1145. self.assertIn(ob, dict)
  1146. self.assertIn(ob, dict)
  1147. self.assertEqual(ob.arg, dict[ob])
  1148. objects2.remove(ob)
  1149. self.assertEqual(len(objects2), 0)
  1150. # Test iterkeyrefs()
  1151. objects2 = list(objects)
  1152. self.assertEqual(len(list(dict.keyrefs())), len(objects))
  1153. for wr in dict.keyrefs():
  1154. ob = wr()
  1155. self.assertIn(ob, dict)
  1156. self.assertIn(ob, dict)
  1157. self.assertEqual(ob.arg, dict[ob])
  1158. objects2.remove(ob)
  1159. self.assertEqual(len(objects2), 0)
  1160. def test_weak_valued_iters(self):
  1161. dict, objects = self.make_weak_valued_dict()
  1162. self.check_iters(dict)
  1163. # Test valuerefs()
  1164. refs = dict.valuerefs()
  1165. self.assertEqual(len(refs), len(objects))
  1166. objects2 = list(objects)
  1167. for wr in refs:
  1168. ob = wr()
  1169. self.assertEqual(ob, dict[ob.arg])
  1170. self.assertEqual(ob.arg, dict[ob.arg].arg)
  1171. objects2.remove(ob)
  1172. self.assertEqual(len(objects2), 0)
  1173. # Test itervaluerefs()
  1174. objects2 = list(objects)
  1175. self.assertEqual(len(list(dict.itervaluerefs())), len(objects))
  1176. for wr in dict.itervaluerefs():
  1177. ob = wr()
  1178. self.assertEqual(ob, dict[ob.arg])
  1179. self.assertEqual(ob.arg, dict[ob.arg].arg)
  1180. objects2.remove(ob)
  1181. self.assertEqual(len(objects2), 0)
  1182. def check_iters(self, dict):
  1183. # item iterator:
  1184. items = list(dict.items())
  1185. for item in dict.items():
  1186. items.remove(item)
  1187. self.assertFalse(items, "items() did not touch all items")
  1188. # key iterator, via __iter__():
  1189. keys = list(dict.keys())
  1190. for k in dict:
  1191. keys.remove(k)
  1192. self.assertFalse(keys, "__iter__() did not touch all keys")
  1193. # key iterator, via iterkeys():
  1194. keys = list(dict.keys())
  1195. for k in dict.keys():
  1196. keys.remove(k)
  1197. self.assertFalse(keys, "iterkeys() did not touch all keys")
  1198. # value iterator:
  1199. values = list(dict.values())
  1200. for v in dict.values():
  1201. values.remove(v)
  1202. self.assertFalse(values,
  1203. "itervalues() did not touch all values")
  1204. def check_weak_destroy_while_iterating(self, dict, objects, iter_name):
  1205. n = len(dict)
  1206. it = iter(getattr(dict, iter_name)())
  1207. next(it) # Trigger internal iteration
  1208. # Destroy an object
  1209. del objects[-1]
  1210. gc.collect() # just in case
  1211. # We have removed either the first consumed object, or another one
  1212. self.assertIn(len(list(it)), [len(objects), len(objects) - 1])
  1213. del it
  1214. # The removal has been committed
  1215. self.assertEqual(len(dict), n - 1)
  1216. def check_weak_destroy_and_mutate_while_iterating(self, dict, testcontext):
  1217. # Check that we can explicitly mutate the weak dict without
  1218. # interfering with delayed removal.
  1219. # `testcontext` should create an iterator, destroy one of the
  1220. # weakref'ed objects and then return a new key/value pair corresponding
  1221. # to the destroyed object.
  1222. with testcontext() as (k, v):
  1223. self.assertNotIn(k, dict)
  1224. with testcontext() as (k, v):
  1225. self.assertRaises(KeyError, dict.__delitem__, k)
  1226. self.assertNotIn(k, dict)
  1227. with testcontext() as (k, v):
  1228. self.assertRaises(KeyError, dict.pop, k)
  1229. self.assertNotIn(k, dict)
  1230. with testcontext() as (k, v):
  1231. dict[k] = v
  1232. self.assertEqual(dict[k], v)
  1233. ddict = copy.copy(dict)
  1234. with testcontext() as (k, v):
  1235. dict.update(ddict)
  1236. self.assertEqual(dict, ddict)
  1237. with testcontext() as (k, v):
  1238. dict.clear()
  1239. self.assertEqual(len(dict), 0)
  1240. def check_weak_del_and_len_while_iterating(self, dict, testcontext):
  1241. # Check that len() works when both iterating and removing keys
  1242. # explicitly through various means (.pop(), .clear()...), while
  1243. # implicit mutation is deferred because an iterator is alive.
  1244. # (each call to testcontext() should schedule one item for removal
  1245. # for this test to work properly)
  1246. o = Object(123456)
  1247. with testcontext():
  1248. n = len(dict)
  1249. # Since underlying dict is ordered, first item is popped
  1250. dict.pop(next(dict.keys()))
  1251. self.assertEqual(len(dict), n - 1)
  1252. dict[o] = o
  1253. self.assertEqual(len(dict), n)
  1254. # last item in objects is removed from dict in context shutdown
  1255. with testcontext():
  1256. self.assertEqual(len(dict), n - 1)
  1257. # Then, (o, o) is popped
  1258. dict.popitem()
  1259. self.assertEqual(len(dict), n - 2)
  1260. with testcontext():
  1261. self.assertEqual(len(dict), n - 3)
  1262. del dict[next(dict.keys())]
  1263. self.assertEqual(len(dict), n - 4)
  1264. with testcontext():
  1265. self.assertEqual(len(dict), n - 5)
  1266. dict.popitem()
  1267. self.assertEqual(len(dict), n - 6)
  1268. with testcontext():
  1269. dict.clear()
  1270. self.assertEqual(len(dict), 0)
  1271. self.assertEqual(len(dict), 0)
  1272. def test_weak_keys_destroy_while_iterating(self):
  1273. # Issue #7105: iterators shouldn't crash when a key is implicitly removed
  1274. dict, objects = self.make_weak_keyed_dict()
  1275. self.check_weak_destroy_while_iterating(dict, objects, 'keys')
  1276. self.check_weak_destroy_while_iterating(dict, objects, 'items')
  1277. self.check_weak_destroy_while_iterating(dict, objects, 'values')
  1278. self.check_weak_destroy_while_iterating(dict, objects, 'keyrefs')
  1279. dict, objects = self.make_weak_keyed_dict()
  1280. @contextlib.contextmanager
  1281. def testcontext():
  1282. try:
  1283. it = iter(dict.items())
  1284. next(it)
  1285. # Schedule a key/value for removal and recreate it
  1286. v = objects.pop().arg
  1287. gc.collect() # just in case
  1288. yield Object(v), v
  1289. finally:
  1290. it = None # should commit all removals
  1291. gc.collect()
  1292. self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
  1293. # Issue #21173: len() fragile when keys are both implicitly and
  1294. # explicitly removed.
  1295. dict, objects = self.make_weak_keyed_dict()
  1296. self.check_weak_del_and_len_while_iterating(dict, testcontext)
  1297. def test_weak_values_destroy_while_iterating(self):
  1298. # Issue #7105: iterators shouldn't crash when a key is implicitly removed
  1299. dict, objects = self.make_weak_valued_dict()
  1300. self.check_weak_destroy_while_iterating(dict, objects, 'keys')
  1301. self.check_weak_destroy_while_iterating(dict, objects, 'items')
  1302. self.check_weak_destroy_while_iterating(dict, objects, 'values')
  1303. self.check_weak_destroy_while_iterating(dict, objects, 'itervaluerefs')
  1304. self.check_weak_destroy_while_iterating(dict, objects, 'valuerefs')
  1305. dict, objects = self.make_weak_valued_dict()
  1306. @contextlib.contextmanager
  1307. def testcontext():
  1308. try:
  1309. it = iter(dict.items())
  1310. next(it)
  1311. # Schedule a key/value for removal and recreate it
  1312. k = objects.pop().arg
  1313. gc.collect() # just in case
  1314. yield k, Object(k)
  1315. finally:
  1316. it = None # should commit all removals
  1317. gc.collect()
  1318. self.check_weak_destroy_and_mutate_while_iterating(dict, testcontext)
  1319. dict, objects = self.make_weak_valued_dict()
  1320. self.check_weak_del_and_len_while_iterating(dict, testcontext)
  1321. def test_make_weak_keyed_dict_from_dict(self):
  1322. o = Object(3)
  1323. dict = weakref.WeakKeyDictionary({o:364})
  1324. self.assertEqual(dict[o], 364)
  1325. def test_make_weak_keyed_dict_from_weak_keyed_dict(self):
  1326. o = Object(3)
  1327. dict = weakref.WeakKeyDictionary({o:364})
  1328. dict2 = weakref.WeakKeyDictionary(dict)
  1329. self.assertEqual(dict[o], 364)
  1330. def make_weak_keyed_dict(self):
  1331. dict = weakref.WeakKeyDictionary()
  1332. objects = list(map(Object, range(self.COUNT)))
  1333. for o in objects:
  1334. dict[o] = o.arg
  1335. return dict, objects
  1336. def test_make_weak_valued_dict_from_dict(self):
  1337. o = Object(3)
  1338. dict = weakref.WeakValueDictionary({364:o})
  1339. self.assertEqual(dict[364], o)
  1340. def test_make_weak_valued_dict_from_weak_valued_dict(self):
  1341. o = Object(3)
  1342. dict = weakref.WeakValueDictionary({364:o})
  1343. dict2 = weakref.WeakValueDictionary(dict)
  1344. self.assertEqual(dict[364], o)
  1345. def test_make_weak_valued_dict_misc(self):
  1346. # errors
  1347. self.assertRaises(TypeError, weakref.WeakValueDictionary.__init__)
  1348. self.assertRaises(TypeError, weakref.WeakValueDictionary, {}, {})
  1349. self.assertRaises(TypeError, weakref.WeakValueDictionary, (), ())
  1350. # special keyword arguments
  1351. o = Object(3)
  1352. for kw in 'self', 'dict', 'other', 'iterable':
  1353. d = weakref.WeakValueDictionary(**{kw: o})
  1354. self.assertEqual(list(d.keys()), [kw])
  1355. self.assertEqual(d[kw], o)
  1356. def make_weak_valued_dict(self):
  1357. dict = weakref.WeakValueDictionary()
  1358. objects = list(map(Object, range(self.COUNT)))
  1359. for o in objects:
  1360. dict[o.arg] = o
  1361. return dict, objects
  1362. def check_popitem(self, klass, key1, value1, key2, value2):
  1363. weakdict = klass()
  1364. weakdict[key1] = value1
  1365. weakdict[key2] = value2
  1366. self.assertEqual(len(weakdict), 2)
  1367. k, v = weakdict.popitem()
  1368. self.assertEqual(len(weakdict), 1)
  1369. if k is key1:
  1370. self.assertIs(v, value1)
  1371. else:
  1372. self.assertIs(v, value2)
  1373. k, v = weakdict.popitem()
  1374. self.assertEqual(len(weakdict), 0)
  1375. if k is key1:
  1376. self.assertIs(v, value1)
  1377. else:
  1378. self.assertIs(v, value2)
  1379. def test_weak_valued_dict_popitem(self):
  1380. self.check_popitem(weakref.WeakValueDictionary,
  1381. "key1", C(), "key2", C())
  1382. def test_weak_keyed_dict_popitem(self):
  1383. self.check_popitem(weakref.WeakKeyDictionary,
  1384. C(), "value 1", C(), "value 2")
  1385. def check_setdefault(self, klass, key, value1, value2):
  1386. self.assertIsNot(value1, value2,
  1387. "invalid test"
  1388. " -- value parameters must be distinct objects")
  1389. weakdict = klass()
  1390. o = weakdict.setdefault(key, value1)
  1391. self.assertIs(o, value1)
  1392. self.assertIn(key, weakdict)
  1393. self.assertIs(weakdict.get(key), value1)
  1394. self.assertIs(weakdict[key], value1)
  1395. o = weakdict.setdefault(key, value2)
  1396. self.assertIs(o, value1)
  1397. self.assertIn(key, weakdict)
  1398. self.assertIs(weakdict.get(key), value1)
  1399. self.assertIs(weakdict[key], value1)
  1400. def test_weak_valued_dict_setdefault(self):
  1401. self.check_setdefault(weakref.WeakValueDictionary,
  1402. "key", C(), C())
  1403. def test_weak_keyed_dict_setdefault(self):
  1404. self.check_setdefault(weakref.WeakKeyDictionary,
  1405. C(), "value 1", "value 2")
  1406. def check_update(self, klass, dict):
  1407. #
  1408. # This exercises d.update(), len(d), d.keys(), k in d,
  1409. # d.get(), d[].
  1410. #
  1411. weakdict = klass()
  1412. weakdict.update(dict)
  1413. self.assertEqual(len(weakdict), len(dict))
  1414. for k in weakdict.keys():
  1415. self.assertIn(k, dict, "mysterious new key appeared in weak dict")
  1416. v = dict.get(k)
  1417. self.assertIs(v, weakdict[k])
  1418. self.assertIs(v, weakdict.get(k))
  1419. for k in dict.keys():
  1420. self.assertIn(k, weakdict, "original key disappeared in weak dict")
  1421. v = dict[k]
  1422. self.assertIs(v, weakdict[k])
  1423. self.assertIs(v, weakdict.get(k))
  1424. def test_weak_valued_dict_update(self):
  1425. self.check_update(weakref.WeakValueDictionary,
  1426. {1: C(), 'a': C(), C(): C()})
  1427. # errors
  1428. self.assertRaises(TypeError, weakref.WeakValueDictionary.update)
  1429. d = weakref.WeakValueDictionary()
  1430. self.assertRaises(TypeError, d.update, {}, {})
  1431. self.assertRaises(TypeError, d.update, (), ())
  1432. self.assertEqual(list(d.keys()), [])
  1433. # special keyword arguments
  1434. o = Object(3)
  1435. for kw in 'self', 'dict', 'other', 'iterable':
  1436. d = weakref.WeakValueDictionary()
  1437. d.update(**{kw: o})
  1438. self.assertEqual(list(d.keys()), [kw])
  1439. self.assertEqual(d[kw], o)
  1440. def test_weak_valued_union_operators(self):
  1441. a = C()
  1442. b = C()
  1443. c = C()
  1444. wvd1 = weakref.WeakValueDictionary({1: a})
  1445. wvd2 = weakref.WeakValueDictionary({1: b, 2: a})
  1446. wvd3 = wvd1.copy()
  1447. d1 = {1: c, 3: b}
  1448. pairs = [(5, c), (6, b)]
  1449. tmp1 = wvd1 | wvd2 # Between two WeakValueDictionaries
  1450. self.assertEqual(dict(tmp1), dict(wvd1) | dict(wvd2))
  1451. self.assertIs(type(tmp1), weakref.WeakValueDictionary)
  1452. wvd1 |= wvd2
  1453. self.assertEqual(wvd1, tmp1)
  1454. tmp2 = wvd2 | d1 # Between WeakValueDictionary and mapping
  1455. self.assertEqual(dict(tmp2), dict(wvd2) | d1)
  1456. self.assertIs(type(tmp2), weakref.WeakValueDictionary)
  1457. wvd2 |= d1
  1458. self.assertEqual(wvd2, tmp2)
  1459. tmp3 = wvd3.copy() # Between WeakValueDictionary and iterable key, value
  1460. tmp3 |= pairs
  1461. self.assertEqual(dict(tmp3), dict(wvd3) | dict(pairs))
  1462. self.assertIs(type(tmp3), weakref.WeakValueDictionary)
  1463. tmp4 = d1 | wvd3 # Testing .__ror__
  1464. self.assertEqual(dict(tmp4), d1 | dict(wvd3))
  1465. self.assertIs(type(tmp4), weakref.WeakValueDictionary)
  1466. del a
  1467. self.assertNotIn(2, tmp1)
  1468. self.assertNotIn(2, tmp2)
  1469. self.assertNotIn(1, tmp3)
  1470. self.assertNotIn(1, tmp4)
  1471. def test_weak_keyed_dict_update(self):
  1472. self.check_update(weakref.WeakKeyDictionary,
  1473. {C(): 1, C(): 2, C(): 3})
  1474. def test_weak_keyed_delitem(self):
  1475. d = weakref.WeakKeyDictionary()
  1476. o1 = Object('1')
  1477. o2 = Object('2')
  1478. d[o1] = 'something'
  1479. d[o2] = 'something'
  1480. self.assertEqual(len(d), 2)
  1481. del d[o1]
  1482. self.assertEqual(len(d), 1)
  1483. self.assertEqual(list(d.keys()), [o2])
  1484. def test_weak_keyed_union_operators(self):
  1485. o1 = C()
  1486. o2 = C()
  1487. o3 = C()
  1488. wkd1 = weakref.WeakKeyDictionary({o1: 1, o2: 2})
  1489. wkd2 = weakref.WeakKeyDictionary({o3: 3, o1: 4})
  1490. wkd3 = wkd1.copy()
  1491. d1 = {o2: '5', o3: '6'}
  1492. pairs = [(o2, 7), (o3, 8)]
  1493. tmp1 = wkd1 | wkd2 # Between two WeakKeyDictionaries
  1494. self.assertEqual(dict(tmp1), dict(wkd1) | dict(wkd2))
  1495. self.assertIs(type(tmp1), weakref.WeakKeyDictionary)
  1496. wkd1 |= wkd2
  1497. self.assertEqual(wkd1, tmp1)
  1498. tmp2 = wkd2 | d1 # Between WeakKeyDictionary and mapping
  1499. self.assertEqual(dict(tmp2), dict(wkd2) | d1)
  1500. self.assertIs(type(tmp2), weakref.WeakKeyDictionary)
  1501. wkd2 |= d1
  1502. self.assertEqual(wkd2, tmp2)
  1503. tmp3 = wkd3.copy() # Between WeakKeyDictionary and iterable key, value
  1504. tmp3 |= pairs
  1505. self.assertEqual(dict(tmp3), dict(wkd3) | dict(pairs))
  1506. self.assertIs(type(tmp3), weakref.WeakKeyDictionary)
  1507. tmp4 = d1 | wkd3 # Testing .__ror__
  1508. self.assertEqual(dict(tmp4), d1 | dict(wkd3))
  1509. self.assertIs(type(tmp4), weakref.WeakKeyDictionary)
  1510. del o1
  1511. self.assertNotIn(4, tmp1.values())
  1512. self.assertNotIn(4, tmp2.values())
  1513. self.assertNotIn(1, tmp3.values())
  1514. self.assertNotIn(1, tmp4.values())
  1515. def test_weak_valued_delitem(self):
  1516. d = weakref.WeakValueDictionary()
  1517. o1 = Object('1')
  1518. o2 = Object('2')
  1519. d['something'] = o1
  1520. d['something else'] = o2
  1521. self.assertEqual(len(d), 2)
  1522. del d['something']
  1523. self.assertEqual(len(d), 1)
  1524. self.assertEqual(list(d.items()), [('something else', o2)])
  1525. def test_weak_keyed_bad_delitem(self):
  1526. d = weakref.WeakKeyDictionary()
  1527. o = Object('1')
  1528. # An attempt to delete an object that isn't there should raise
  1529. # KeyError. It didn't before 2.3.
  1530. self.assertRaises(KeyError, d.__delitem__, o)
  1531. self.assertRaises(KeyError, d.__getitem__, o)
  1532. # If a key isn't of a weakly referencable type, __getitem__ and
  1533. # __setitem__ raise TypeError. __delitem__ should too.
  1534. self.assertRaises(TypeError, d.__delitem__, 13)
  1535. self.assertRaises(TypeError, d.__getitem__, 13)
  1536. self.assertRaises(TypeError, d.__setitem__, 13, 13)
  1537. def test_weak_keyed_cascading_deletes(self):
  1538. # SF bug 742860. For some reason, before 2.3 __delitem__ iterated
  1539. # over the keys via self.data.iterkeys(). If things vanished from
  1540. # the dict during this (or got added), that caused a RuntimeError.
  1541. d = weakref.WeakKeyDictionary()
  1542. mutate = False
  1543. class C(object):
  1544. def __init__(self, i):
  1545. self.value = i
  1546. def __hash__(self):
  1547. return hash(self.value)
  1548. def __eq__(self, other):
  1549. if mutate:
  1550. # Side effect that mutates the dict, by removing the
  1551. # last strong reference to a key.
  1552. del objs[-1]
  1553. return self.value == other.value
  1554. objs = [C(i) for i in range(4)]
  1555. for o in objs:
  1556. d[o] = o.value
  1557. del o # now the only strong references to keys are in objs
  1558. # Find the order in which iterkeys sees the keys.
  1559. objs = list(d.keys())
  1560. # Reverse it, so that the iteration implementation of __delitem__
  1561. # has to keep looping to find the first object we delete.
  1562. objs.reverse()
  1563. # Turn on mutation in C.__eq__. The first time through the loop,
  1564. # under the iterkeys() business the first comparison will delete
  1565. # the last item iterkeys() would see, and that causes a
  1566. # RuntimeError: dictionary changed size during iteration
  1567. # when the iterkeys() loop goes around to try comparing the next
  1568. # key. After this was fixed, it just deletes the last object *our*
  1569. # "for o in obj" loop would have gotten to.
  1570. mutate = True
  1571. count = 0
  1572. for o in objs:
  1573. count += 1
  1574. del d[o]
  1575. gc_collect() # For PyPy or other GCs.
  1576. self.assertEqual(len(d), 0)
  1577. self.assertEqual(count, 2)
  1578. def test_make_weak_valued_dict_repr(self):
  1579. dict = weakref.WeakValueDictionary()
  1580. self.assertRegex(repr(dict), '<WeakValueDictionary at 0x.*>')
  1581. def test_make_weak_keyed_dict_repr(self):
  1582. dict = weakref.WeakKeyDictionary()
  1583. self.assertRegex(repr(dict), '<WeakKeyDictionary at 0x.*>')
  1584. @threading_helper.requires_working_threading()
  1585. def test_threaded_weak_valued_setdefault(self):
  1586. d = weakref.WeakValueDictionary()
  1587. with collect_in_thread():
  1588. for i in range(100000):
  1589. x = d.setdefault(10, RefCycle())
  1590. self.assertIsNot(x, None) # we never put None in there!
  1591. del x
  1592. @threading_helper.requires_working_threading()
  1593. def test_threaded_weak_valued_pop(self):
  1594. d = weakref.WeakValueDictionary()
  1595. with collect_in_thread():
  1596. for i in range(100000):
  1597. d[10] = RefCycle()
  1598. x = d.pop(10, 10)
  1599. self.assertIsNot(x, None) # we never put None in there!
  1600. @threading_helper.requires_working_threading()
  1601. def test_threaded_weak_valued_consistency(self):
  1602. # Issue #28427: old keys should not remove new values from
  1603. # WeakValueDictionary when collecting from another thread.
  1604. d = weakref.WeakValueDictionary()
  1605. with collect_in_thread():
  1606. for i in range(200000):
  1607. o = RefCycle()
  1608. d[10] = o
  1609. # o is still alive, so the dict can't be empty
  1610. self.assertEqual(len(d), 1)
  1611. o = None # lose ref
  1612. def check_threaded_weak_dict_copy(self, type_, deepcopy):
  1613. # `type_` should be either WeakKeyDictionary or WeakValueDictionary.
  1614. # `deepcopy` should be either True or False.
  1615. exc = []
  1616. class DummyKey:
  1617. def __init__(self, ctr):
  1618. self.ctr = ctr
  1619. class DummyValue:
  1620. def __init__(self, ctr):
  1621. self.ctr = ctr
  1622. def dict_copy(d, exc):
  1623. try:
  1624. if deepcopy is True:
  1625. _ = copy.deepcopy(d)
  1626. else:
  1627. _ = d.copy()
  1628. except Exception as ex:
  1629. exc.append(ex)
  1630. def pop_and_collect(lst):
  1631. gc_ctr = 0
  1632. while lst:
  1633. i = random.randint(0, len(lst) - 1)
  1634. gc_ctr += 1
  1635. lst.pop(i)
  1636. if gc_ctr % 10000 == 0:
  1637. gc.collect() # just in case
  1638. self.assertIn(type_, (weakref.WeakKeyDictionary, weakref.WeakValueDictionary))
  1639. d = type_()
  1640. keys = []
  1641. values = []
  1642. # Initialize d with many entries
  1643. for i in range(70000):
  1644. k, v = DummyKey(i), DummyValue(i)
  1645. keys.append(k)
  1646. values.append(v)
  1647. d[k] = v
  1648. del k
  1649. del v
  1650. t_copy = threading.Thread(target=dict_copy, args=(d, exc,))
  1651. if type_ is weakref.WeakKeyDictionary:
  1652. t_collect = threading.Thread(target=pop_and_collect, args=(keys,))
  1653. else: # weakref.WeakValueDictionary
  1654. t_collect = threading.Thread(target=pop_and_collect, args=(values,))
  1655. t_copy.start()
  1656. t_collect.start()
  1657. t_copy.join()
  1658. t_collect.join()
  1659. # Test exceptions
  1660. if exc:
  1661. raise exc[0]
  1662. @threading_helper.requires_working_threading()
  1663. def test_threaded_weak_key_dict_copy(self):
  1664. # Issue #35615: Weakref keys or values getting GC'ed during dict
  1665. # copying should not result in a crash.
  1666. self.check_threaded_weak_dict_copy(weakref.WeakKeyDictionary, False)
  1667. @threading_helper.requires_working_threading()
  1668. def test_threaded_weak_key_dict_deepcopy(self):
  1669. # Issue #35615: Weakref keys or values getting GC'ed during dict
  1670. # copying should not result in a crash.
  1671. self.check_threaded_weak_dict_copy(weakref.WeakKeyDictionary, True)
  1672. @threading_helper.requires_working_threading()
  1673. def test_threaded_weak_value_dict_copy(self):
  1674. # Issue #35615: Weakref keys or values getting GC'ed during dict
  1675. # copying should not result in a crash.
  1676. self.check_threaded_weak_dict_copy(weakref.WeakValueDictionary, False)
  1677. @threading_helper.requires_working_threading()
  1678. def test_threaded_weak_value_dict_deepcopy(self):
  1679. # Issue #35615: Weakref keys or values getting GC'ed during dict
  1680. # copying should not result in a crash.
  1681. self.check_threaded_weak_dict_copy(weakref.WeakValueDictionary, True)
  1682. @support.cpython_only
  1683. def test_remove_closure(self):
  1684. d = weakref.WeakValueDictionary()
  1685. self.assertIsNone(d._remove.__closure__)
  1686. from test import mapping_tests
  1687. class WeakValueDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
  1688. """Check that WeakValueDictionary conforms to the mapping protocol"""
  1689. __ref = {"key1":Object(1), "key2":Object(2), "key3":Object(3)}
  1690. type2test = weakref.WeakValueDictionary
  1691. def _reference(self):
  1692. return self.__ref.copy()
  1693. class WeakKeyDictionaryTestCase(mapping_tests.BasicTestMappingProtocol):
  1694. """Check that WeakKeyDictionary conforms to the mapping protocol"""
  1695. __ref = {Object("key1"):1, Object("key2"):2, Object("key3"):3}
  1696. type2test = weakref.WeakKeyDictionary
  1697. def _reference(self):
  1698. return self.__ref.copy()
  1699. class FinalizeTestCase(unittest.TestCase):
  1700. class A:
  1701. pass
  1702. def _collect_if_necessary(self):
  1703. # we create no ref-cycles so in CPython no gc should be needed
  1704. if sys.implementation.name != 'cpython':
  1705. support.gc_collect()
  1706. def test_finalize(self):
  1707. def add(x,y,z):
  1708. res.append(x + y + z)
  1709. return x + y + z
  1710. a = self.A()
  1711. res = []
  1712. f = weakref.finalize(a, add, 67, 43, z=89)
  1713. self.assertEqual(f.alive, True)
  1714. self.assertEqual(f.peek(), (a, add, (67,43), {'z':89}))
  1715. self.assertEqual(f(), 199)
  1716. self.assertEqual(f(), None)
  1717. self.assertEqual(f(), None)
  1718. self.assertEqual(f.peek(), None)
  1719. self.assertEqual(f.detach(), None)
  1720. self.assertEqual(f.alive, False)
  1721. self.assertEqual(res, [199])
  1722. res = []
  1723. f = weakref.finalize(a, add, 67, 43, 89)
  1724. self.assertEqual(f.peek(), (a, add, (67,43,89), {}))
  1725. self.assertEqual(f.detach(), (a, add, (67,43,89), {}))
  1726. self.assertEqual(f(), None)
  1727. self.assertEqual(f(), None)
  1728. self.assertEqual(f.peek(), None)
  1729. self.assertEqual(f.detach(), None)
  1730. self.assertEqual(f.alive, False)
  1731. self.assertEqual(res, [])
  1732. res = []
  1733. f = weakref.finalize(a, add, x=67, y=43, z=89)
  1734. del a
  1735. self._collect_if_necessary()
  1736. self.assertEqual(f(), None)
  1737. self.assertEqual(f(), None)
  1738. self.assertEqual(f.peek(), None)
  1739. self.assertEqual(f.detach(), None)
  1740. self.assertEqual(f.alive, False)
  1741. self.assertEqual(res, [199])
  1742. def test_arg_errors(self):
  1743. def fin(*args, **kwargs):
  1744. res.append((args, kwargs))
  1745. a = self.A()
  1746. res = []
  1747. f = weakref.finalize(a, fin, 1, 2, func=3, obj=4)
  1748. self.assertEqual(f.peek(), (a, fin, (1, 2), {'func': 3, 'obj': 4}))
  1749. f()
  1750. self.assertEqual(res, [((1, 2), {'func': 3, 'obj': 4})])
  1751. with self.assertRaises(TypeError):
  1752. weakref.finalize(a, func=fin, arg=1)
  1753. with self.assertRaises(TypeError):
  1754. weakref.finalize(obj=a, func=fin, arg=1)
  1755. self.assertRaises(TypeError, weakref.finalize, a)
  1756. self.assertRaises(TypeError, weakref.finalize)
  1757. def test_order(self):
  1758. a = self.A()
  1759. res = []
  1760. f1 = weakref.finalize(a, res.append, 'f1')
  1761. f2 = weakref.finalize(a, res.append, 'f2')
  1762. f3 = weakref.finalize(a, res.append, 'f3')
  1763. f4 = weakref.finalize(a, res.append, 'f4')
  1764. f5 = weakref.finalize(a, res.append, 'f5')
  1765. # make sure finalizers can keep themselves alive
  1766. del f1, f4
  1767. self.assertTrue(f2.alive)
  1768. self.assertTrue(f3.alive)
  1769. self.assertTrue(f5.alive)
  1770. self.assertTrue(f5.detach())
  1771. self.assertFalse(f5.alive)
  1772. f5() # nothing because previously unregistered
  1773. res.append('A')
  1774. f3() # => res.append('f3')
  1775. self.assertFalse(f3.alive)
  1776. res.append('B')
  1777. f3() # nothing because previously called
  1778. res.append('C')
  1779. del a
  1780. self._collect_if_necessary()
  1781. # => res.append('f4')
  1782. # => res.append('f2')
  1783. # => res.append('f1')
  1784. self.assertFalse(f2.alive)
  1785. res.append('D')
  1786. f2() # nothing because previously called by gc
  1787. expected = ['A', 'f3', 'B', 'C', 'f4', 'f2', 'f1', 'D']
  1788. self.assertEqual(res, expected)
  1789. def test_all_freed(self):
  1790. # we want a weakrefable subclass of weakref.finalize
  1791. class MyFinalizer(weakref.finalize):
  1792. pass
  1793. a = self.A()
  1794. res = []
  1795. def callback():
  1796. res.append(123)
  1797. f = MyFinalizer(a, callback)
  1798. wr_callback = weakref.ref(callback)
  1799. wr_f = weakref.ref(f)
  1800. del callback, f
  1801. self.assertIsNotNone(wr_callback())
  1802. self.assertIsNotNone(wr_f())
  1803. del a
  1804. self._collect_if_necessary()
  1805. self.assertIsNone(wr_callback())
  1806. self.assertIsNone(wr_f())
  1807. self.assertEqual(res, [123])
  1808. @classmethod
  1809. def run_in_child(cls):
  1810. def error():
  1811. # Create an atexit finalizer from inside a finalizer called
  1812. # at exit. This should be the next to be run.
  1813. g1 = weakref.finalize(cls, print, 'g1')
  1814. print('f3 error')
  1815. 1/0
  1816. # cls should stay alive till atexit callbacks run
  1817. f1 = weakref.finalize(cls, print, 'f1', _global_var)
  1818. f2 = weakref.finalize(cls, print, 'f2', _global_var)
  1819. f3 = weakref.finalize(cls, error)
  1820. f4 = weakref.finalize(cls, print, 'f4', _global_var)
  1821. assert f1.atexit == True
  1822. f2.atexit = False
  1823. assert f3.atexit == True
  1824. assert f4.atexit == True
  1825. def test_atexit(self):
  1826. prog = ('from test.test_weakref import FinalizeTestCase;'+
  1827. 'FinalizeTestCase.run_in_child()')
  1828. rc, out, err = script_helper.assert_python_ok('-c', prog)
  1829. out = out.decode('ascii').splitlines()
  1830. self.assertEqual(out, ['f4 foobar', 'f3 error', 'g1', 'f1 foobar'])
  1831. self.assertTrue(b'ZeroDivisionError' in err)
  1832. class ModuleTestCase(unittest.TestCase):
  1833. def test_names(self):
  1834. for name in ('ReferenceType', 'ProxyType', 'CallableProxyType',
  1835. 'WeakMethod', 'WeakSet', 'WeakKeyDictionary', 'WeakValueDictionary'):
  1836. obj = getattr(weakref, name)
  1837. if name != 'WeakSet':
  1838. self.assertEqual(obj.__module__, 'weakref')
  1839. self.assertEqual(obj.__name__, name)
  1840. self.assertEqual(obj.__qualname__, name)
  1841. libreftest = """ Doctest for examples in the library reference: weakref.rst
  1842. >>> from test.support import gc_collect
  1843. >>> import weakref
  1844. >>> class Dict(dict):
  1845. ... pass
  1846. ...
  1847. >>> obj = Dict(red=1, green=2, blue=3) # this object is weak referencable
  1848. >>> r = weakref.ref(obj)
  1849. >>> print(r() is obj)
  1850. True
  1851. >>> import weakref
  1852. >>> class Object:
  1853. ... pass
  1854. ...
  1855. >>> o = Object()
  1856. >>> r = weakref.ref(o)
  1857. >>> o2 = r()
  1858. >>> o is o2
  1859. True
  1860. >>> del o, o2
  1861. >>> gc_collect() # For PyPy or other GCs.
  1862. >>> print(r())
  1863. None
  1864. >>> import weakref
  1865. >>> class ExtendedRef(weakref.ref):
  1866. ... def __init__(self, ob, callback=None, **annotations):
  1867. ... super().__init__(ob, callback)
  1868. ... self.__counter = 0
  1869. ... for k, v in annotations.items():
  1870. ... setattr(self, k, v)
  1871. ... def __call__(self):
  1872. ... '''Return a pair containing the referent and the number of
  1873. ... times the reference has been called.
  1874. ... '''
  1875. ... ob = super().__call__()
  1876. ... if ob is not None:
  1877. ... self.__counter += 1
  1878. ... ob = (ob, self.__counter)
  1879. ... return ob
  1880. ...
  1881. >>> class A: # not in docs from here, just testing the ExtendedRef
  1882. ... pass
  1883. ...
  1884. >>> a = A()
  1885. >>> r = ExtendedRef(a, foo=1, bar="baz")
  1886. >>> r.foo
  1887. 1
  1888. >>> r.bar
  1889. 'baz'
  1890. >>> r()[1]
  1891. 1
  1892. >>> r()[1]
  1893. 2
  1894. >>> r()[0] is a
  1895. True
  1896. >>> import weakref
  1897. >>> _id2obj_dict = weakref.WeakValueDictionary()
  1898. >>> def remember(obj):
  1899. ... oid = id(obj)
  1900. ... _id2obj_dict[oid] = obj
  1901. ... return oid
  1902. ...
  1903. >>> def id2obj(oid):
  1904. ... return _id2obj_dict[oid]
  1905. ...
  1906. >>> a = A() # from here, just testing
  1907. >>> a_id = remember(a)
  1908. >>> id2obj(a_id) is a
  1909. True
  1910. >>> del a
  1911. >>> gc_collect() # For PyPy or other GCs.
  1912. >>> try:
  1913. ... id2obj(a_id)
  1914. ... except KeyError:
  1915. ... print('OK')
  1916. ... else:
  1917. ... print('WeakValueDictionary error')
  1918. OK
  1919. """
  1920. __test__ = {'libreftest' : libreftest}
  1921. def load_tests(loader, tests, pattern):
  1922. tests.addTest(doctest.DocTestSuite())
  1923. return tests
  1924. if __name__ == "__main__":
  1925. unittest.main()