|
| 1 | +import asyncio |
| 2 | +from typing import AsyncIterator |
| 3 | + |
| 4 | +import pytest |
| 5 | +import pytest_asyncio |
| 6 | + |
| 7 | +from dispatcherd.protocols import DispatcherMain |
| 8 | +from dispatcherd.testing.asyncio import adispatcher_service |
| 9 | + |
| 10 | + |
| 11 | +@pytest.fixture(scope='session') |
| 12 | +def order_config(): |
| 13 | + return { |
| 14 | + "version": 2, |
| 15 | + "service": { |
| 16 | + "pool_kwargs": {"min_workers": 2, "max_workers": 2}, |
| 17 | + "main_kwargs": {"node_id": "order-test"}, |
| 18 | + }, |
| 19 | + } |
| 20 | + |
| 21 | + |
| 22 | +@pytest_asyncio.fixture |
| 23 | +async def aorder_dispatcher(order_config) -> AsyncIterator[DispatcherMain]: |
| 24 | + async with adispatcher_service(order_config) as dispatcher: |
| 25 | + yield dispatcher |
| 26 | + |
| 27 | + |
| 28 | +@pytest.mark.asyncio |
| 29 | +async def test_workers_reorder_and_dispatch_longest_idle(aorder_dispatcher): |
| 30 | + pool = aorder_dispatcher.pool |
| 31 | + assert list(pool.workers.workers.keys()) == [0, 1] |
| 32 | + |
| 33 | + pool.events.work_cleared.clear() |
| 34 | + await aorder_dispatcher.process_message({ |
| 35 | + "task": "tests.data.methods.sleep_function", |
| 36 | + "kwargs": {"seconds": 0.1}, |
| 37 | + "uuid": "t1", |
| 38 | + }) |
| 39 | + await aorder_dispatcher.process_message({ |
| 40 | + "task": "tests.data.methods.sleep_function", |
| 41 | + "kwargs": {"seconds": 0.05}, |
| 42 | + "uuid": "t2", |
| 43 | + }) |
| 44 | + await asyncio.wait_for(pool.events.work_cleared.wait(), timeout=1) |
| 45 | + |
| 46 | + assert list(pool.workers.workers.keys()) == [1, 0] |
| 47 | + |
| 48 | + pool.events.work_cleared.clear() |
| 49 | + await aorder_dispatcher.process_message({ |
| 50 | + "task": "tests.data.methods.sleep_function", |
| 51 | + "kwargs": {"seconds": 0.01}, |
| 52 | + "uuid": "t3", |
| 53 | + }) |
| 54 | + await asyncio.sleep(0.01) |
| 55 | + assert pool.workers.get_by_id(1).current_task["uuid"] == "t3" |
| 56 | + assert pool.workers.get_by_id(0).current_task is None |
| 57 | + await asyncio.wait_for(pool.events.work_cleared.wait(), timeout=1) |
| 58 | + |
| 59 | + pool.events.work_cleared.clear() |
| 60 | + await aorder_dispatcher.process_message({ |
| 61 | + "task": "tests.data.methods.sleep_function", |
| 62 | + "kwargs": {"seconds": 0.01}, |
| 63 | + "uuid": "t4", |
| 64 | + }) |
| 65 | + await asyncio.sleep(0.01) |
| 66 | + assert pool.workers.get_by_id(0).current_task["uuid"] == "t4" |
| 67 | + await asyncio.wait_for(pool.events.work_cleared.wait(), timeout=1) |
| 68 | + |
| 69 | + assert list(pool.workers.workers.keys()) == [1, 0] |
0 commit comments