Skip to content
Snippets Groups Projects
Commit c9a92380 authored by Piotr Maślanka's avatar Piotr Maślanka
Browse files

more coverage + add timeout to join

parent 6b5e42ec
No related branches found
No related tags found
No related merge requests found
......@@ -2,3 +2,4 @@
* added `MetricDataCollection.remove_internals`
* added `whereis`
* added `timeout` to `ThreadCollection.join`
......@@ -2,6 +2,8 @@ import threading
import typing as tp
from threading import Thread
from satella.exceptions import WouldWaitMore
class ThreadCollection:
"""
......@@ -116,14 +118,21 @@ class ThreadCollection:
pass
return self
def join(self) -> 'ThreadCollection':
def join(self, timeout: tp.Optional[float] = None) -> 'ThreadCollection':
"""
Join all threads
:param timeout: maximum time in seconds to wait for the threads to terminate.
Note that the timeout will be applied to each thread in sequence, so this
can block for up to thread_count*timeout seconds. Default value of
None means wait as long as it's necessary.
:returns: this thread collection instance
:raises WouldWaitMore: one of the threads failed to terminate
"""
for thread in self.threads:
thread.join()
thread.join(timeout=timeout)
if thread.is_alive():
raise WouldWaitMore('Thread failed to terminate')
return self
def is_alive(self) -> bool:
......
......@@ -29,17 +29,21 @@ class TestConcurrent(unittest.TestCase):
def run(self):
nonlocal dct
dct[self.a] = True
if self.a == 6:
time.sleep(5)
self.assertGreaterEqual(len(ThreadCollection.get_currently_running()), 1)
tc = ThreadCollection.from_class(Threading, [2, 3, 4])
tc.daemon = False
self.assertFalse(tc.is_alive())
self.assertEqual(len(tc), 3)
self.assertFalse(tc.daemon)
self.assertEqual(len(tc.get_currently_running()), 0)
for t in tc:
self.assertIsInstance(t, Threading)
tc.append(Threading(5)).add(Threading(6))
tc.start().terminate().join()
tc.start()
self.assertRaises(WouldWaitMore, lambda: tc.join(2))
tc.terminate().join()
self.assertEqual(dct, {2: True, 3: True, 4: True, 5: True, 6: True})
def test_cancellable_callback(self):
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment