authentik.lib.tests.utils

Test utils

 1"""Test utils"""
 2
 3from collections.abc import Generator
 4from contextlib import contextmanager
 5from dataclasses import dataclass
 6from inspect import currentframe
 7from pathlib import Path
 8from unittest import SkipTest
 9
10from django.db import connection
11from django.db.models import Model
12
13
14def load_fixture(path: str, path_only=False, **kwargs) -> str:
15    """Load fixture, optionally formatting it with kwargs"""
16    current = currentframe()
17    parent = current.f_back
18    calling_file_path = parent.f_globals["__file__"]
19    fixture_path = Path(calling_file_path).resolve().parent / Path(path)
20    if path_only:
21        return fixture_path
22    with open(fixture_path, encoding="utf-8") as _fixture:
23        fixture = _fixture.read()
24        try:
25            return fixture % kwargs
26        except TypeError, ValueError:
27            return fixture
28
29
30@dataclass
31class RowCounts:
32    """Rows read from and deleted in one table"""
33
34    read: int = 0
35    deleted: int = 0
36
37
38def _table_counts(model: type[Model]) -> tuple[int, int]:
39    with connection.cursor() as cursor:
40        # Make rows read by already committed transactions visible, see
41        # https://www.postgresql.org/docs/current/monitoring-stats.html
42        cursor.execute("SELECT pg_stat_force_next_flush()")
43        cursor.execute("SELECT pg_stat_clear_snapshot()")
44        cursor.execute(
45            "SELECT t.seq_tup_read + coalesce(t.idx_tup_fetch, 0) "
46            "+ x.seq_tup_read + coalesce(x.idx_tup_fetch, 0), t.n_tup_del + x.n_tup_del "
47            "FROM pg_stat_user_tables t JOIN pg_stat_xact_user_tables x USING (relid) "
48            "WHERE relid = %s::regclass",
49            [model._meta.db_table],
50        )
51        return cursor.fetchone()
52
53
54@contextmanager
55def table_row_counts(model: type[Model]) -> Generator[RowCounts]:
56    """Count the rows the enclosed code reads from and deletes in `model`'s table.
57
58    Reads Postgres' statistics counters only, so it doesn't change how queries are planned or
59    run. Unlike timing, the counts are the same on every machine. Note that Postgres plans
60    small test tables differently from large ones, so a query that is cheap here can still
61    scan a whole table in production."""
62    counts = RowCounts()
63    # https://pgpedia.info/p/pg_stat_force_next_flush.html
64    min_postgres_version = 15
65    # https://www.postgresql.org/docs/current/libpq-status.html#LIBPQ-PQSERVERVERSION
66    if connection.pg_version // 10000 < min_postgres_version:
67        raise SkipTest(f"Row counts need PostgreSQL {min_postgres_version} or newer")
68    with connection.cursor() as cursor:
69        cursor.execute(f"ANALYZE {model._meta.db_table}")
70    read, deleted = _table_counts(model)
71    yield counts
72    after_read, after_deleted = _table_counts(model)
73    counts.read, counts.deleted = after_read - read, after_deleted - deleted
def load_fixture(path: str, path_only=False, **kwargs) -> str:
15def load_fixture(path: str, path_only=False, **kwargs) -> str:
16    """Load fixture, optionally formatting it with kwargs"""
17    current = currentframe()
18    parent = current.f_back
19    calling_file_path = parent.f_globals["__file__"]
20    fixture_path = Path(calling_file_path).resolve().parent / Path(path)
21    if path_only:
22        return fixture_path
23    with open(fixture_path, encoding="utf-8") as _fixture:
24        fixture = _fixture.read()
25        try:
26            return fixture % kwargs
27        except TypeError, ValueError:
28            return fixture

Load fixture, optionally formatting it with kwargs

@dataclass
class RowCounts:
31@dataclass
32class RowCounts:
33    """Rows read from and deleted in one table"""
34
35    read: int = 0
36    deleted: int = 0

Rows read from and deleted in one table

RowCounts(read: int = 0, deleted: int = 0)
read: int = 0
deleted: int = 0
@contextmanager
def table_row_counts( model: type[django.db.models.base.Model]) -> Generator[RowCounts]:
55@contextmanager
56def table_row_counts(model: type[Model]) -> Generator[RowCounts]:
57    """Count the rows the enclosed code reads from and deletes in `model`'s table.
58
59    Reads Postgres' statistics counters only, so it doesn't change how queries are planned or
60    run. Unlike timing, the counts are the same on every machine. Note that Postgres plans
61    small test tables differently from large ones, so a query that is cheap here can still
62    scan a whole table in production."""
63    counts = RowCounts()
64    # https://pgpedia.info/p/pg_stat_force_next_flush.html
65    min_postgres_version = 15
66    # https://www.postgresql.org/docs/current/libpq-status.html#LIBPQ-PQSERVERVERSION
67    if connection.pg_version // 10000 < min_postgres_version:
68        raise SkipTest(f"Row counts need PostgreSQL {min_postgres_version} or newer")
69    with connection.cursor() as cursor:
70        cursor.execute(f"ANALYZE {model._meta.db_table}")
71    read, deleted = _table_counts(model)
72    yield counts
73    after_read, after_deleted = _table_counts(model)
74    counts.read, counts.deleted = after_read - read, after_deleted - deleted

Count the rows the enclosed code reads from and deletes in model's table.

Reads Postgres' statistics counters only, so it doesn't change how queries are planned or run. Unlike timing, the counts are the same on every machine. Note that Postgres plans small test tables differently from large ones, so a query that is cheap here can still scan a whole table in production.