From afa147b1dc80419b4aac0a532f7fb6b009475a78 Mon Sep 17 00:00:00 2001 From: Leavers Date: Wed, 27 Dec 2023 18:56:56 +0800 Subject: [PATCH] test: adapt to github win runner --- tests/conftest.py | 22 +++++++++++++++++++++- tests/test_async.py | 5 ++--- tests/test_thread.py | 11 ++++------- 3 files changed, 27 insertions(+), 11 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index 0297cfd..a128daf 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,7 +1,27 @@ +import time from typing import Union from flexexecutor import AsyncPoolExecutor, ThreadPoolExecutor +AnyPoolExecutor = Union[AsyncPoolExecutor, ThreadPoolExecutor] -def alive_threads(executor: Union[AsyncPoolExecutor, ThreadPoolExecutor]): + +def alive_threads(executor: AnyPoolExecutor): return [t for t in executor._threads if t.is_alive()] + + +def wait_for_alive_threads( + executor: AnyPoolExecutor, + expect: int, + timeout: float, +) -> int: + t = -1 + tick = time.monotonic() + while True: + t = len(alive_threads(executor)) + if t == expect: + break + if time.monotonic() - tick > timeout: + break + time.sleep(0.05) + return t diff --git a/tests/test_async.py b/tests/test_async.py index 7611e71..38e11e5 100644 --- a/tests/test_async.py +++ b/tests/test_async.py @@ -7,7 +7,7 @@ from pytest_mock import MockerFixture from flexexecutor import AsyncPoolExecutor -from tests.conftest import alive_threads +from tests.conftest import alive_threads, wait_for_alive_threads async def simple_return(n: int = 1): @@ -141,8 +141,7 @@ def test_finite_timeout(): assert len(alive_threads(executor)) == 1 future.result() - time.sleep(0.2) - assert len(alive_threads(executor)) == 0 + assert wait_for_alive_threads(executor, 0, 0.5) == 0 executor.submit(simple_delay_return, wait=0.1) assert len(alive_threads(executor)) == 1 diff --git a/tests/test_thread.py b/tests/test_thread.py index 69d7560..bb394ac 100644 --- a/tests/test_thread.py +++ b/tests/test_thread.py @@ -6,7 +6,7 @@ from pytest_mock import MockerFixture from flexexecutor import ThreadPoolExecutor -from tests.conftest import alive_threads +from tests.conftest import alive_threads, wait_for_alive_threads def simple_delay_return(n: int = 1, wait: float = 0.1): @@ -128,8 +128,7 @@ def test_worker_alive(): assert len(alive_threads(executor)) == 0 executor.submit(lambda: 1) assert len(alive_threads(executor)) == 1 - time.sleep(0.5) - assert len(alive_threads(executor)) == 0 + assert wait_for_alive_threads(executor, 0, 0.5) == 0 def test_max_workers(): @@ -147,11 +146,9 @@ def test_finite_timeout(): assert len(alive_threads(executor)) == 1 future.result() - time.sleep(0.5) - assert len(alive_threads(executor)) == 0 - + assert wait_for_alive_threads(executor, 0, 0.5) == 0 executor.submit(lambda: time.sleep(0.1)) - assert len(alive_threads(executor)) == 1 + assert wait_for_alive_threads(executor, 1, 0.1) == 1 assert len(alive_threads(executor)) == 0