Andrushika commented on code in PR #77463:
URL: https://github.com/apache/airflow/pull/77463#discussion_r4771163114


##########
.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:
   Makes sense. I'll do it in a follow-up that moves the allowlist-edit check 
from `check_provide_session_kwargs.py` into `AllowlistManager`, so all three 
allowlist hooks get it (plus `require_serial` on the other two).



##########
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:
   Added, thanks.



##########
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:
   No worries, fixed. A `new_callable=` naming a mock class or `PropertyMock` 
counts again unless `spec` / `spec_set` / `autospec` is passed too.



##########
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:
   Done -- a `**{...}` literal with string keys is read like normal keywords 
now.



-- 
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]

Reply via email to