potiuk commented on code in PR #77463:
URL: https://github.com/apache/airflow/pull/77463#discussion_r4754370259
##########
.pre-commit-config.yaml:
##########
@@ -1905,6 +1905,15 @@ repos:
language: python
pass_filenames: true
files:
^(airflow-core|providers)/.*\.py$|^scripts/ci/prek/known_provide_session_positional\.txt$|^scripts/ci/prek/check_provide_session_kwargs\.py$
+ - id: check-no-new-unspecced-mocks
+ name: Check that no new mocks without spec/autospec are added to tests
+ env:
+ PYTHONPYCACHEPREFIX: .build/pycache
+ entry: ./scripts/ci/prek/check_unspecced_mocks.py
+ language: python
+ pass_filenames: true
+ require_serial: true
+ files:
^(airflow-core|airflow-ctl|airflow-ctl-tests|airflow-e2e-tests|chart|dev|devel-common|docker-tests|kubernetes-tests|performance|providers|scripts|shared|task-sdk|task-sdk-integration-tests)/(.*/)?tests/.*\.py$
Review Comment:
**Editing the allowlist itself is not checked**
The hook only matches test `.py` files, so a change that raises a count in
`generated/known_unspecced_mocks.txt`, drops entries in a conflict resolution,
or deletes the file runs nothing: the hook never re-counts the files the
allowlist names. `check-no-new-provide-session-positional` covers this by also
matching its allowlist and its script and re-checking every file the allowlist
lists when either changes. Add `^generated/known_unspecced_mocks\.txt$` and the
script to `files`, and when either is among the changed files, check the files
the allowlist names (and fail when the allowlist is missing), as
`check_provide_session_kwargs.py` does.
*Flagged by antigravity (adversarial review); cross-checked.*
---
Drafted-by: Claude Code (Opus 5.5); reviewed by @potiuk before posting
##########
scripts/ci/prek/check_unspecced_mocks.py:
##########
@@ -0,0 +1,295 @@
+#!/usr/bin/env python
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+# /// script
+# requires-python = ">=3.11"
+# dependencies = [
+# "rich>=13.0.0",
+# ]
+# ///
+"""Check that no new mocks without ``spec``/``autospec`` are added to test
files.
+
+The project convention is to use ``spec``/``autospec`` when mocking, so a mock
+rejects attributes and call signatures that the real object does not have. A
+violation is a call that creates a mock without a spec:
+
+* ``Mock``, ``MagicMock``, ``AsyncMock``, ``NonCallableMock`` or
+ ``NonCallableMagicMock`` without ``spec``/``spec_set`` or a positional spec.
+* ``patch`` or ``patch.object`` without ``spec``, ``spec_set``, ``autospec``,
+ ``new`` or ``new_callable``, given by keyword or by position.
+
+An argument set to its "no spec" value counts as missing: ``None`` or ``False``
+for ``spec``, ``spec_set`` and ``autospec``, ``DEFAULT`` for ``new``, and
+``None`` for ``new_callable``. Calls are matched by name, so ``patch`` called
+through a renamed module (``async_mock.patch(...)``) and a mock class imported
+under another name (``MagicMock as MM``) are not counted.
+
+All *existing* violations are recorded in
``generated/known_unspecced_mocks.txt``
+as ``relative/path::N`` entries (one per file), where ``N`` is the maximum
+number of mocks without a spec allowed in that file. A file whose current count
+exceeds the recorded limit is treated as a violation – pass ``spec=`` or
+``autospec=True`` instead.
+
+Modes
+-----
+Default (files passed by prek/pre-commit):
+ Check only the supplied files; fail if any file's count exceeds the limit.
+ When a file's count has *decreased*, the allowlist entry is tightened
+ automatically and the hook exits with a non-zero code so that pre-commit
+ reports the modified allowlist – just stage
+ ``generated/known_unspecced_mocks.txt`` and re-run.
+
+ A file that cannot be read or parsed fails the hook and leaves its entry
unchanged.
+
+``--all-files``:
+ Walk every ``.py`` file in a ``tests`` directory under the project roots
+ listed in ``_PROJECT_ROOTS`` — the same scope the pre-commit hook applies
to.
+
+``--cleanup``:
+ Remove entries for files that no longer exist. Safe to run at any time;
+ does not add new entries or raise limits.
+
+``--generate``:
+ Scan the same files as ``--all-files`` and *rebuild* the allowlist from
+ scratch. Intended for the initial setup or after a large-scale clean-up
sprint.
+"""
+
+from __future__ import annotations
+
+import argparse
+import ast
+import textwrap
+from collections.abc import Iterable, Iterator
+from pathlib import Path
+from typing import NamedTuple
+
+from common_prek_utils import AIRFLOW_ROOT_PATH, AllowlistManager
+from rich.console import Console
+
+console = Console(color_system="standard", width=200)
+
+REPO_ROOT = AIRFLOW_ROOT_PATH
+
+# Top-level directories scanned by ``--all-files`` / ``--generate``. Keep in
sync with the
+# ``files:`` pattern for this hook in ``.pre-commit-config.yaml``.
+_PROJECT_ROOTS = (
+ "airflow-core",
+ "airflow-ctl",
+ "airflow-ctl-tests",
+ "airflow-e2e-tests",
+ "chart",
+ "dev",
+ "devel-common",
+ "docker-tests",
+ "kubernetes-tests",
+ "performance",
+ "providers",
+ "scripts",
+ "shared",
+ "task-sdk",
+ "task-sdk-integration-tests",
+)
+
+_EXCLUDED_DIRS = frozenset({".build", "node_modules", "site-packages"})
+
+_DEFAULT_NAMES = frozenset(
+ {
+ "DEFAULT",
+ "mock.DEFAULT",
+ "unittest.mock.DEFAULT",
+ "mocker.DEFAULT",
+ "sentinel.DEFAULT",
+ "mock.sentinel.DEFAULT",
+ }
+)
+
+_MOCK_CLASSES = frozenset({"Mock", "MagicMock", "AsyncMock",
"NonCallableMock", "NonCallableMagicMock"})
+
+
+class _SpecRule(NamedTuple):
+ target_arg_count: int
+ positional_params: tuple[str, ...]
+ spec_params: frozenset[str]
+
+
+_PATCH_PARAMS = ("new", "spec", "create", "spec_set", "autospec",
"new_callable")
+_PATCH_SPEC_OR_NEW_PARAMS = frozenset(_PATCH_PARAMS) - {"create"}
+
+_MOCK_CLASS_RULE = _SpecRule(0, ("spec",), frozenset({"spec", "spec_set"}))
+_PATCH_RULE = _SpecRule(1, _PATCH_PARAMS, _PATCH_SPEC_OR_NEW_PARAMS)
+_PATCH_OBJECT_RULE = _SpecRule(2, _PATCH_PARAMS, _PATCH_SPEC_OR_NEW_PARAMS)
+
+
+def _get_dotted_name(node: ast.expr) -> str | None:
+ parts: list[str] = []
+ while isinstance(node, ast.Attribute):
+ parts.append(node.attr)
+ node = node.value
+ if not isinstance(node, ast.Name):
+ return None
+ parts.append(node.id)
+ return ".".join(reversed(parts))
+
+
+def _get_spec_rule(name: str) -> _SpecRule | None:
+ parts = name.split(".")
+ if parts[-1] in _MOCK_CLASSES:
+ return _MOCK_CLASS_RULE
+ if parts == ["patch"] or parts[-2:] in (["mock", "patch"], ["mocker",
"patch"]):
+ return _PATCH_RULE
+ if parts[-2:] == ["patch", "object"]:
+ return _PATCH_OBJECT_RULE
+ return None
+
+
+def _is_none_or_false(value: ast.expr) -> bool:
+ return isinstance(value, ast.Constant) and (value.value is None or
value.value is False)
+
+
+def _is_spec_or_new_argument(param: str, value: ast.expr) -> bool:
Review Comment:
**`new_callable=MagicMock` still creates an unspecced mock**
My earlier suggestion to count `new_callable=` as specced was too broad,
sorry: it is fine when it names a real or specced factory, but `patch("x",
new_callable=MagicMock)` (or `Mock`, `AsyncMock`, `PropertyMock`) builds
exactly the unspecced mock the hook is about, unless
`spec`/`spec_set`/`autospec` is passed too. Treat `new_callable` set to
`MagicMock`, `Mock`, `AsyncMock`, `NonCallableMagicMock` or `PropertyMock` (any
of the import spellings) without a spec argument as unspecced, and add test
cases for it.
*Flagged by antigravity (adversarial review); cross-checked.*
---
Drafted-by: Claude Code (Opus 5.5); reviewed by @potiuk before posting
##########
dev/breeze/src/airflow_breeze/utils/selective_checks.py:
##########
@@ -698,14 +698,15 @@ def __hash__(self):
# The CI image is built from these before the sources are copied in;
any other change reuses the
# cached layers, so the build-time check has nothing new to measure.
Breeze's FILES_FOR_REBUILD_CHECK
# are these or ENVIRONMENT_FILES. The build first regenerates the
provider dependencies with the
- # prek script, which is not an ENVIRONMENT_FILES match.
+ # prek script, which is not an ENVIRONMENT_FILES match. Only prek
hooks read the
+ # generated/known_*.txt allowlists.
FileGroupForCi.IMAGE_BUILD_FILES: [
r"^scripts/ci/prek/(common_prek_utils|update_providers_dependencies)\.py$",
r"^Dockerfile",
r"^\.dockerignore$",
r"^scripts/docker/",
r".*hatch_build\.py$",
- r"^generated/",
+ r"^generated/(?!known_[^/]*\.txt$)",
Review Comment:
**The allowlist also turns on the provider compatibility tests**
Taking `generated/known_*.txt` out of `IMAGE_BUILD_FILES` is right, but the
same reasoning (only prek hooks read it) applies to
`COMPAT_TESTS_HIDDEN_FILES`. A PR that only changes `task-sdk/tests/` skips the
provider compatibility matrix today; once it fixes a mock there it also commits
the tightened allowlist, and that one file switches the whole matrix on across
every Airflow version. 42 files under `task-sdk/tests/` are in the allowlist.
Add `^generated/known_[^/]*\.txt$` to `COMPAT_TESTS_HIDDEN_FILES`, with a case
in `test_selective_checks.py` and a line in `04_selective_checks.md`.
*Flagged by antigravity (adversarial review); cross-checked.*
---
Drafted-by: Claude Code (Opus 5.5); reviewed by @potiuk before posting
##########
scripts/ci/prek/check_unspecced_mocks.py:
##########
@@ -0,0 +1,295 @@
+#!/usr/bin/env python
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+# /// script
+# requires-python = ">=3.11"
+# dependencies = [
+# "rich>=13.0.0",
+# ]
+# ///
+"""Check that no new mocks without ``spec``/``autospec`` are added to test
files.
+
+The project convention is to use ``spec``/``autospec`` when mocking, so a mock
+rejects attributes and call signatures that the real object does not have. A
+violation is a call that creates a mock without a spec:
+
+* ``Mock``, ``MagicMock``, ``AsyncMock``, ``NonCallableMock`` or
+ ``NonCallableMagicMock`` without ``spec``/``spec_set`` or a positional spec.
+* ``patch`` or ``patch.object`` without ``spec``, ``spec_set``, ``autospec``,
+ ``new`` or ``new_callable``, given by keyword or by position.
+
+An argument set to its "no spec" value counts as missing: ``None`` or ``False``
+for ``spec``, ``spec_set`` and ``autospec``, ``DEFAULT`` for ``new``, and
+``None`` for ``new_callable``. Calls are matched by name, so ``patch`` called
+through a renamed module (``async_mock.patch(...)``) and a mock class imported
+under another name (``MagicMock as MM``) are not counted.
+
+All *existing* violations are recorded in
``generated/known_unspecced_mocks.txt``
+as ``relative/path::N`` entries (one per file), where ``N`` is the maximum
+number of mocks without a spec allowed in that file. A file whose current count
+exceeds the recorded limit is treated as a violation – pass ``spec=`` or
+``autospec=True`` instead.
+
+Modes
+-----
+Default (files passed by prek/pre-commit):
+ Check only the supplied files; fail if any file's count exceeds the limit.
+ When a file's count has *decreased*, the allowlist entry is tightened
+ automatically and the hook exits with a non-zero code so that pre-commit
+ reports the modified allowlist – just stage
+ ``generated/known_unspecced_mocks.txt`` and re-run.
+
+ A file that cannot be read or parsed fails the hook and leaves its entry
unchanged.
+
+``--all-files``:
+ Walk every ``.py`` file in a ``tests`` directory under the project roots
+ listed in ``_PROJECT_ROOTS`` — the same scope the pre-commit hook applies
to.
+
+``--cleanup``:
+ Remove entries for files that no longer exist. Safe to run at any time;
+ does not add new entries or raise limits.
+
+``--generate``:
+ Scan the same files as ``--all-files`` and *rebuild* the allowlist from
+ scratch. Intended for the initial setup or after a large-scale clean-up
sprint.
+"""
+
+from __future__ import annotations
+
+import argparse
+import ast
+import textwrap
+from collections.abc import Iterable, Iterator
+from pathlib import Path
+from typing import NamedTuple
+
+from common_prek_utils import AIRFLOW_ROOT_PATH, AllowlistManager
+from rich.console import Console
+
+console = Console(color_system="standard", width=200)
+
+REPO_ROOT = AIRFLOW_ROOT_PATH
+
+# Top-level directories scanned by ``--all-files`` / ``--generate``. Keep in
sync with the
+# ``files:`` pattern for this hook in ``.pre-commit-config.yaml``.
+_PROJECT_ROOTS = (
+ "airflow-core",
+ "airflow-ctl",
+ "airflow-ctl-tests",
+ "airflow-e2e-tests",
+ "chart",
+ "dev",
+ "devel-common",
+ "docker-tests",
+ "kubernetes-tests",
+ "performance",
+ "providers",
+ "scripts",
+ "shared",
+ "task-sdk",
+ "task-sdk-integration-tests",
+)
+
+_EXCLUDED_DIRS = frozenset({".build", "node_modules", "site-packages"})
+
+_DEFAULT_NAMES = frozenset(
+ {
+ "DEFAULT",
+ "mock.DEFAULT",
+ "unittest.mock.DEFAULT",
+ "mocker.DEFAULT",
+ "sentinel.DEFAULT",
+ "mock.sentinel.DEFAULT",
+ }
+)
+
+_MOCK_CLASSES = frozenset({"Mock", "MagicMock", "AsyncMock",
"NonCallableMock", "NonCallableMagicMock"})
+
+
+class _SpecRule(NamedTuple):
+ target_arg_count: int
+ positional_params: tuple[str, ...]
+ spec_params: frozenset[str]
+
+
+_PATCH_PARAMS = ("new", "spec", "create", "spec_set", "autospec",
"new_callable")
+_PATCH_SPEC_OR_NEW_PARAMS = frozenset(_PATCH_PARAMS) - {"create"}
+
+_MOCK_CLASS_RULE = _SpecRule(0, ("spec",), frozenset({"spec", "spec_set"}))
+_PATCH_RULE = _SpecRule(1, _PATCH_PARAMS, _PATCH_SPEC_OR_NEW_PARAMS)
+_PATCH_OBJECT_RULE = _SpecRule(2, _PATCH_PARAMS, _PATCH_SPEC_OR_NEW_PARAMS)
+
+
+def _get_dotted_name(node: ast.expr) -> str | None:
+ parts: list[str] = []
+ while isinstance(node, ast.Attribute):
+ parts.append(node.attr)
+ node = node.value
+ if not isinstance(node, ast.Name):
+ return None
+ parts.append(node.id)
+ return ".".join(reversed(parts))
+
+
+def _get_spec_rule(name: str) -> _SpecRule | None:
+ parts = name.split(".")
+ if parts[-1] in _MOCK_CLASSES:
+ return _MOCK_CLASS_RULE
+ if parts == ["patch"] or parts[-2:] in (["mock", "patch"], ["mocker",
"patch"]):
+ return _PATCH_RULE
+ if parts[-2:] == ["patch", "object"]:
+ return _PATCH_OBJECT_RULE
+ return None
+
+
+def _is_none_or_false(value: ast.expr) -> bool:
+ return isinstance(value, ast.Constant) and (value.value is None or
value.value is False)
+
+
+def _is_spec_or_new_argument(param: str, value: ast.expr) -> bool:
+ if param == "new":
+ return _get_dotted_name(value) not in _DEFAULT_NAMES
+ return not _is_none_or_false(value)
+
+
+def _is_unspecced(call: ast.Call, rule: _SpecRule) -> bool:
+ if any(keyword.arg is None for keyword in call.keywords):
Review Comment:
**`MagicMock(**{...})` with a literal dict is skipped**
Any `**` unpacking counts as possibly specced, which is right for
`**kwargs`, but a literal dict can be read:
`MagicMock(**{"to_dict.return_value": ...})` (used in
`providers/celery/tests/integration/celery/test_celery_executor.py`) has no
spec and passes. When the unpacked value is an `ast.Dict` with constant keys,
look at those keys like ordinary keywords.
*Flagged by codex (adversarial review); cross-checked.*
---
Drafted-by: Claude Code (Opus 5.5); reviewed by @potiuk before posting
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]