Running queryguard in CI and in GitHub code scanning#

pytest-queryguard already fails the test run on a new N+1 query, so any CI that runs pytest enforces it. To also see the findings in the GitHub UI, as code scanning alerts with a file, a line and a fix hint, use the pytest-queryguard action or upload the SARIF file yourself.

The action#

name: Tests
on:
  push:
    branches: [main]
  pull_request:

permissions:
  contents: read

jobs:
  tests:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      security-events: write   # needed to upload to code scanning
      actions: read            # compare query counts with the base branch
      pull-requests: write     # comment the comparison on the pull request
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-python@v7
        with:
          python-version: "3.12"
      - run: pip install -e ".[test]"        # your project and its test dependencies
      - uses: MaciejZiel/pytest-queryguard-action@v1.1.0   # a release tag, or a commit SHA
        with:
          pytest-args: tests/   # no -x: see below
          # baseline: queryguard-baseline.json   # add once the file exists, see below

The action lives in MaciejZiel/pytest-queryguard-action, the repository listed in the GitHub Marketplace as pytest-queryguard. It holds a copy of action/action.yml of this repository that each release copies there, so its vX.Y.Z is the same action as this repository's vX.Y.Z; issues and changes go to this repository. A release tag or a commit SHA is the safer pin: it never changes, and Dependabot proposes the updates. @v1 follows the newest 1.x final release (never a release candidate), so a run can change without a change to your workflow. Existing workflows that use MaciejZiel/pytest-queryguard/action@<tag> keep working and get every 1.x release too; switching is a change of the uses: line only, and the comparison with the base branch, the trend and open code scanning alerts carry over, since the inputs, outputs, artifact name, category and comment marker are the same.

The push trigger is limited to main so that a pull request does not run the workflow twice, once for the push and once for the pull request.

pytest-args has no -x. A run that stops at the first failure writes a JSON file with "complete": false, which the comparison with the base branch cannot fully use (see Query counts as JSON), and it keeps --queryguard-update-baseline and the budget file update from writing (see baseline.md).

The example has no baseline input on purpose. A baseline path that does not exist makes pytest stop with baseline file ... does not exist; create it with --queryguard-update-baseline, and the action never creates the file. To use a baseline, create it locally with pytest --queryguard-baseline=queryguard-baseline.json --queryguard-update-baseline (see baseline.md), commit it, and then uncomment the baseline line.

