-
Notifications
You must be signed in to change notification settings - Fork 50
[CI]: Add flake8 local plugin enforcing the async naming convention #158
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Spencer Schoenberg (spencrr)
merged 3 commits into
microsoft:main
from
spencrr:dev/spencrr/linter-tool-v2-flake8
Aug 14, 2026
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| [flake8] | ||
| # Flake8 runs ONLY the RAMPART local plugin. Every general-purpose check | ||
| # (pycodestyle, pyflakes, mccabe) is ruff's job, so selecting just RMP keeps | ||
| # the two linters from ever reporting the same problem twice. | ||
| select = RMP | ||
|
|
||
| # extend-exclude, not exclude, so flake8's defaults (__pycache__, .tox, .eggs) | ||
| # are kept rather than replaced. | ||
| extend-exclude = .venv,build,dist | ||
|
|
||
| # Baseline of pre-existing violations, recorded so the rule can be enforced | ||
| # from day one without a large mechanical rename in the same change. Each | ||
| # entry is removed by the commit that fixes the file. Do not add new entries. | ||
| per-file-ignores = | ||
| rampart/core/execution.py:RMP001 | ||
| rampart/core/injection.py:RMP001 | ||
| rampart/evaluators/llm_judge.py:RMP001 | ||
| rampart/pyrit_bridge/llm_bridge.py:RMP001 | ||
| rampart/pytest_plugin/_collection.py:RMP001 | ||
| rampart/surfaces/onedrive.py:RMP001 | ||
| tests/*:RMP001 | ||
|
|
||
| [flake8:local-plugins] | ||
| extension = | ||
| RMP = flake8_rampart:RampartChecker | ||
| paths = | ||
| ./tools |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT license. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT license. | ||
|
|
||
| """Tests for the flake8-rampart local plugin (RMP001).""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import ast | ||
| import subprocess # ruff: ignore[suspicious-subprocess-import] | ||
| import sys | ||
| from pathlib import Path | ||
|
|
||
| import pytest | ||
| from flake8_rampart import RampartChecker | ||
|
|
||
| _REPO_ROOT = Path(__file__).resolve().parents[3] | ||
|
|
||
|
|
||
| def _messages(source: str) -> list[str]: | ||
| """Return the messages the checker reports for a source snippet.""" | ||
| return [msg for _, _, msg, _ in RampartChecker(ast.parse(source)).run()] | ||
|
|
||
|
|
||
| class TestAsyncSuffixRule: | ||
| def test_flags_async_function_without_suffix(self) -> None: | ||
| (message,) = _messages("async def fetch(): ...") | ||
| assert message.startswith("RMP001") | ||
| assert "`fetch`" in message | ||
|
|
||
| def test_accepts_async_function_with_suffix(self) -> None: | ||
| assert _messages("async def fetch_async(): ...") == [] | ||
|
|
||
| def test_ignores_sync_function(self) -> None: | ||
| assert _messages("def fetch(): ...") == [] | ||
|
|
||
| def test_exempts_dunder(self) -> None: | ||
| assert _messages("async def __aenter__(self): ...") == [] | ||
|
|
||
| def test_flags_method_inside_class(self) -> None: | ||
| source = "class A:\n async def fetch(self): ...\n" | ||
| assert len(_messages(source)) == 1 | ||
|
|
||
| def test_flags_nested_function(self) -> None: | ||
| source = "def outer():\n async def inner(): ...\n" | ||
| assert len(_messages(source)) == 1 | ||
|
|
||
| def test_reports_position_of_definition(self) -> None: | ||
| checker = RampartChecker(ast.parse("\n\nasync def fetch(): ...")) | ||
| ((line, col, _, _),) = checker.run() | ||
| assert (line, col) == (3, 0) | ||
|
|
||
|
|
||
| @pytest.mark.slow | ||
| class TestPluginWiring: | ||
| """Guard against the plugin silently failing to load. | ||
|
|
||
| ``flake8 --select=RMP`` exits 0 when no plugin owns the ``RMP`` prefix, so | ||
| a broken registration would disable the rule with no visible error. These | ||
| tests run the repository's real ``.flake8`` configuration to prove | ||
| otherwise. | ||
| """ | ||
|
|
||
| def _run_flake8(self, target: Path) -> subprocess.CompletedProcess[str]: | ||
| return subprocess.run( # ruff: ignore[subprocess-without-shell-equals-true] | ||
| [sys.executable, "-m", "flake8", str(target)], | ||
| cwd=_REPO_ROOT, | ||
| capture_output=True, | ||
| text=True, | ||
| check=False, | ||
| ) | ||
|
|
||
| def test_reports_violation_through_flake8(self, tmp_path: Path) -> None: | ||
| target = tmp_path / "sample.py" | ||
| target.write_text("async def fetch():\n pass\n", encoding="utf-8") | ||
|
|
||
| result = self._run_flake8(target) | ||
|
|
||
| assert result.returncode == 1 | ||
| assert "RMP001" in result.stdout | ||
|
|
||
| def test_honors_noqa_through_flake8(self, tmp_path: Path) -> None: | ||
| target = tmp_path / "sample.py" | ||
| target.write_text( | ||
| "async def fetch(): # noqa: RMP001\n pass\n", | ||
| encoding="utf-8", | ||
| ) | ||
|
|
||
| result = self._run_flake8(target) | ||
|
|
||
| assert result.returncode == 0, result.stdout | ||
|
|
||
| def test_runs_no_rules_other_than_rmp(self, tmp_path: Path) -> None: | ||
| """``select = RMP`` keeps pycodestyle and pyflakes off; that is ruff's job.""" | ||
| target = tmp_path / "sample.py" | ||
| target.write_text("import os\nx=1\n", encoding="utf-8") | ||
|
|
||
| result = self._run_flake8(target) | ||
|
|
||
| assert result.returncode == 0, result.stdout |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT license. | ||
|
|
||
| """Flake8 plugin for RAMPART conventions that ruff cannot express. | ||
|
|
||
| Registered as a flake8 *local plugin*: see the ``[flake8:local-plugins]`` | ||
| section of ``.flake8``. Local plugins need no packaging or installation: | ||
| flake8 adds ``tools/`` to ``sys.path`` and imports this module directly. | ||
|
|
||
| Rules: | ||
| RMP001: Async functions must be named with an ``_async`` suffix. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import ast | ||
| from typing import TYPE_CHECKING, ClassVar | ||
|
|
||
| if TYPE_CHECKING: | ||
| from collections.abc import Iterator | ||
|
|
||
| RMP001 = "RMP001 async function `{name}` must be named with an `_async` suffix" | ||
|
|
||
|
|
||
| def _is_dunder(name: str) -> bool: | ||
| """Return whether a name follows Python's ``__dunder__`` convention. | ||
|
|
||
| Args: | ||
| name (str): The function name to test. | ||
|
|
||
| Returns: | ||
| bool: True for names like ``__aenter__`` that Python itself defines. | ||
| """ | ||
| return name.startswith("__") and name.endswith("__") | ||
|
|
||
|
|
||
| class RampartChecker: | ||
| """Flake8 checker enforcing RAMPART's async naming convention.""" | ||
|
|
||
| name: ClassVar[str] = "flake8-rampart" | ||
| version: ClassVar[str] = "1.0.0" | ||
|
|
||
| def __init__(self, tree: ast.AST) -> None: | ||
| """Store the module AST supplied by flake8. | ||
|
|
||
| Args: | ||
| tree (ast.AST): Parsed syntax tree for the file under check. | ||
| """ | ||
| self._tree = tree | ||
|
|
||
| def run(self) -> Iterator[tuple[int, int, str, type]]: | ||
| """Yield a violation for every async function missing the suffix. | ||
|
|
||
| Yields: | ||
| tuple[int, int, str, type]: Line, column, message, and checker | ||
| type, in the 4-tuple shape flake8 expects. | ||
| """ | ||
| for node in ast.walk(self._tree): | ||
| if not isinstance(node, ast.AsyncFunctionDef): | ||
| continue | ||
| # Dunders implement Python protocols; their names are not ours to choose. | ||
| if _is_dunder(node.name) or node.name.endswith("_async"): | ||
| continue | ||
| yield ( | ||
| node.lineno, | ||
| node.col_offset, | ||
| RMP001.format(name=node.name), | ||
| type(self), | ||
| ) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.