Tests with several sessions or requests#
The repeat rules count how often something happens. By default they count over the whole test, and a test that makes several independent requests then looks like a loop although nothing loops:
def test_five_requests(client, org):
for _ in range(5):
client.get(f"/orgs/{org.id}") # each request: its own Session, the
# same authentication lookup
Every request opens its own Session, runs the same lookups, and closes it.
The statement runs five times in the test and once in each request.
Sessions begun on separate lines#
A store or service that opens a Session per call, called on separate lines
of a test with no loop, runs its shared lookup once per call:
def test_set_tag(store):
store.set_tag(1, "a", "x") # each call: its own Session, and the
store.set_tag(2, "a", "y") # same lookup in a shared helper
assert store.get_tags(1) == {"a": "x"}
assert store.get_tags(2) == {"a": "y"}
The default scope counts these on their own, without any option. When a
Session (or a connection checkout) begins, the plugin notes the application
lines on the stack, from its first statement up to the test, as for a call
site's callers. A Session begun from lines that no other Session of the
test began from is counted alone. The Sessions begun from the same lines (a
loop, a comprehension, asyncio.gather, a thread pool, each depth of a
recursion) are counted together, and so are all others whose lines repeat,
whatever lines each began from: a loop whose passes call two store methods in
turn is not split in two. A loop of three passes and three separate calls is
a run of three, not of six.
Requests that the application handles in another thread (Starlette's
TestClient runs it in a portal thread) have no frame of the test on their
stack: they begin from the same handler lines and are counted together as
before. Sessions begun before the test (a fixture's) and those begun from
lines first seen after 100,000 different ones in one test are counted
together too. A pass of a loop whose Session begins from lines no other
pass began from (a branch or a handler taken in one pass only) counts on its
own, outside the loop: two passes through an if and its else look like
two separate calls, and so does a call that primes a loop before it
(page = store.first() and then store.next(page) in the loop), which then
needs the threshold without it. As with queryguard_scope = session, a
rule reports one finding per relationship or statement, from the unit with
the most; another unit's N+1 of the same relationship is reported once that
one is fixed.
Requests on separate lines in one Session#
A test whose requests all use one Session (an application context pushed
once for the suite, a scoped session that the requests share) has one scope,
and the Sessions cannot tell the requests apart:
def test_update_then_read(client):
client.post("/vulns", json=VULN) # each request: the same workspace
client.patch("/vulns/1", json=EDIT) # lookup and one lazy load, in the
client.get("/vulns/1") # Session all requests share
The default scope tells them apart by the call path of each statement (see Calls on separate lines): the requests sent from separate lines of the test are calls on separate lines, and each request's lookup and lazy load count on their own. Requests sent in a loop of the test have one call path, as an N+1 in the application has, and add up; a statement or load that each request runs once is then the test code's repetition (see Loops of the test). Requests handled in another thread add up, as above.
The option#
[tool.pytest.ini_options]
queryguard_scope = "session"
| Value | What is counted together |
|---|---|
test (default) |
Everything the test runs, except Sessions begun from lines of their own (see above); with Django, each request of the test client still counts on its own (Django). |
session |
The statements, lazy loads, column loads and writes of one scope. A finding needs one scope to reach the threshold. |
It applies to four kinds: repeated-statement (also the small-repeat rule),
relationship-load, column-load and write-loop. missing-index and
unused-eager-load do not count occurrences and are not affected. The default
stays test, so an upgrade changes nothing until you set the option.
Before 0.8.0 the option was called queryguard_repeat_scope (and the argument
below repeat_scope=), although it scopes more than the repeat rule. The old
names still work until 2.0 and emit a QueryGuardDeprecationWarning; setting
both names to different values is a usage error.
With test, a finding whose occurrences come from more than one scope says so:
the same statement ran 9 times across 8 different Sessions or connection checkouts
first at app/auth.py:31 in current_user
kind: repeated-statement label: SELECT users.id FROM users WHERE users.token = ?
docs: https://maciejziel.github.io/pytest-queryguard/how-detection-works.html#repeated-statement
note: if each belongs to a separate request or unit of work, this is not a
loop; set queryguard_scope = session to count each Session on its
own (QueryLog.assert_no_nplusone: scope='session')
With session, the message says ran 6 times in one Session or connection
checkout, and the count is the largest one scope has. The identity of a finding
(kind, label, file and function) and the baseline format do not change.
QueryLog.assert_no_nplusone(scope="session") does the same for a
recorded block; like the thresholds it does not read the ini option.
How the scope is decided#
- A statement run through a
Session(ORM queries,session.execute(text()),session.connection()) belongs to thatSession: the plugin listens toafter_begin, which hands it theSessionand the connection it opened for the transaction. All transactions of oneSessionare one scope, so a loop with acommit()in every round is still a loop. - A statement on a connection no
Sessionopened (engine.connect(), Core) is one scope per connection checkout. A checkout that runscommit()and goes on is still one scope. - Lazy loads and column loads belong to the
Sessionthat loaded them. - Async works the same:
AsyncSessionandAsyncConnectionwrap a syncSessionandConnection, and those are what the plugin sees. Concurrent tasks each have their ownAsyncSession, so they are separate scopes. - A pooled or
StaticPoolconnection that several checkouts share does not merge their scopes: every checkout gets a newConnectionobject, which is what the scope is attached to. ASessionbound to oneConnectionthat severalSessions share (the "test transaction" pattern) is separated bySession, because eachSessiontransaction tags the connection again.
Limits#
- One
Sessionis one scope. If a test passes the sameSessionto every request (a dependency override that returns the fixture's session), the requests are one scope and the repeats of requests sent in a loop add up again. Give each request its ownSessionin the override, or keeptest. To keep the test's rolled-back transaction, bind each request'sSessionto the test's connection withjoin_transaction_mode="create_savepoint"; see A session per request in a test transaction. - Two
Sessions that use one sharedConnectionat the same time are not told apart; the later transaction'sSessionwins until the next one starts. - A loop that opens a new
Sessionper round (for x in xs: with Session() as s: s.get(...)) is a real N+1 thatsessioncannot see, because every round is its own scope. Withtestit is reported, with the note above. This is the cost of the option; check that a report with the note is really independent requests before you set it. - A statement the plugin cannot attach to a
SessionorConnectionobject (a connection type that refuses attributes) counts as one unknown scope. - The scope is attached to the Python objects, not to the database transaction, so it is unrelated to isolation levels or the pool.