Debian Codegraph @

tests/test_syncdict.py

raw symbols SCIP
1 from beaker.util import SyncDict, WeakValuedRegistry
2 import random, time, weakref
3 import threading
4
5 class Value(object):
6 values = {}
7
8 def do_something(self, id):
9 Value.values[id] = self
10
11 def stop_doing_something(self, id):
12 del Value.values[id]
13
14 mutex = threading.Lock()
15
16 def create(id):
17 assert not Value.values, "values still remain"
18 global totalcreates
19 totalcreates += 1
20 return Value()
21
22 def threadtest(s, id):
23 print("create thread %d starting" % id)
24
25 global running
26 global totalgets
27 while running:
28 try:
29 value = s.get('test', lambda: create(id))
30 value.do_something(id)
31 except Exception as e:
32 print("Error", e)
33 running = False
34 break
35 else:
36 totalgets += 1
37 time.sleep(random.random() * .01)
38 value.stop_doing_something(id)
39 del value
40 time.sleep(random.random() * .01)
41
42 def runtest(s):
43
44 global values
45 values = {}
46
47 global totalcreates
48 totalcreates = 0
49
50 global totalgets
51 totalgets = 0
52
53 global running
54 running = True
55
56 threads = []
57 for id_ in range(1, 20):
58 t = threading.Thread(target=threadtest, args=(s, id_))
59 t.start()
60 threads.append(t)
61
62 for i in range(0, 10):
63 if not running:
64 break
65 time.sleep(1)
66
67 failed = not running
68
69 running = False
70
71 for t in threads:
72 t.join()
73
74 assert not failed, "test failed"
75
76 print("total object creates %d" % totalcreates)
77 print("total object gets %d" % totalgets)
78
79
80 def test_dict():
81 # normal dictionary test, where we will remove the value
82 # periodically. the number of creates should be equal to
83 # the number of removes plus one.
84 print("\ntesting with normal dict")
85 runtest(SyncDict())
86
87
88 def test_weakdict():
89 print("\ntesting with weak dict")
90 runtest(WeakValuedRegistry())