python / expert
Snippet
Custom TestCase Mixin for Programmatic SQL Query Count Assertions
By subclassing Django's `CaptureQueriesContext`, you can write custom test mixins that measure executed database queries and fail unit tests dynamically when query boundaries are exceeded.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
from django.test import TestCasefrom django.test.utils import CaptureQueriesContextfrom django.db import connectionclass AssertQueryLimitMixin:def assert_max_queries(self, limit: int):class QueryContextManager(CaptureQueriesContext):def __exit__(self, exc_type, exc_val, exc_tb):super().__exit__(exc_type, exc_val, exc_tb)query_count = len(self.captured_queries)if query_count > limit:raise AssertionError(f'Query limit exceeded: {query_count} > {limit}')return QueryContextManager(connection)
django
Breakdown
1
class AssertQueryLimitMixin:
Defines a reusable test mixin for database query boundary inspection.
2
class QueryContextManager(CaptureQueriesContext):
Extends Django SQL query capturing context manager.
3
if query_count > limit:
Compares the total captured SQL queries against the specified threshold and raises an AssertionError if exceeded.