Skip to content

style: adopt the shared ruff standard - #358

Merged
uniqueg merged 7 commits into
devfrom
style/shared-ruff
Oct 21, 2026
Merged

uniqueg merged 7 commits into
devfrom
style/shared-ruff

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #344 (part 2; part 1, the reformat with line length 88, is #353)

  • ruff: add S (bandit) and G (logging format). Only tests/** ignores S101 (assert), and D (Google convention) now applies to tests, docs and examples too. The rules are now B C4 D E F G I PL RUF S SIM UP W with FOCA's documented ignores.
  • mypy: settings as in cloud-registry. files = ["foca", "tests"], with disallow_untyped_defs, disallow_any_generics and warn_unused_ignores; CI runs plain mypy. Examples are covered by ruff only, because mypy cannot check the two example apps together (both have top-level app/controllers modules).
  • .git-blame-ignore-revs: lists the squash commit of style: reformat with line length 88 #353 (8dfb0ca), which contains formatting only.
  • Package:
    • logging calls use lazy %-style arguments instead of f-strings (G004); the messages are unchanged.
    • generic types are parametrized and the remaining functions annotated.
    • the 0.0.0.0 default host (S104) and a false positive on the invalid_token description (S105) are justified inline.
  • Tests and examples:
    • type hints and docstrings added.
    • logger mocks format the lazy arguments.
    • integration-test requests now have timeouts (S113).
    • deliberately invalid arguments carry type: ignore[<code>] with a reason.
    • the shared test constant and type live in tests/mock_data.py.
    • no test was added or removed (1050 before and after).

Behaviour is unchanged, apart from the request timeouts in the integration tests.

Release notes (0.16.0): none for users (internal style and type-checking change). Optionally: "FOCA now lints with the shared ruff standard of ELIXIR Cloud & AAI apps and is fully type-checked (package and tests)."

Verification

  • ruff check, ruff format --check: pass
  • mypy (68 files, package and tests, strict): no issues
  • mkdocs build --strict: pass
  • Full suite with MongoDB 7.0: 1050 passed on Python 3.13; 1049 passed, 1 skipped on Python 3.10; 1050 passed on Python 3.14; lowest direct dependencies: 1049 passed, 1 skipped
  • Coverage of foca: 100%
  • Adversarial and quality reviewer agents. Round 1: the adversarial review found nothing (every converted logging call matches its old message, and no test assertion was weakened); the quality review found three mediums, all fixed (a shared test constant and client type, and consistent reasons for type: ignore/noqa). Round 2: the adversarial review found nothing; the quality review found a medium (three tests still spelled out the client type), now fixed, and two lows: F401 re-export reasons were added, and a duplicated comment in celery_app.py predates this PR
  • semgrep (p/python, p/secrets): clean; a false positive of logger-credential-disclosure on the debug message about validated tokens (logs issuer and subject only) is suppressed inline
  • CI: all checks pass

Declined review findings

  • Passthrough clients fixtures in tests/database/test_register_mongodb.py and tests/security/access_control/test_register_casbin_enforcer.py: they predate this PR; removing them is test refactoring outside style: adopt the shared ruff standard #344.
  • Shared mongomock collection helper: optional; not needed for this PR.
  • Duplicated comment above ContextTask in foca/factories/celery_app.py: predates this PR.
  • Sourcery: test_no_claims_logged passes on an empty log (tests/security/test_auth.py): it does not; the test already asserts that the issuer/subject message is logged. (Sourcery's other finding, on test_no_flask_config_logged, is fixed in f8149db.)

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 6 commits October 22, 2026 00:07
- ruff: add S (bandit) and G (logging format); tests ignore S101
  only; D (Google convention) now also applies to tests, docs and
  examples.
- mypy: as in cloud-registry, check the package and the tests
  (files in pyproject.toml; CI runs plain mypy), with
  disallow_untyped_defs, disallow_any_generics and warn_unused_ignores.
- Ignore the reformat with line length 88 (#353) in git blame.

Refs #344

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Log with lazy %-style arguments instead of f-strings (G004);
  messages are unchanged.
- Parametrize generic types and annotate the remaining functions
  (disallow_any_generics, disallow_untyped_defs).
- Justify the default host 0.0.0.0 (S104) and a false positive for
  the invalid_token description (S105) inline.

Refs #344

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Type and document the tests and examples for the shared ruff standard
and strict mypy. Logger mocks format the lazy %-style arguments, the
integration tests set request timeouts (S113), and deliberately
invalid arguments carry type: ignore with error codes. No test was
added or removed.

Refs #344

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Give every type: ignore a reason and noqa comments their reason in
  parentheses, as elsewhere in FOCA; list error codes without spaces.
- Define the invalid_token challenge and the type of the in-memory
  MongoDB clients once in tests/mock_data.py.

Refs #344

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Use the MongoClients alias in the remaining tests and give the F401
noqa comments of re-exports their reason.

Refs #344

Co-Authored-By: Claude Opus 5.5 <[email protected]>
semgrep's logger-credential-disclosure rule flags the debug message
about validated tokens, which now uses lazy arguments; it logs the
issuer and subject only, not the token.

Refs #344

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR applies the shared ELIXIR Cloud & AAI Ruff standard and strict package/test mypy configuration across the repository, then updates production code, examples, fixtures, mocks, and tests to satisfy those checks without changing application behavior; integration-test requests additionally gain finite timeouts.

Flow diagram for the updated quality checks

flowchart TD
    Config[pyproject.toml shared Ruff and mypy settings] --> RuffRules[Ruff rules: B C4 D E F G I PL RUF S SIM UP W]
    Config --> MypyRules[Strict mypy: foca and tests]
    RuffRules --> SourceUpdates[Typed code, lazy logging, docstrings, justified ignores]
    MypyRules --> SourceUpdates
    SourceUpdates --> Validation[ruff, mypy, tests, documentation build]
    Validation --> Result[Behavior unchanged; integration requests have timeouts]
Loading

File-Level Changes

Change Details Files
Adopt the shared Ruff linting and formatting standard, including security, logging-format, documentation, import, simplification, upgrade, and project-specific rule configuration.
  • Enabled Ruff Bandit and logging-format rule families.
  • Applied Google-style docstring checks across tests, docs, and examples, retaining only the assert exemption for tests.
  • Added documented inline suppressions for intentional security findings and re-exported symbols.
  • Recorded the formatting-only revision in git-blame exclusions.
pyproject.toml
.git-blame-ignore-revs
Make mypy cover the package and test suite with stricter completeness requirements and run it from the configured project scope in CI.
  • Configured mypy for foca and tests with untyped-definition, generic-type, and unused-ignore checks.
  • Changed CI to invoke plain mypy so the configured file set is checked.
  • Added type annotations and parametrized generic types throughout package code, examples, fixtures, helpers, and tests.
.github/workflows/checks.yml
foca/**/*.py
examples/**/*.py
tests/**/*.py
Modernize logging calls without changing their rendered messages or behavior.
  • Converted eager f-string logging arguments to lazy %-style logging arguments.
  • Updated logger mocks and assertions to format lazy arguments before comparison.
  • Added an inline semgrep suppression for the token-validation log false positive while preserving issuer/subject-only logging.
