| 1 |
from django.core.management.color import no_style |
| 2 |
from django.db import DEFAULT_DB_ALIAS, connection, connections, transaction |
| 3 |
|
| 4 |
from django.test import TransactionTestCase |
| 5 |
from django.test.utils import CaptureQueriesContext |
| 6 |
|
| 7 |
from ..utils import _get_tables |
| 8 |
from .models import PostgresModel |
| 9 |
|
| 10 |
|
| 11 |
class TestUtilsMixin: |
| 12 |
def setUp(self): |
| 13 |
self.is_sqlite = connection.vendor == 'sqlite' |
| 14 |
self.is_mysql = connection.vendor == 'mysql' |
| 15 |
self.is_postgresql = connection.vendor == 'postgresql' |
| 16 |
self.force_reopen_connection() |
| 17 |
|
| 18 |
# TODO: Remove this workaround when this issue is fixed: |
| 19 |
# https://code.djangoproject.com/ticket/29494 |
| 20 |
def tearDown(self): |
| 21 |
if connection.vendor == 'postgresql': |
| 22 |
flush_args = [no_style(), (PostgresModel._meta.db_table,),] |
| 23 |
flush_sql_list = connection.ops.sql_flush(*flush_args) |
| 24 |
with transaction.atomic(): |
| 25 |
for sql in flush_sql_list: |
| 26 |
with connection.cursor() as cursor: |
| 27 |
cursor.execute(sql) |
| 28 |
|
| 29 |
def force_reopen_connection(self): |
| 30 |
if connection.vendor in ('mysql', 'postgresql'): |
| 31 |
# We need to reopen the connection or Django |
| 32 |
# will execute an extra SQL request below. |
| 33 |
connection.cursor() |
| 34 |
|
| 35 |
def assert_tables(self, queryset, *tables): |
| 36 |
tables = {table if isinstance(table, str) |
| 37 |
else table._meta.db_table for table in tables} |
| 38 |
self.assertSetEqual(_get_tables(queryset.db, queryset.query), tables, str(queryset.query)) |
| 39 |
|
| 40 |
def assert_query_cached(self, queryset, result=None, result_type=None, |
| 41 |
compare_results=True, before=1, after=0): |
| 42 |
if result_type is None: |
| 43 |
result_type = list if result is None else type(result) |
| 44 |
with self.assertNumQueries(before): |
| 45 |
data1 = queryset.all() |
| 46 |
if result_type is list: |
| 47 |
data1 = list(data1) |
| 48 |
with self.assertNumQueries(after): |
| 49 |
data2 = queryset.all() |
| 50 |
if result_type is list: |
| 51 |
data2 = list(data2) |
| 52 |
if not compare_results: |
| 53 |
return |
| 54 |
assert_functions = { |
| 55 |
list: self.assertListEqual, |
| 56 |
set: self.assertSetEqual, |
| 57 |
dict: self.assertDictEqual, |
| 58 |
} |
| 59 |
assert_function = assert_functions.get(result_type, self.assertEqual) |
| 60 |
assert_function(data2, data1) |
| 61 |
if result is not None: |
| 62 |
assert_function(data2, result) |
| 63 |
|
| 64 |
class FilteredTransactionTestCase(TransactionTestCase): |
| 65 |
""" |
| 66 |
TransactionTestCase with assertNumQueries that ignores BEGIN, COMMIT and ROLLBACK |
| 67 |
queries. |
| 68 |
""" |
| 69 |
def assertNumQueries(self, num, func=None, *args, using=DEFAULT_DB_ALIAS, **kwargs): |
| 70 |
conn = connections[using] |
| 71 |
|
| 72 |
context = FilteredAssertNumQueriesContext(self, num, conn) |
| 73 |
if func is None: |
| 74 |
return context |
| 75 |
|
| 76 |
with context: |
| 77 |
func(*args, **kwargs) |
| 78 |
|
| 79 |
|
| 80 |
class FilteredAssertNumQueriesContext(CaptureQueriesContext): |
| 81 |
""" |
| 82 |
Capture queries and assert their number ignoring BEGIN, COMMIT and ROLLBACK queries. |
| 83 |
""" |
| 84 |
EXCLUDE = ('BEGIN', 'COMMIT', 'ROLLBACK') |
| 85 |
|
| 86 |
def __init__(self, test_case, num, connection): |
| 87 |
self.test_case = test_case |
| 88 |
self.num = num |
| 89 |
super().__init__(connection) |
| 90 |
|
| 91 |
def __exit__(self, exc_type, exc_value, traceback): |
| 92 |
super().__exit__(exc_type, exc_value, traceback) |
| 93 |
if exc_type is not None: |
| 94 |
return |
| 95 |
|
| 96 |
filtered_queries = [] |
| 97 |
excluded_queries = [] |
| 98 |
for q in self.captured_queries: |
| 99 |
if q['sql'].upper() not in self.EXCLUDE: |
| 100 |
filtered_queries.append(q) |
| 101 |
else: |
| 102 |
excluded_queries.append(q) |
| 103 |
|
| 104 |
executed = len(filtered_queries) |
| 105 |
|
| 106 |
self.test_case.assertEqual( |
| 107 |
executed, |
| 108 |
self.num, |
| 109 |
f"\n{executed} queries executed on {self.connection.vendor}, {self.num} expected\n" + |
| 110 |
"\nCaptured queries were:\n" + |
| 111 |
"".join( |
| 112 |
f"{i}. {query['sql']}\n" |
| 113 |
for i, query in enumerate(filtered_queries, start=1) |
| 114 |
) + |
| 115 |
"\nCaptured queries, that were excluded:\n" + |
| 116 |
"".join( |
| 117 |
f"{i}. {query['sql']}\n" |
| 118 |
for i, query in enumerate(excluded_queries, start=1) |
| 119 |
) |
| 120 |
) |