66import threading
77import time
88from concurrent_collections import ConcurrentDictionary
9+ import pytest
910
1011
1112def test_concurrentdictionary_update_thread_safe ():
12- D = ConcurrentDictionary ({'x' : 0 })
13+ dic : ConcurrentDictionary [str , int ] = ConcurrentDictionary ()
14+ dic ["x" ] = 0
1315 def worker ():
1416 for _ in range (10000 ):
15- old = D ['x' ]
17+ old = dic ['x' ]
1618 time .sleep (0.00001 )
1719 # D.__setitem__('x', old + 1)
18- D .update_atomic ("x" , lambda v : v + 1 )
20+ dic .update_atomic ("x" , lambda v : v + 1 )
1921
2022 threads = [threading .Thread (target = worker ) for _ in range (8 )]
2123 for t in threads :
@@ -24,12 +26,12 @@ def worker():
2426 t .join ()
2527
2628 # The expected value is 8 * 10000 = 80000
27- assert D ['x' ] == 80000 , f"ConcurrentDictionary should be thread-safe, got { D ['x' ]} "
29+ assert dic ['x' ] == 80000 , f"ConcurrentDictionary should be thread-safe, got { dic ['x' ]} "
2830
2931
3032def test_concurrentdictionary_setdefault_thread_safe ():
31- D = ConcurrentDictionary ()
32- errors = []
33+ D : ConcurrentDictionary [ str , int ] = ConcurrentDictionary ()
34+ errors : list [ Exception ] = []
3335
3436 def worker ():
3537 for _ in range (10000 ):
@@ -49,8 +51,8 @@ def worker():
4951
5052
5153def test_concurrentdictionary_pop_thread_safe ():
52- D = ConcurrentDictionary ({'x' : 0 })
53- errors = []
54+ D : ConcurrentDictionary [ str , int ] = ConcurrentDictionary ({'x' : 0 })
55+ errors : list [ Exception ] = []
5456
5557 def worker ():
5658 for _ in range (1000 ):
@@ -71,8 +73,8 @@ def worker():
7173
7274
7375def test_concurrentdictionary_clear_thread_safe ():
74- D = ConcurrentDictionary ({i : i for i in range (100 )})
75- errors = []
76+ D : ConcurrentDictionary [ str , int ] = ConcurrentDictionary ({i : i for i in range (100 )})
77+ errors : list [ Exception ] = []
7678
7779 def worker ():
7880 for _ in range (100 ):
@@ -90,23 +92,7 @@ def worker():
9092
9193 # No thread safety errors should occur
9294 assert not errors , f"Thread safety errors occurred: { errors } "
95+
9396
94-
9597if __name__ == "__main__" :
96- import types
97-
98- # Collect all functions in globals() that start with 'test_' and are functions
99- test_functions = [
100- func for name , func in globals ().items ()
101- if name .startswith ("test_" ) and isinstance (func , types .FunctionType )
102- ]
103- failed = 0
104- for func in test_functions :
105- try :
106- print (f"Running { func .__name__ } ..." )
107- func ()
108- except Exception as e :
109- failed += 1
110- print (f"***\n FAILED: { func .__name__ } : { e } \n ***" )
111-
112- print (f"\n { len (test_functions ) - failed } passed, { failed } failed." )
98+ pytest .main ([__file__ ])
0 commit comments