import time from threading import Event from unittest.mock import MagicMock, call, patch import fakeredis import pytest from bec_lib.redis_connector import RedisConnector from mx_bec.endpoints import QueueEndpoints from mx_bec.messages import MXQueueChangedMessage, MXTaskExecutionMessage from mx_bec.tasks import MxTaskQueue, RoleT, Server, TaskManager, task @pytest.fixture def connector(): conn = RedisConnector("localhost:1", redis_cls=lambda *_, **__: fakeredis.FakeRedis()) conn._managed_connection.flushall() yield conn conn.shutdown() @pytest.fixture def client(connector): client = MagicMock() client.connector = connector return client class _Tasks(TaskManager[RoleT]): """Records the calls of its one task on `calls`.""" calls: MagicMock @task def run_optical_centering(self, sample_id: int) -> None: self.calls.run_optical_centering(sample_id) def _publish_optical_centering_done(self, sample_id: int) -> None: self.calls._publish_optical_centering_done(sample_id) @pytest.fixture def tasks(): """The recorder of the calls made to the tasks.""" return MagicMock() @pytest.fixture def queue(client, tasks): manager = _Tasks[Server](client) manager.calls = tasks q = MxTaskQueue(client, manager, poll_interval_s=0.05) yield q q.shutdown() def _request(name="run_optical_centering", *args): return MXTaskExecutionMessage(name=name, args=args, kwargs={}) def _wait_for(predicate, timeout_s=3.0): deadline = time.monotonic() + timeout_s while time.monotonic() < deadline: if predicate(): return time.sleep(0.01) raise AssertionError("condition not met in time") def test_queue_runs_tasks_in_order(connector, queue, tasks): for sample_id in (1, 2, 3): connector.rpush( QueueEndpoints.task_execution(), _request("run_optical_centering", sample_id) ) queue.start() _wait_for(lambda: tasks.run_optical_centering.call_count == 3) assert tasks.run_optical_centering.call_args_list == [call(1), call(2), call(3)] assert connector.llen(QueueEndpoints.task_execution()) == 0 def test_queue_announces_each_pop(connector, queue): notifications = [] def on_changed(msg): # the connector keeps a weak ref: must be a function, not list.append notifications.append(msg) connector.register(QueueEndpoints.task_queue_changed(), cb=on_changed) for sample_id in (1, 2): connector.rpush( QueueEndpoints.task_execution(), _request("run_optical_centering", sample_id) ) queue.start() _wait_for(lambda: len(notifications) == 2) assert all(n.value == MXQueueChangedMessage() for n in notifications) def test_queue_does_not_pop_while_paused(connector, queue, tasks): queue.pause() connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 1)) queue.start() time.sleep(0.3) tasks.run_optical_centering.assert_not_called() assert connector.llen(QueueEndpoints.task_execution()) == 1 queue.resume() _wait_for(lambda: tasks.run_optical_centering.call_count == 1) assert connector.llen(QueueEndpoints.task_execution()) == 0 def test_paused_flag_is_shared_through_redis(connector, queue): # another client (here: a second config value on the same endpoint) can pause the queue other = MagicMock() other.connector = connector other_queue = MxTaskQueue(other, _Tasks[Server](other)) try: assert not queue.paused other_queue.pause() _wait_for(lambda: queue.paused) other_queue.resume() _wait_for(lambda: not queue.paused) finally: other_queue.shutdown() def test_queue_skips_non_task_names(connector, queue, tasks): connector.rpush(QueueEndpoints.task_execution(), _request("_publish_optical_centering_done", 1)) connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 2)) with patch("mx_bec.tasks.core.logger") as logger: queue.start() _wait_for(lambda: tasks.run_optical_centering.call_count == 1) tasks.run_optical_centering.assert_called_once_with(2) tasks._publish_optical_centering_done.assert_not_called() logger.warning.assert_called_once() def test_failed_task_is_logged_and_queue_continues(connector, queue, tasks): tasks.run_optical_centering.side_effect = [RuntimeError("boom"), None] connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 1)) connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 2)) with patch("mx_bec.tasks.core.logger") as logger: queue.start() _wait_for(lambda: tasks.run_optical_centering.call_count == 2) logger.exception.assert_called_once() assert tasks.run_optical_centering.call_args_list == [call(1), call(2)] def test_shutdown_waits_for_running_task(connector, queue, tasks): started, release = Event(), Event() def slow_task(*_): started.set() release.wait(timeout=3) tasks.run_optical_centering.side_effect = slow_task connector.rpush(QueueEndpoints.task_execution(), _request("run_optical_centering", 1)) queue.start() assert started.wait(timeout=3) assert queue._thread.is_alive() release.set() queue.shutdown() assert not queue._thread.is_alive()