| 1 |
###################################################################### |
| 2 |
# |
| 3 |
# File: test/unit/helpers.py |
| 4 |
# |
| 5 |
# Copyright 2023 Backblaze Inc. All Rights Reserved. |
| 6 |
# |
| 7 |
# License https://www.backblaze.com/using_b2_code.html |
| 8 |
# |
| 9 |
###################################################################### |
| 10 |
import concurrent.futures |
| 11 |
import sys |
| 12 |
|
| 13 |
|
| 14 |
class RunOrDieExecutor(concurrent.futures.ThreadPoolExecutor): |
| 15 |
""" |
| 16 |
Deadly ThreadPoolExecutor, which ensures all task are quickly closed before exiting. |
| 17 |
|
| 18 |
Only really usable in tests. |
| 19 |
""" |
| 20 |
|
| 21 |
def __exit__(self, exc_type, exc_val, exc_tb): |
| 22 |
self.shutdown(wait=False, cancel_futures=True) |
| 23 |
return super().__exit__(exc_type, exc_val, exc_tb) |
| 24 |
|
| 25 |
if sys.version_info < (3, 9): # shutdown(cancel_futures=True) is Python 3.9+ |
| 26 |
|
| 27 |
def __init__(self, *args, **kwargs): |
| 28 |
super().__init__(*args, **kwargs) |
| 29 |
self._futures = [] |
| 30 |
|
| 31 |
def shutdown(self, wait=True, cancel_futures=False): |
| 32 |
if cancel_futures: |
| 33 |
for future in self._futures: |
| 34 |
future.cancel() |
| 35 |
super().shutdown(wait=wait) |
| 36 |
|
| 37 |
def submit(self, *args, **kwargs): |
| 38 |
future = super().submit(*args, **kwargs) |
| 39 |
self._futures.append(future) |
| 40 |
return future |