python / expert
Snippet
Dynamic Query Count Validation Context Manager for Unit Testing
This expert testing pattern utilizes Django's CaptureQueriesContext alongside Python's @contextmanager generator standard to build dynamic SQL query assertions during unit testing. Unlike standard assertNumQueries, this wrapper allows setting flexible upper bounds on database interactions across complex test scenarios.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
from contextlib import contextmanagerfrom django.db import connectionfrom django.test.utils import CaptureQueriesContext@contextmanagerdef assert_max_queries(max_queries: int):with CaptureQueriesContext(connection) as ctx:yield ctxquery_count = len(ctx.captured_queries)assert query_count <= max_queries, f"Expected <={max_queries} queries, got {query_count}"
django
Breakdown
1
from contextlib import contextmanager
Imports the contextmanager decorator to construct generator-based context managers.
2
from django.db import connection
Retrieves the active Django default database connection instance.
3
from django.test.utils import CaptureQueriesContext
Imports Django test utility for capturing raw SQL queries generated within an execution block.
4
@contextmanager
Decorates generator function to implement context management entry and exit protocols.
5
def assert_max_queries(max_queries: int):
Defines helper accepting integer bound for allowed SQL database queries.
6
with CaptureQueriesContext(connection) as ctx:
Instantiates capture context listener around yielding execution scope.
7
yield ctx
Pauses execution yielding context object allowing inner block evaluation.
8
query_count = len(ctx.captured_queries)
Calculates total count of executed SQL statements recorded during yielding.
9
assert query_count <= max_queries, f"Expected <={max_queries} queries, got {query_count}"
Evaluates assertion validating executed queries do not exceed designated upper threshold.