-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.py
143 lines (116 loc) · 4.59 KB
/
test.py
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
'''
Created on 2017/05/16
@author: sakurai
'''
from contextlib import closing
from multiprocessing.connection import Pipe
from multiprocessing.dummy import Pool
try:
from queue import Queue # Py3
except ImportError:
from Queue import Queue # Py2
from subprocess import Popen
import sys
import threading
import time
from unittest import main
from unittest import TestCase
from unittest import TestLoader
import warnings
from T800.winthread import TerminatableThread
from T800.winthread import ThreadTerminationWarning
class T800WinThreadTest(TestCase):
WAITSEC = 1
PYSCRIPT_SYS_EXIT = (
"import sys;"
"from T800.winthread import TerminatableThread as T;"
"t = T(target=sys.stdin.read);"
"t.start();"
"t.terminate();"
"sys.exit(0);"
)
def setUp(self):
warnings.simplefilter("ignore", category=ThreadTerminationWarning)
# Preserving current statuses
self.active_count = threading.active_count()
self.all_threads = threading.enumerate()
def tearDown(self):
# Comparing current statuses with preserved ones
self.assertEqual(self.active_count, threading.active_count())
self.assertEqual(set(self.all_threads), set(threading.enumerate()))
warnings.resetwarnings()
def _start_threads(self, target, num_threads):
"""Overwrite here when you reuse the test case with your own thread"""
threads = []
for _ in range(num_threads):
t = TerminatableThread(target=target)
t.start()
threads.append(t)
return threads
def _terminate_still_alive(self, threads):
"""Invoke terminate() method concurrently"""
with closing(Pool(len(threads) // 4)) as pool:
for t in filter(lambda t: t.is_alive(), threads):
pool.apply_async(t.terminate)
pool.join()
pool.terminate()
def assertNumAliveThreads(self, num_threads, threads, msg=None):
self.assertEqual(
num_threads, len([t for t in threads if t.is_alive()]), msg)
def test_terminate_method_with_Pipe(self, num_threads=50):
readable, writable = Pipe(duplex=False)
threads = self._start_threads(readable.recv_bytes, num_threads)
writable.send_bytes(b"spam")
time.sleep(self.WAITSEC)
self.assertNumAliveThreads(
num_threads - 1, threads, "No thread has ended, %r" % threads)
self._terminate_still_alive(threads)
for t in threads:
self.assertRaises(OSError, t.terminate)
self.assertNumAliveThreads(
0, threads, "Some threads are still alive, %r" % threads)
for i in range(num_threads):
data = ("%d" % i).encode("ascii")
writable.send_bytes(data)
self.assertEqual(data, readable.recv_bytes(),
"Someone seems to intercept pipe, %r" % threads)
def test_terminate_method_with_Queue(self, num_threads=50):
q = Queue()
threads = self._start_threads(q.get, num_threads)
q.put(None)
time.sleep(self.WAITSEC)
self.assertNumAliveThreads(
num_threads - 1, threads, "No thread has ended, %r" % threads)
self._terminate_still_alive(threads)
for t in threads:
self.assertRaises(OSError, t.terminate)
self.assertNumAliveThreads(
0, threads, "Some threads are still alive, %r" % threads)
for i in range(num_threads):
q.put(i)
self.assertEqual(i, q.get(timeout=self.WAITSEC),
"Someone seems to intercept queue, %r" % threads)
def test_terminate_method_with_join_method(self):
t1 = self._start_threads(sys.stdin.read, 1)[0]
t2 = self._start_threads(t1.join, 1)[0]
self.assertTrue(t2.is_alive(), t2) # t2 is blocked due to running t1
t1.terminate()
time.sleep(self.WAITSEC)
self.assertFalse(t2.is_alive(), t2) # t2 stops due to terminated t1
def test_terminate_method_with_sys_exit(self):
args = [sys.executable, "-W", "ignore", "-c", self.PYSCRIPT_SYS_EXIT]
p = Popen(args)
for _ in range(int(2 * self.WAITSEC + 1)):
returncode = p.poll()
if returncode is not None:
self.assertEqual(0, returncode, p)
break
else:
time.sleep(1)
else:
p.terminate()
self.fail("Python hasn't stopped expectedly, %r" % p)
def suite():
return TestLoader().loadTestsFromTestCase(T800WinThreadTest)
if __name__ == "__main__":
main(verbosity=2)