-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_pynchronized.py
More file actions
executable file
·94 lines (70 loc) · 2.77 KB
/
Copy pathtest_pynchronized.py
File metadata and controls
executable file
·94 lines (70 loc) · 2.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#! /usr/bin/python3
import unittest
import time
from threading import Thread
from multiprocessing import Process
from pynchronized import synchronized, thread_synchronized
class TestStrategyUtils(unittest.TestCase):
def test_synchronized_class_in_thread(self):
self._test_synchronized_class(synchronized, Thread)
def test_synchronized_method_in_thread(self):
self._test_synchronized_method(synchronized, Thread)
def test_synchronized_class_in_process(self):
self._test_synchronized_class(synchronized, Process)
def test_synchronized_method_in_process(self):
self._test_synchronized_method(synchronized, Process)
def test_thread_synchronized_class_in_thread(self):
self._test_synchronized_class(thread_synchronized, Thread)
def test_thread_synchronized_method_in_thread(self):
self._test_synchronized_method(thread_synchronized, Thread)
def _test_synchronized_class(self, decorator, executor):
"""test if methods run sequentially in synchronized class"""
delay = 0.05 # time in seconds to measure if sequentially or concurrent
@decorator
class SyncClass:
def a(self):
time.sleep(delay)
def b(self):
time.sleep(delay)
c = SyncClass()
fns_to_run = [c.a, c.b, c.a]
executors = []
for m in fns_to_run:
executors.append(executor(target=m, daemon=True))
start = time.time()
for e in executors:
e.start()
for e in executors:
e.join()
end = time.time()
self.assertGreater(end - start, len(fns_to_run) * delay)
def _test_synchronized_method(self, decorator, executor):
"""test if synchronized methods run sequentially"""
delay = 0.05 # time in seconds to measure if sequentially or concurrent
class SyncClass:
@decorator
def sync_method(self):
time.sleep(delay)
def b(self):
time.sleep(delay)
c = SyncClass()
sync_fns_to_run = [c.sync_method, c.sync_method, c.sync_method]
other_fns_to_run = [c.b, c.b]
executors = []
for m in sync_fns_to_run:
executors.append(executor(target=m, daemon=True))
for m in other_fns_to_run:
executors.append(executor(target=m, daemon=True))
start = time.time()
for e in executors:
e.start()
for e in executors:
e.join()
end = time.time()
self.assertGreater(end - start, len(sync_fns_to_run) * delay)
self.assertLess(
end - start,
(len(sync_fns_to_run) + len(other_fns_to_run)) * delay,
)
if __name__ == '__main__':
unittest.main()