Metadata-Version: 2.4
Name: dj-mercury
Version: 0.1.0
Summary: Counts what a Django test costs in trips to the database, and fails it when that cost is a bug.
License-Expression: AGPL-3.0-only
Project-URL: Repository, https://git.stormdevelopments.ca/official-public/dj-mercury
Keywords: django,testing,performance,queries,n+1
Classifier: Framework :: Django
Classifier: Framework :: Django :: 5.2
Classifier: Framework :: Django :: 6.0
Classifier: Framework :: Django :: 6.1
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Testing
Classifier: Typing :: Typed
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: django>=5.2
Provides-Extra: dev
Requires-Dist: ruff==0.17.6; extra == "dev"
Requires-Dist: mypy<3.0,>=1.13; extra == "dev"
Requires-Dist: psycopg[binary]>=3.2; extra == "dev"
Dynamic: license-file

<img src="icon.svg" alt="" width="96" align="right">

# dj-mercury

[![CI](https://git.stormdevelopments.ca/official-public/dj-mercury/actions/workflows/test.yml/badge.svg)](https://git.stormdevelopments.ca/official-public/dj-mercury/actions)
[![License: AGPL-3.0](https://img.shields.io/badge/license-AGPL--3.0-blue.svg)](https://git.stormdevelopments.ca/official-public/dj-mercury/src/branch/main/LICENSE)
![76 tests](https://img.shields.io/badge/tests-76-blue.svg)
![11 source files](https://img.shields.io/badge/source_files-11-blue.svg)
![1 dependency](https://img.shields.io/badge/dependencies-1-blue.svg)

Mercury counts what a Django test costs in trips to the database, and fails the
test when that cost is a bug.

On a laptop the database is next door, so forty queries look free. In
production each one is a round trip over a network, and the same forty are the
slow page. A stopwatch on your laptop cannot see that. A count can.

```python
from dj_mercury import performance_monitor


class OrderListTests(TestCase):
    def test_order_list(self):
        with performance_monitor(queries=4):
            self.client.get("/orders/")
```

```text
Mercury FAILED: orders/tests/test_views.py:12 in OrderListTests.test_order_list
  round trips      31 (limit 4)
  round-trip cost  at least 62 ms, at 2 ms per round trip
  stopwatch        4.1 ms on this machine, never a reason to fail
  most rows        30 from one query
  repeated query   30 times from orders/views.py:18
      SELECT "orders_customer"."id", "orders_customer"."name" FROM "orders_customer" WHERE "orders_customer"."id" = ? LIMIT ?
  fails: A query repeated 30 times from orders/views.py:18.
  fails: 31 round trips, over the limit of 4.
```

## Install

```text
pip install dj-mercury
```

Python 3.12 or newer, Django 5.2 or newer. Django is the only dependency.
`performance_monitor()` needs no setup. Add `"dj_mercury"` to `INSTALLED_APPS`
only if you want the `mercury` command or a hunt.

## What fails with no limit written

Two things are bugs whatever the page, so they fail a block on their own.

- **A repeated query.** The same query, with different values, sent from the
  same line of your code three or more times. That is a loop asking the database
  once per row. Three lookups from three different lines are three decisions,
  and pass.
- **An exact duplicate.** The same query with the same values, more than once.

Everything else is reported and fails only against a limit you write. Mercury
ships no limits of its own: the right number for your page is yours to know.

## Options

| Option | Fails the block when | Default |
|--------|----------------------|---------|
| `queries` | it makes more round trips than this | no limit |
| `rows` | one query returns more rows than this | no limit |
| `round_trip_cost_ms` | its round-trip cost is above this | no limit |
| `round_trip_ms` | never: it is the distance to your database | not set |
| `repeats` | one line sends the same query this many times | `3` |
| `duplicates` | `True`, and a query repeats with the same values | `True` |
| `report_file` | never: it is where the run's report is written | not set |

An option can be written in three places, and the nearest one wins.

```python
# settings.py: the whole project
MERCURY_PERFORMANCE_TESTING = {"round_trip_ms": 2, "queries": 20}

# the top of a test file: every block written in that file
MERCURY_PERFORMANCE_TESTING = {"queries": 8}

# one block
with performance_monitor(queries=3, duplicates=False):
    ...
```

Each place changes only the options it names. The file above still measures at
2 ms per round trip. `None` removes a limit for one block. `report_file` belongs
to the whole run, so it is set in settings only.

## Round-trip cost

`round_trip_ms` is the average delay you expect on a round trip to your
database, wherever it is hosted. Time a trivial query from your app server to
find it: about 0.1 ms on the same machine, 0.5 to 2 ms in the same data centre,
10 ms and up across regions.

Round-trip cost is round trips multiplied by that number. It is arithmetic, so
it is the same on every machine. It is a floor: it counts the network wait and
nothing the database does. With no `round_trip_ms` set, Mercury reports counts
and leaves the cost out.

Stopwatch time, the milliseconds the block really took, is reported and can
never fail a test. A limit that passes on your laptop and fails on a busy CI
runner teaches people to ignore the tool.

## Run only the performance tests

```text
python manage.py mercury
python manage.py mercury orders --output mercury-report.md
```

`mercury` reads your test files, finds the tests that use
`performance_monitor`, prints them, and runs exactly those through Django's own
test runner. It takes the options `manage.py test` takes. `--output` writes the
run's report as Markdown, which a CI job can keep.

A test counts if it uses `performance_monitor` itself or calls a function or
method in the same file that does. A helper in another file is not followed, so
the list Mercury prints is the list it runs. If it finds none it exits with
status 5 and runs nothing.

Outside the command, set `report_file` in settings and any test run writes the
same report.

## Hunt through the tests you already have

A project that has never counted its queries does not know where to start. A
hunt answers that from the tests you already have, with nothing new to write.

```text
python manage.py mercury --hunt
python manage.py mercury --hunt orders --output hunt.md
```

A hunt runs every test, not only the performance tests, and watches each page a
test loads through Django's test client. It fails nothing. When the run ends it
writes `mercury-hunt.md`, one entry per finding:

````markdown
## repeated query, 4 times from `accounts/gates.py:47`

- seen on 995 page loads, worst on `GET /dashboard/`

```sql
SELECT ? AS "a" FROM "auth_group" WHERE "auth_group"."name" = ? LIMIT ?
```
````

Read an entry as: this line sent this query 4 times while one page loaded, and
995 page loads met it. Entries are ordered by page loads, so the query every
page pays for comes before the one bad page.

Then fix the first entry, wrap that page's test in `performance_monitor` so it
stays fixed, and hunt again.

What to expect:

- **Some findings are not loops.** Test data is small, so a hunt notes a query
  sent twice from one line, where a monitored block waits for three.
- **One line can appear twice**, once as a repeated query and once as an exact
  duplicate.
- **It sees only pages loaded with `self.client`.** Code a test calls directly
  and the async client are not watched, and a test that errors before it loads
  a page adds nothing.
- **It is a full test run.** It takes as long as your suite and works under
  `--parallel`. Run one at a time: two runs on the same test database spoil
  each other.

## What it does not do

- **Async tests.** A block inside an `async def` test raises an error. It does
  not pass silently with a count of zero.
- **Parallel reports.** Under `--parallel` the tests run and fail as usual, but
  no report file is written, and one line says so.
- **Values.** A report shows the shape of a query, never the values in it, so a
  report kept by CI carries nothing from your fixtures.
- **Raw cursor iteration.** Rows read by looping over a raw cursor are not
  counted. Rows the ORM fetches are.
- **Templates.** A query fired while a template renders is reported at the line
  of your code that rendered it.
- **Advice.** Mercury says what ran, how often and from where.

## Development

`make gates` runs formatting, lint, strict types and the tests on SQLite. CI also
runs the tests on PostgreSQL; `make test-postgres` does the same against a
server you point it at.
The words Mercury uses are defined in `CONTEXT.md`.

## License

AGPL-3.0. The full text is in the `LICENSE` file.

Maintained by [Storm Developments](https://stormdevelopments.ca).
