33# for complete details.
44
55
6- import contextlib
76import sys
87import threading
98
1211from cryptography .exceptions import AlreadyFinalized
1312from cryptography .hazmat .primitives import padding
1413
15- from .utils import IS_FREETHREADED_BUILD , run_threaded
14+ from .utils import IS_FREETHREADED_BUILD , SwitchIntervalContext , run_threaded
15+
16+ SHOULD_LOCK_BYTESTRING = (
17+ IS_FREETHREADED_BUILD or
18+ sys .version_info < (3 , 10 ) or
19+ sys .implementation .name == "pypy"
20+ )
1621
1722
1823class TestPKCS7 :
@@ -248,20 +253,6 @@ def test_bytearray(self):
248253 assert final == unpadded + unpadded
249254
250255
251- class SwitchIntervalContext (contextlib .ContextDecorator ):
252- def __init__ (self , interval ):
253- self .interval = interval
254-
255- def __enter__ (self ):
256- self .orig_interval = sys .getswitchinterval ()
257- sys .setswitchinterval (self .interval )
258- return self
259-
260- def __exit__ (self , * exc ):
261- sys .setswitchinterval (self .orig_interval )
262- return False
263-
264-
265256@SwitchIntervalContext (0.0000001 )
266257@pytest .mark .parametrize (
267258 "algorithm" ,
@@ -292,8 +283,8 @@ def pad_in_chunks(chunk_size):
292283 while index < len (data ):
293284 try :
294285 new_content = padder .update (data [index : index + chunk_size ])
295- if IS_FREETHREADED_BUILD or sys . version_info < ( 3 , 10 ) :
296- # appending to a bytestring is racey on 3.13t and < 3.10
286+ if SHOULD_LOCK_BYTESTRING :
287+ # appending to a bytestring is racey on some Pythons
297288 lock .acquire ()
298289 calculated_pad += new_content
299290 lock .release ()
@@ -314,7 +305,7 @@ def prepare_args(threadnum):
314305 assert chunk_size % len (chunk ) == 0
315306 return (chunk_size ,)
316307
317- run_threaded (num_threads , chunk , pad_in_chunks , prepare_args )
308+ run_threaded (num_threads , pad_in_chunks , prepare_args )
318309
319310 calculated_pad += padder .finalize ()
320311 assert expected_pad == calculated_pad
@@ -349,8 +340,8 @@ def unpad_in_chunks():
349340 while index < num_repeats :
350341 try :
351342 new_content = padder .update (block )
352- if IS_FREETHREADED_BUILD or sys . version_info < ( 3 , 10 ) :
353- # appending to a bytestring is racey on 3.13t and < 3.10
343+ if SHOULD_LOCK_BYTESTRING :
344+ # appending to a bytestring is racey on some Pythons
354345 lock .acquire ()
355346 calculated_unpadded_message += new_content
356347 lock .release ()
@@ -365,7 +356,7 @@ def unpad_in_chunks():
365356 continue
366357 index += 1
367358
368- run_threaded (num_threads , chunk , unpad_in_chunks , lambda x : tuple ())
359+ run_threaded (num_threads , unpad_in_chunks , lambda x : tuple ())
369360
370361 calculated_unpadded_message += padder .finalize ()
371362 assert expected_unpadded_message == calculated_unpadded_message
0 commit comments