Skip to content

Commit ad344a4

Browse files
committed
Update remaining free-threading library tests for Python 3.15
Extract the six canonical library-only modules from #9439. Regenerated with scripts/update_lib from CPython d220409a13b77de7a6c30abe16ea90db01528edc. Assisted-by: OpenAI Codex: model version unavailable
1 parent 84d7afc commit ad344a4

6 files changed

Lines changed: 613 additions & 0 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import unittest
2+
3+
from test.support import threading_helper
4+
5+
import cProfile
6+
import pstats
7+
8+
9+
NTHREADS = 10
10+
INSERT_PER_THREAD = 1000
11+
12+
13+
@threading_helper.requires_working_threading()
14+
class TestCProfile(unittest.TestCase):
15+
def test_cprofile_racing_list_insert(self):
16+
def list_insert(lst):
17+
for i in range(INSERT_PER_THREAD):
18+
lst.insert(0, i)
19+
20+
lst = []
21+
22+
with cProfile.Profile() as pr:
23+
threading_helper.run_concurrently(
24+
worker_func=list_insert, nthreads=NTHREADS, args=(lst,)
25+
)
26+
pr.create_stats()
27+
ps = pstats.Stats(pr)
28+
stats_profile = ps.get_stats_profile()
29+
list_insert_profile = stats_profile.func_profiles[
30+
"<method 'insert' of 'list' objects>"
31+
]
32+
# Even though there is no explicit recursive call to insert,
33+
# cProfile may record some calls as recursive due to limitations
34+
# in its handling of multithreaded programs. This issue is not
35+
# directly related to FT Python itself; however, it tends to be
36+
# more noticeable when using FT Python. Therefore, consider only
37+
# the calls section and disregard the recursive part.
38+
list_insert_ncalls = list_insert_profile.ncalls.split("/")[0]
39+
self.assertEqual(
40+
int(list_insert_ncalls), NTHREADS * INSERT_PER_THREAD
41+
)
42+
43+
self.assertEqual(len(lst), NTHREADS * INSERT_PER_THREAD)
Lines changed: 200 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,200 @@
1+
import codecs
2+
import io
3+
import _pyio as pyio
4+
import threading
5+
from unittest import TestCase
6+
from test.support import threading_helper
7+
from test.support.threading_helper import run_concurrently
8+
from random import randint
9+
from sys import getsizeof
10+
11+
threading_helper.requires_working_threading(module=True)
12+
13+
14+
class ThreadSafetyMixin:
15+
# Test pretty much everything that can break under free-threading.
16+
# Non-deterministic, but at least one of these things will fail if
17+
# BytesIO object is not free-thread safe.
18+
19+
def check(self, funcs, *args):
20+
barrier = threading.Barrier(len(funcs))
21+
threads = []
22+
23+
for func in funcs:
24+
thread = threading.Thread(target=func, args=(barrier, *args))
25+
26+
threads.append(thread)
27+
28+
with threading_helper.start_threads(threads):
29+
pass
30+
31+
@threading_helper.requires_working_threading()
32+
@threading_helper.reap_threads
33+
def test_free_threading(self):
34+
"""Test for segfaults and aborts."""
35+
36+
def write(barrier, b, *ignore):
37+
barrier.wait()
38+
try: b.write(b'0' * randint(100, 1000))
39+
except ValueError: pass # ignore write fail to closed file
40+
41+
def writelines(barrier, b, *ignore):
42+
barrier.wait()
43+
b.write(b'0\n' * randint(100, 1000))
44+
45+
def truncate(barrier, b, *ignore):
46+
barrier.wait()
47+
try: b.truncate(0)
48+
except BufferError: pass # ignore exported buffer
49+
50+
def read(barrier, b, *ignore):
51+
barrier.wait()
52+
b.read()
53+
54+
def read1(barrier, b, *ignore):
55+
barrier.wait()
56+
b.read1()
57+
58+
def readline(barrier, b, *ignore):
59+
barrier.wait()
60+
b.readline()
61+
62+
def readlines(barrier, b, *ignore):
63+
barrier.wait()
64+
b.readlines()
65+
66+
def readinto(barrier, b, into, *ignore):
67+
barrier.wait()
68+
b.readinto(into)
69+
70+
def close(barrier, b, *ignore):
71+
barrier.wait()
72+
b.close()
73+
74+
def getvalue(barrier, b, *ignore):
75+
barrier.wait()
76+
b.getvalue()
77+
78+
def getbuffer(barrier, b, *ignore):
79+
barrier.wait()
80+
b.getbuffer()
81+
82+
def iter(barrier, b, *ignore):
83+
barrier.wait()
84+
list(b)
85+
86+
def getstate(barrier, b, *ignore):
87+
barrier.wait()
88+
b.__getstate__()
89+
90+
def setstate(barrier, b, st, *ignore):
91+
barrier.wait()
92+
b.__setstate__(st)
93+
94+
def sizeof(barrier, b, *ignore):
95+
barrier.wait()
96+
getsizeof(b)
97+
98+
self.check([write] * 10, self.ioclass())
99+
self.check([writelines] * 10, self.ioclass())
100+
self.check([write] * 10 + [truncate] * 10, self.ioclass())
101+
self.check([truncate] + [read] * 10, self.ioclass(b'0\n'*204800))
102+
self.check([truncate] + [read1] * 10, self.ioclass(b'0\n'*204800))
103+
self.check([truncate] + [readline] * 10, self.ioclass(b'0\n'*20480))
104+
self.check([truncate] + [readlines] * 10, self.ioclass(b'0\n'*20480))
105+
self.check([truncate] + [readinto] * 10, self.ioclass(b'0\n'*204800), bytearray(b'0\n'*204800))
106+
self.check([close] + [write] * 10, self.ioclass())
107+
self.check([truncate] + [getvalue] * 10, self.ioclass(b'0\n'*204800))
108+
self.check([truncate] + [getbuffer] * 10, self.ioclass(b'0\n'*204800))
109+
self.check([truncate] + [iter] * 10, self.ioclass(b'0\n'*20480))
110+
self.check([truncate] + [getstate] * 10, self.ioclass(b'0\n'*204800))
111+
state = self.ioclass(b'123').__getstate__()
112+
self.check([truncate] + [setstate] * 10, self.ioclass(b'0\n'*204800), state)
113+
self.check([truncate] + [sizeof] * 10, self.ioclass(b'0\n'*204800))
114+
115+
# no tests for seek or tell because they don't break anything
116+
117+
class CBytesIOTest(ThreadSafetyMixin, TestCase):
118+
ioclass = io.BytesIO
119+
120+
@threading_helper.requires_working_threading()
121+
@threading_helper.reap_threads
122+
def test_concurrent_whole_buffer_read_and_resize(self):
123+
shared = self.ioclass(b"x" * 64)
124+
writers = 2
125+
readers = 8
126+
loops = 2000
127+
barrier = threading.Barrier(writers + readers)
128+
129+
def writer():
130+
barrier.wait()
131+
for i in range(loops):
132+
shared.seek(0)
133+
shared.write(b"a" * (64 + (i & 63)))
134+
135+
def reader():
136+
barrier.wait()
137+
for _ in range(loops):
138+
shared.seek(0)
139+
shared.read()
140+
shared.seek(0)
141+
shared.getvalue()
142+
143+
threads = [threading.Thread(target=writer) for _ in range(writers)]
144+
threads += [threading.Thread(target=reader) for _ in range(readers)]
145+
with threading_helper.start_threads(threads):
146+
pass
147+
148+
class PyBytesIOTest(ThreadSafetyMixin, TestCase):
149+
ioclass = pyio.BytesIO
150+
151+
152+
class IncrementalNewlineDecoderTest(TestCase):
153+
def make_decoder(self):
154+
utf8_decoder = codecs.getincrementaldecoder('utf-8')()
155+
return io.IncrementalNewlineDecoder(utf8_decoder, translate=True)
156+
157+
def test_concurrent_reset(self):
158+
decoder = self.make_decoder()
159+
160+
def worker():
161+
for _ in range(100):
162+
decoder.reset()
163+
164+
run_concurrently(worker_func=worker, nthreads=2)
165+
166+
def test_concurrent_decode(self):
167+
decoder = self.make_decoder()
168+
169+
def worker():
170+
for _ in range(100):
171+
decoder.decode(b"line\r\n", final=False)
172+
173+
run_concurrently(worker_func=worker, nthreads=2)
174+
175+
def test_concurrent_getstate_setstate(self):
176+
decoder = self.make_decoder()
177+
state = decoder.getstate()
178+
179+
def getstate_worker():
180+
for _ in range(100):
181+
decoder.getstate()
182+
183+
def setstate_worker():
184+
for _ in range(100):
185+
decoder.setstate(state)
186+
187+
run_concurrently([getstate_worker] * 2 + [setstate_worker] * 2)
188+
189+
def test_concurrent_decode_and_reset(self):
190+
decoder = self.make_decoder()
191+
192+
def decode_worker():
193+
for _ in range(100):
194+
decoder.decode(b"line\r\n", final=False)
195+
196+
def reset_worker():
197+
for _ in range(100):
198+
decoder.reset()
199+
200+
run_concurrently([decode_worker] * 2 + [reset_worker] * 2)
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
import threading
2+
import unittest
3+
from test import support
4+
5+
# The race conditions these tests were written for only happen every now and
6+
# then, even with the current numbers. To find rare race conditions, bumping
7+
# these up will help, but it makes the test runtime highly variable under
8+
# free-threading. Overhead is much higher under ThreadSanitizer, but it's
9+
# also much better at detecting certain races, so we don't need as many
10+
# items/threads.
11+
if support.check_sanitizer(thread=True):
12+
NUMITEMS = 1000
13+
NUMTHREADS = 2
14+
else:
15+
NUMITEMS = 5000
16+
NUMTHREADS = 5
17+
NUMMUTATORS = 2
18+
19+
class ContendedTupleIterationTest(unittest.TestCase):
20+
def make_testdata(self, n):
21+
return tuple(range(n))
22+
23+
def assert_iterator_results(self, results, expected):
24+
# Most iterators are not atomic (yet?) so they can skip or duplicate
25+
# items, but they should not invent new items (like the range
26+
# iterator currently does).
27+
extra_items = set(results) - set(expected)
28+
self.assertEqual(set(), extra_items)
29+
30+
def run_threads(self, func, *args, numthreads=NUMTHREADS):
31+
threads = []
32+
for _ in range(numthreads):
33+
t = threading.Thread(target=func, args=args)
34+
t.start()
35+
threads.append(t)
36+
return threads
37+
38+
def test_iteration(self):
39+
"""Test iteration over a shared container"""
40+
seq = self.make_testdata(NUMITEMS)
41+
results = []
42+
start = threading.Barrier(NUMTHREADS)
43+
def worker():
44+
idx = 0
45+
start.wait()
46+
for item in seq:
47+
idx += 1
48+
results.append(idx)
49+
threads = self.run_threads(worker)
50+
for t in threads:
51+
t.join()
52+
# Each thread has its own iterator, so results should be entirely predictable.
53+
self.assertEqual(results, [NUMITEMS] * NUMTHREADS)
54+
55+
def test_shared_iterator(self):
56+
"""Test iteration over a shared iterator"""
57+
seq = self.make_testdata(NUMITEMS)
58+
it = iter(seq)
59+
results = []
60+
start = threading.Barrier(NUMTHREADS)
61+
def worker():
62+
items = []
63+
start.wait()
64+
# We want a tight loop, so put items in the shared list at the end.
65+
for item in it:
66+
items.append(item)
67+
results.extend(items)
68+
threads = self.run_threads(worker)
69+
for t in threads:
70+
t.join()
71+
self.assert_iterator_results(results, seq)
72+
73+
class ContendedListIterationTest(ContendedTupleIterationTest):
74+
def make_testdata(self, n):
75+
return list(range(n))
76+
77+
def test_iteration_while_mutating(self):
78+
"""Test iteration over a shared mutating container."""
79+
seq = self.make_testdata(NUMITEMS)
80+
results = []
81+
start = threading.Barrier(NUMTHREADS + NUMMUTATORS)
82+
endmutate = threading.Event()
83+
def mutator():
84+
orig = seq[:]
85+
# Make changes big enough to cause resizing of the list, with
86+
# items shifted around for good measure.
87+
replacement = (orig * 3)[NUMITEMS//2:]
88+
start.wait()
89+
while not endmutate.is_set():
90+
seq.extend(replacement)
91+
seq[:0] = orig
92+
seq.__imul__(2)
93+
seq.extend(seq)
94+
seq[:] = orig
95+
def worker():
96+
items = []
97+
start.wait()
98+
# We want a tight loop, so put items in the shared list at the end.
99+
for item in seq:
100+
items.append(item)
101+
results.extend(items)
102+
mutators = ()
103+
try:
104+
threads = self.run_threads(worker)
105+
mutators = self.run_threads(mutator, numthreads=NUMMUTATORS)
106+
for t in threads:
107+
t.join()
108+
finally:
109+
endmutate.set()
110+
for m in mutators:
111+
m.join()
112+
self.assert_iterator_results(results, list(seq))
113+
114+
115+
class ContendedRangeIterationTest(ContendedTupleIterationTest):
116+
def make_testdata(self, n):
117+
return range(n)
118+
119+
def assert_iterator_results(self, results, expected):
120+
# Range iterators that are shared between threads will (right now)
121+
# sometimes produce items after the end of the range, sometimes
122+
# _far_ after the end of the range. That should be fixed, but for
123+
# now, let's just check they're integers that could have resulted
124+
# from stepping beyond the range bounds.
125+
extra_items = set(results) - set(expected)
126+
for item in extra_items:
127+
self.assertEqual((item - expected.start) % expected.step, 0)

0 commit comments

Comments
 (0)