You do not need to set package. Left empty, the action installs the plugin its own ref ships (the release's wheel in dist/ of the action repository, the same file as on PyPI, or the checkout above action/ here), so pin the action to a release tag or a commit and you get the plugin of that release. A fixed default such as pytest-queryguard would let pip pick an older release (for example 0.3.0, which has no --queryguard-sarif), and pytest would stop with unrecognized arguments. Set package only to install something else, such as pytest-queryguard==0.7.0 or a path. The action needs pytest-queryguard 0.6.0 or newer: it passes --queryguard-sarif and --queryguard-json and runs python -m pytest_queryguard.compare, which older releases do not have. The trend input needs 0.8.0 or newer (python -m pytest_queryguard.trend), and the lint input 0.10.0 or newer (--format github).

The action installs pytest-queryguard into the active Python, runs pytest --queryguard-sarif=queryguard.sarif, uploads the file with github/codeql-action/upload-sarif (pinned by commit SHA inside the action) and then fails the step if pytest failed. Install your own project first: the action does not know how.

Input Default Meaning
pytest-args empty Arguments for pytest, as a list of shell words: quotes group words (-k "a or b"). The value is split by Python's shlex and is not evaluated by a shell, so $(...), backticks and $VAR are passed to pytest as literal text.
python-version empty Set up this Python. Empty: use the python on PATH.
package empty What to pip install. Empty: the plugin the action's own ref ships, matching the pinned ref. Otherwise a requirement like pytest-queryguard>=0.6 (the oldest release the action works with; 0.8.0 for trend, 0.10.0 for lint), or a path.
baseline empty Baseline file, see baseline.md. Empty: queryguard_baseline from your config.
fail true true: fail the step when pytest fails. false: a failed test run does not fail the step, only report. An invalid input or a failed install still fails it.
working-directory . Where to run pytest. Locations in the SARIF file are still relative to the repository root (see SARIF output).
sarif-file queryguard.sarif Output file, relative to working-directory.
upload true Upload to code scanning. false: only write the file.
category pytest-queryguard Code scanning category; use one per job when several jobs upload, including each job of a matrix (see Limits). It also names the job's query-count artifact, queryguard-json-<category> with " : < > \| * ? \ / and line breaks turned into -, and its pull-request comment. Must not be empty.
json-file queryguard.json The per-test query counts, relative to working-directory; uploaded as the artifact queryguard-json-<category>. Empty: none.
compare true On a pull request, compare the counts with the base branch and write the result to the job summary.
comment true Also post the comparison as a pull-request comment, updated in place on later pushes.
trend false Since 0.8.0, experimental. A number of runs N (2 to 100; true means 10): on pushes to the default branch and on pull requests, show how the counts moved over the last N runs, see below.
github-token github.token Token for the comparison, the trend, the comment and the changed files of lint: changed.
lint false Since 0.10.0, experimental. true: after pytest, run the static check on lint-paths with --format github, so its findings show as warnings on the lines of the pull request. changed: on a pull request, only the changed Python files in lint-paths. See below.
lint-models empty The modules that define or import your mapped classes, separated by spaces (app.models). Required when lint is not false.
lint-paths . Files and directories for the static check, relative to working-directory, split like pytest-args.

fail, upload, compare and comment take true or false (in any case) and nothing else: the action stops with an error on a value such as yes, 1 or an empty string, which would otherwise quietly mean false. trend takes false, true or a number from 2 to 100, and stops the same way on anything else. lint takes true, changed or false; when it is not false, lint-models must hold module names (letters, digits, _ and dots), or the action stops before pytest runs.

Outputs: exit-code (pytest's), sarif-file, json-file, trend-report (since 0.8.0: the trend's Markdown file, empty when there is none) and lint-exit-code (since 0.10.0: the static check's, 0 or 1, empty when it did not run).

Query counts on pull requests#

On every run the action writes the query counts and uploads them as an artifact. On a pull request it downloads the file of the latest finished run of the same workflow on the base branch (a push or scheduled run, never a pull-request run: a fork's pull request from its own main would otherwise count as the base), compares the two, and writes the result to the job summary and to one pull-request comment:

### pytest-queryguard: queries compared with the base branch

412 tests compared: 3120 -> 3187 statements (+67). 2 run more, 1 fewer; 1 new finding, 0 fixed.

#### New findings
| Kind | Label | Where | Times | Tests |
| relationship-load | `Order.items` | `app/orders.py in list_orders` | 50 | `tests/test_orders.py::test_list` |

#### Tests that run more statements
| Test | Before | After | Change |
| `tests/test_orders.py::test_list` | 3 | 53 | +50 |

A reviewer sees that a change made a test run more queries even when no rule fired yet (a new loop of two, a test under its budget). The comparison never fails the job.

Query counts over the last runs#

Since 0.8.0; experimental (see Stability).

The comparison shows one step; trend: "10" shows the last ten runs, as an APM shows a query count over time in production. On a push to the default branch and on a pull request, the action downloads the query-count artifacts of the latest finished runs of the same workflow on the (base) branch, adds the file of this run as the newest, and appends the trend to the job summary. On a pull request with a comment it is also folded into that comment, as a collapsed <details> block below the comparison.

### pytest-queryguard: query counts over the last 5 runs

5 runs, statements 3120 -> 3187 (+67) `▁▁▂▂█`. 3 tests changed their count, 2 new, 0 not in the latest run; 1 new finding, 0 gone.

| Run | Tests | Statements | |
| `1a2b3c4` | 410 | 3120 |  |
| ... | | | |
| `9f8e7d6 (this run)` | 412 | 3187 |  |

#### Tests whose count changed most
| Test | Runs | First | Last | Change |
| `tests/test_orders.py::test_list` | `▁▁▁▁█` | 3 | 53 | +50 |

The same report locally, from files given oldest first:

python -m pytest_queryguard.trend mon.json tue.json wed.json --top 20
python -m pytest_queryguard.trend runs/*.json --test "tests/test_orders.py::*" --format text

--format is markdown (the default), text or json; --test keeps the tests whose node id contains the pattern, or matches it when it is a glob; --label names the runs (once per file, default: the file names). The sparklines use Unicode blocks; --ascii prints _-~=+*#@ instead, and the console output falls back to it by itself when the console cannot print the blocks (a Windows console with cp1252). The exit status is 2 when a file cannot be read or is not a --queryguard-json file (--skip-unreadable leaves it out instead) or the --output file cannot be written, otherwise 0.

--format json prints one object with "format": 1 (the number goes up when a key changes meaning; new keys may be added): runs (per file, oldest first: label, tests, statements, complete), complete, changed (the tests whose count changed most, up to --top: nodeid, counts per run, null where the test did not run, first, last, change), changed_total, added_tests and gone_tests (how many tests are in the last run but not the first, and in an earlier run but not the last), new_findings and gone_findings (kind, label, file, function, count, tests; a new finding also has since, the label of the run from which on it is in every run). Like the rest of the trend it is experimental (see Stability).

A typical rollout: run once with fail: "false" to see the alerts, create a baseline for what you cannot fix yet, then switch to fail: "true" (the default).

The static check as annotations#

Add to the with: of the action:

          lint: changed            # or "true" for every file of lint-paths
          lint-models: app.models
          lint-paths: app

With lint, the action runs python -m pytest_queryguard.lint --format github --models=app.models -- PATHS in working-directory after pytest, the upload and the comparison, so that a check that cannot run does not keep those from running. The paths of the annotations are relative to the root of the checkout, also when actions/checkout puts it below the workspace with path:. Each finding is a workflow command, ::warning file=...,line=...,col=..., which GitHub shows as an annotation on that line of the pull request's diff and in the run's summary. The check imports lint-models (see Static check), so the step needs your project installed, as pytest does.

lint, lint-models, lint-paths and lint-exit-code are experimental (see Stability).

Permissions and forks#

Permissions per input#

Permission Needed by Without it
contents: read actions/checkout The checkout fails.
security-events: write upload: "true" The upload step fails (it has continue-on-error), the job does not.
actions: read compare, trend; the upload in a private repository The job summary or the log says the runs could not be listed.
pull-requests: write comment: "true" A warning in the log; the report stays in the job summary.
pull-requests: read lint: changed A warning in the log; every file of lint-paths is checked. pull-requests: write includes it.

Grant only what the inputs you use need: with upload: "false", compare: "false" and comment: "false" the job needs contents: read alone.

Limits and edge cases#

yaml concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true

Without the action#

      - run: pytest --queryguard-sarif=queryguard.sarif
        continue-on-error: true
      - uses: github/codeql-action/upload-sarif@v4
        if: always()
        with:
          sarif_file: queryguard.sarif
          category: pytest-queryguard

The upload step prints one warning per finding (Calculated fingerprint ... but found existing inconsistent fingerprint value). It is noise: the upload succeeds and alerts are matched correctly. See SARIF output for why.

Query counts as JSON#

pytest --queryguard-json=queryguard.json writes one entry per test: how many statements it ran, the same split by verb, the database time and the findings it found (after ignores). Keep the file from the main branch as an artifact and compare a pull request's file with it to see which tests started running more queries before anything fails.

{
  "format": 1,
  "tool": {"name": "pytest-queryguard", "version": "0.8.0"},
  "complete": true,
  "tests": {
    "tests/test_orders.py::test_list_orders": {
      "statements": 51,
      "by_verb": {"select": 51},
      "db_time": 0.0007,
      "truncated": false,
      "findings": [
        {"kind": "relationship-load", "label": "Order.customer", "count": 50,
         "file": "app/orders.py", "function": "list_orders", "line": 10,
         "stack": [{"file": "tests/test_orders.py", "function": "test_list_orders",
                    "line": 7}],
         "baselined": false,
         "message": "Order.customer was lazy-loaded 50 times\nfirst at app/orders.py:10 in list_orders\n..."}
      ],
      "max_queries_marker": false
    }
  }
}

How this repository tests the action#

The action job in .github/workflows/ci.yml runs the local action (uses: ./action) on examples/action-sample, a project with one N+1 query: once with fail: "false" (the SARIF file is checked, including that its URI starts with examples/action-sample/, the working directory), once expecting the step to fail, and once with the finding in a baseline. The first run also has trend: "5"; when the trend wrote a report, the job checks that it has this run's row. None of them uploads: a sample upload with no results would make every pull request report "1 configuration not found" in its checks.

tests/test_action_steps.py runs the shell steps of action/action.yml with crafted inputs, among them the install step in both layouts: with a pyproject.toml above the action (this repository) and with a wheel in dist/ (the action repository). The action repository's own workflow runs the copy there, with the default package, on a project like examples/action-sample.

Edit this page on GitHub