2 from doctest
import DocTestSuite
3 from test
import test_support
11 def target(local
, weaklist
):
14 weaklist
.append(weakref
.ref(weak
))
16 class ThreadingLocalTest(unittest
.TestCase
):
18 def test_local_refs(self
):
23 def _local_refs(self
, n
):
24 local
= threading
.local()
27 t
= threading
.Thread(target
=target
, args
=(local
, weaklist
))
33 self
.assertEqual(len(weaklist
), n
)
35 # XXX threading.local keeps the local of the last stopped thread alive.
36 deadlist
= [weak
for weak
in weaklist
if weak() is None]
37 self
.assertEqual(len(deadlist
), n
-1)
39 # Assignment to the same thread local frees it sometimes (!)
40 local
.someothervar
= None
42 deadlist
= [weak
for weak
in weaklist
if weak() is None]
43 self
.assertTrue(len(deadlist
) in (n
-1, n
), (n
, len(deadlist
)))
45 def test_derived(self
):
46 # Issue 3088: if there is a threads switch inside the __init__
47 # of a threading.local derived class, the per-thread dictionary
48 # is created but not correctly set on the object.
49 # The first member set may be bogus.
51 class Local(threading
.local
):
58 # Simply check that the variable is correctly set
59 self
.assertEqual(local
.x
, i
)
63 t
= threading
.Thread(target
=f
, args
=(i
,))
70 def test_derived_cycle_dealloc(self
):
71 # http://bugs.python.org/issue6990
72 class Local(threading
.local
):
76 e1
= threading
.Event()
77 e2
= threading
.Event()
80 # 1) Involve Local in a cycle
85 # 2) GC the cycle (triggers threadmodule.c::local_clear
86 # before local_dealloc)
92 # 4) New Locals should be empty
93 passed
[0] = all(not hasattr(local
, 'foo') for local
in locals)
95 t
= threading
.Thread(target
=f
)
99 # 3) New Locals should recycle the original's address. Creating
100 # them in the thread overwrites the thread state and avoids the
102 locals = [Local() for i
in range(10)]
106 self
.assertTrue(passed
[0])
110 suite
= unittest
.TestSuite()
111 suite
.addTest(DocTestSuite('_threading_local'))
112 suite
.addTest(unittest
.makeSuite(ThreadingLocalTest
))
115 from thread
import _local
119 import _threading_local
120 local_orig
= _threading_local
.local
122 _threading_local
.local
= _local
124 _threading_local
.local
= local_orig
125 suite
.addTest(DocTestSuite('_threading_local',
126 setUp
=setUp
, tearDown
=tearDown
)
129 test_support
.run_unittest(suite
)
131 if __name__
== '__main__':