foca/**/*.py
tests/**/*.py
Complete test and example maintenance required by the new lint and type-check rules while preserving coverage and behavior.
  • Added module, class, function, and example docstrings plus explicit annotations.
  • Centralized Mongo client typing and the invalid-token challenge constant in tests/mock_data.py.
  • Added reasoned type-ignore/noqa annotations for deliberately invalid inputs and intentional findings.
  • Added timeouts to integration-test HTTP requests.
examples/**/*.py
tests/**/*.py

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@uniqueg
uniqueg marked this pull request as ready for review October 21, 2026 22:21
@codecov

codecov Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (8dfb0ca) to head (f8149db).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #358   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           24        24           
  Lines         1786      1797   +11     
=========================================
+ Hits          1786      1797   +11     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 2 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="tests/config/test_config_parser.py" line_range="300" />
<code_context>


-def test_no_flask_config_logged(monkeypatch):
+def test_no_flask_config_logged(monkeypatch: pytest.MonkeyPatch) -> None:
     """The Flask config, including secrets, is not logged."""
     messages: list[str] = []
</code_context>
<issue_to_address>
**Secret logging goes undetected**

When the factory logs each app's Flask config during creation, in `test_no_flask_config_logged`, line 304 creates an app before line 305 adds `SECRET_KEY`, and line 306 creates a second app with a fresh `Config`; the assertion at line 307 therefore passes even if each app's config is logged, leaving a secret leak undetected.

Set the secret in the configuration before calling the factory, then assert it is absent from the captured logs.
</issue_to_address>

### Comment 2
<location path="tests/security/test_auth.py" line_range="179" />
<code_context>
+        monkeypatch.setattr(
+            auth.logger,
+            "debug",
+            lambda msg, *args: messages.append(msg % args),
+        )
         token = make_token(email="[email protected]", name="Alice A.")
</code_context>
<issue_to_address>
**Missing token logs go undetected**

When `validate_token` emits no debug message, in `test_no_claims_logged`, the assertions at lines 185-186 only check that sensitive values are absent from the captured messages; an empty message list passes, so removing the validated-token debug log goes unnoticed.

Assert that the expected issuer and subject appear in the captured log, in addition to checking that sensitive values do not.
</issue_to_address>

Sourcery assessment

Approval pending. 2 findings to address first.

Blocking findings: tests/config/test_config_parser.py:300, tests/security/test_auth.py:179


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread tests/config/test_config_parser.py Resolved
Comment thread tests/security/test_auth.py Resolved
The test set SECRET_KEY after the app was created, so it could not
catch a logged Flask config. Check instead that no key of the created
app's Flask config appears in the factory's debug messages, and that
those messages were captured at all.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit e491f10 into dev Oct 21, 2026
14 checks passed
@uniqueg
uniqueg deleted the style/shared-ruff branch October 21, 2026 22:29
uniqueg added a commit that referenced this pull request Oct 21, 2026
Add docstrings and return types to the chart tests and justify the
subprocess call, as the shared ruff standard (#358) requires.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant