Source code for smarter.lib.unittest.queued_tasks

"""
Keep an app's Celery tasks from reaching a worker, for a whole test class (ADR-030, rule 10).

Celery isn't eager in tests: ``.delay()`` or ``.apply_async()`` sends a task to a real worker, which holds real
credentials. Each app queues its tasks from one module, its ``tasks/queue.py``, so the tasks that module holds are
every task that anything queues. :class:`QueuedTasksPatcher` patches ``delay`` and ``apply_async`` on each of them,
on the task objects, so that a call is caught wherever it comes from, and records each call on a stand-in per task.

Each app's test mixin is a thin wrapper, e.g.
:class:`smarter.apps.llmclient.tests.base_classes.TestLLMClientQueuedTasksMixin`: it starts the patcher in
``setUpClass``, stops it in ``tearDownClass``, and names its own attribute, so that two apps' mixins can share a test
class.
"""

import ast
import unittest
from collections.abc import Collection
from pathlib import Path
from types import ModuleType
from typing import TYPE_CHECKING, Optional, Union
from unittest.mock import AsyncMock, MagicMock, patch

from celery import Task

from smarter.lib.typing import SmarterDictType

if TYPE_CHECKING:
    from unittest.mock import _patch

    _ConventionTestsBase = unittest.TestCase
else:
    # a mixin, not a test case: unittest would otherwise run its tests alone, without an app to check.
    _ConventionTestsBase = object


[docs] def queued_tasks_of(queue_module: ModuleType) -> dict[str, Task]: """ Return every Celery task that an app's queue module holds, by its function's name. :param queue_module: The app's ``tasks/queue.py``, e.g. :mod:`smarter.apps.llmclient.tasks.queue`. :returns: The tasks, e.g. ``{"deploy_default_api": deploy_default_api, ...}``. """ tasks = {} for name, value in vars(queue_module).items(): if isinstance(value, Task): tasks[name] = value return tasks
[docs] def queued_calls(stand_in: MagicMock) -> list[SmarterDictType]: """ Return the keyword arguments of each time a task was queued, whether with ``delay`` or ``apply_async``. :param stand_in: The task's stand-in, from :attr:`QueuedTasksPatcher.stand_ins`. :returns: The arguments of each call, in order, e.g. ``[{"hosted_zone_id": "Z1", ...}]``. """ calls = [] for call in stand_in.delay.call_args_list: calls.append(dict(call.kwargs)) for call in stand_in.apply_async.call_args_list: task_kwargs = call.kwargs.get("kwargs") or {} calls.append(dict(task_kwargs)) return calls
[docs] class QueuedTasksPatcher: """ Patch ``delay`` and ``apply_async`` on every task that an app's queue module holds, and record their calls. :param queue_module: The app's ``tasks/queue.py``. """
[docs] def __init__(self, queue_module: ModuleType) -> None: self.queue_module = queue_module self.stand_ins: dict[str, MagicMock] = {} """A stand-in per task, by its function's name, whose ``delay`` and ``apply_async`` record the calls.""" self._patchers: list["_patch[Union[MagicMock, AsyncMock]]"] = []
[docs] def start(self) -> dict[str, MagicMock]: """ Patch every task. :returns: The stand-ins, by task. """ for name, task in queued_tasks_of(self.queue_module).items(): stand_in = MagicMock(name=name) for method in ("delay", "apply_async"): method_mock = getattr(stand_in, method) patcher = patch.object(task, method, method_mock) patcher.start() self._patchers.append(patcher) self.stand_ins[name] = stand_in return self.stand_ins
[docs] def stop(self) -> None: """Restore every task.""" for patcher in reversed(self._patchers): patcher.stop() self._patchers = []
[docs] def forget(self) -> None: """Forget every call recorded so far.""" for stand_in in self.stand_ins.values(): stand_in.reset_mock()
QUEUE_METHODS = ("delay", "apply_async") """The methods of a Celery task that queue it.""" QUEUE_FUNCTIONS = ("delay_through_breaker",) """ The functions that queue the task they are given as their first argument. :func:`smarter.lib.celery_conf.publish.delay_through_breaker` queues a task through the broker's circuit breaker. """
[docs] def registered_task_functions(task_name_prefix: str) -> list[str]: """ Return the function name of every task that Celery registered under a prefix. :param task_name_prefix: The start of the tasks' Celery names, e.g. ``smarter.apps.llmclient.tasks.``. :returns: The names, sorted, e.g. ``["deploy_default_api", ...]``. """ # pylint: disable=import-outside-toplevel from smarter.workers.celery import app names = [] for registered_name in app.tasks: if registered_name.startswith(task_name_prefix): function_name = registered_name.rsplit(".", 1)[-1] names.append(function_name) return sorted(names)
[docs] def queueing_calls(path: Path) -> list[tuple[int, str]]: """ Return each call in a module that queues a Celery task, and the task it queues. A call is ``<task>.delay(...)``, ``<task>.apply_async(...)``, or one of :data:`QUEUE_FUNCTIONS` with the task as its first argument. The module is parsed, not searched, so the words ``task.delay()`` in a docstring or a comment don't count, and neither does a reference to the method that isn't called, e.g. ``partial(task.delay, ...)``. :param path: The module. :returns: The line and the task's expression of each call, e.g. ``(42, "deploy_default_api")``. """ text = path.read_text(encoding="utf-8") tree = ast.parse(text, filename=str(path)) calls = [] for node in ast.walk(tree): if not isinstance(node, ast.Call): continue function = node.func if isinstance(function, ast.Attribute) and function.attr in QUEUE_METHODS: task = ast.unparse(function.value) calls.append((node.lineno, task)) continue if isinstance(function, ast.Name) and function.id in QUEUE_FUNCTIONS and node.args: task = ast.unparse(node.args[0]) calls.append((node.lineno, task)) calls.sort() return calls
[docs] def calls_that_queue( directory: Path, allowed: Collection[Path], root: Path, task_names: Optional[Collection[str]] = None, ) -> list[str]: """ Return each call, under a directory, outside the allowed modules, the tests and the migrations, that queues a task. :param directory: The directory to search, e.g. an app's, or the whole ``smarter`` package. :param allowed: The modules that may queue, e.g. the queue modules. :param root: The directory that the returned paths are relative to. :param task_names: Only the calls that queue one of these tasks, by its function's name. All of them if None. :returns: ``path:line task`` of each call, e.g. ``apps/llmclient/receivers.py:71 deploy_default_api``. """ found = [] for path in sorted(directory.rglob("*.py")): if path in allowed: continue parts = path.relative_to(directory).parts if "tests" in parts or "migrations" in parts: continue for number, task in queueing_calls(path): name = task.rsplit(".", 1)[-1] if task_names is not None and name not in task_names: continue relative = path.relative_to(root) found.append(f"{relative}:{number} {task}") return found
[docs] class QueueConventionTests(_ConventionTestsBase): """ The tests that keep an app to ADR-030's rule 10: its tasks are queued by its ``tasks/queue.py``, and nothing else. Mix it into an app's test class, after :class:`~smarter.lib.unittest.base_classes.SmarterTestBase` or a class derived from it, and set the class attributes. It is not a test case itself, so it runs only where it is mixed in. """ queue_module: ModuleType """The app's ``tasks/queue.py``.""" tasks_package: ModuleType """The app's ``tasks`` package.""" task_name_prefix: str """The start of the app's tasks' Celery names, with its trailing dot.""" queued_task_names: dict[str, str] """The Celery name of each task that queue.py queues, by its function's name, which waiting messages use.""" not_queued: frozenset[str] = frozenset() """The app's tasks that nothing queues, e.g. those that only Celery Beat sends, by name."""
[docs] def app_directory(self) -> Path: """ Return the app's directory, the parent of its tasks package. :returns: The directory. """ queue_path = Path(self.queue_module.__file__ or "").resolve() directory = queue_path.parent.parent return directory
[docs] def smarter_package(self) -> Path: """ Return the ``smarter`` package's directory, which holds every app. :returns: The directory. """ # pylint: disable=import-outside-toplevel import smarter directory = Path(smarter.__file__ or "").resolve().parent return directory
[docs] def test_task_names_are_kept(self): """Each queued task keeps the Celery name that messages already waiting in Redis use.""" for attribute, name in self.queued_task_names.items(): with self.subTest(task=attribute): task = getattr(self.queue_module, attribute) self.assertEqual(task.name, name)
[docs] def test_every_queued_task_has_a_queue_function(self): """Each of the app's registered tasks is held by queue.py, except those that nothing queues.""" registered = set(registered_task_functions(self.task_name_prefix)) self.assertEqual(registered - set(self.not_queued), set(self.queued_task_names))
[docs] def test_nothing_in_the_app_queues_outside_queue_py(self): """No module of the app, its tasks included, calls .delay() or .apply_async(), except queue.py.""" queue_path = Path(self.queue_module.__file__ or "").resolve() offenders = calls_that_queue(self.app_directory(), {queue_path}, self.smarter_package()) self.assertEqual(offenders, [], f"Queue the task with a function of {self.queue_module.__name__}.")
[docs] def test_no_other_app_queues_its_tasks(self): """No module of another app calls .delay() or .apply_async() on one of the app's tasks.""" task_names = registered_task_functions(self.task_name_prefix) self.assertGreaterEqual(len(task_names), 1) queue_path = Path(self.queue_module.__file__ or "").resolve() offenders = calls_that_queue(self.smarter_package(), {queue_path}, self.smarter_package(), task_names) self.assertEqual(offenders, [], f"Queue the task with a function of {self.queue_module.__name__}.")
[docs] def test_the_package_exports_no_task(self): """The tasks package exports the queue functions, never a task, so that nothing is tempted to call .delay().""" task_names = set(registered_task_functions(self.task_name_prefix)) exported = set(self.tasks_package.__all__) self.assertEqual(exported & task_names, set()) for name in self.queue_module.__all__: with self.subTest(function=name): self.assertIn(name, exported)
__all__ = [ "QUEUE_FUNCTIONS", "QUEUE_METHODS", "QueueConventionTests", "QueuedTasksPatcher", "calls_that_queue", "queueing_calls", "queued_calls", "queued_tasks_of", "registered_task_functions", ]