Skip to content

Commit 7a655f8

Browse files
committed
_assert_num_queries: support any connection
1 parent b1d93fc commit 7a655f8

File tree

3 files changed

+30
-4
lines changed

3 files changed

+30
-4
lines changed

docs/helpers.rst

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -249,8 +249,13 @@ Example
249249
``django_assert_num_queries``
250250
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
251251

252+
.. fixture:: django_assert_num_queries
253+
252254
This fixture allows to check for an expected number of DB queries.
253-
It currently only supports the default database.
255+
256+
It wraps `django.test.utils.CaptureQueriesContext`. A non-default DB
257+
connection can be passed in using the `connection` keyword argument, and it
258+
will yield the wrapped CaptureQueriesContext instance.
254259

255260

256261
Example
@@ -270,8 +275,11 @@ Example
270275
``django_assert_max_num_queries``
271276
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
272277

278+
.. fixture:: django_assert_max_num_queries
279+
273280
This fixture allows to check for an expected maximum number of DB queries.
274-
It currently only supports the default database.
281+
282+
It is a specialized version of :fixture:`django_assert_num_queries`.
275283

276284

277285
Example

pytest_django/fixtures.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -355,9 +355,12 @@ def _live_server_helper(request):
355355

356356

357357
@contextmanager
358-
def _assert_num_queries(config, num, exact=True):
359-
from django.db import connection
358+
def _assert_num_queries(config, num, exact=True, connection=None):
360359
from django.test.utils import CaptureQueriesContext
360+
361+
if connection is None:
362+
from django.db import connection
363+
361364
verbose = config.getoption('verbose') > 0
362365
with CaptureQueriesContext(connection) as context:
363366
yield context

tests/test_fixtures.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,6 +138,21 @@ def test_queries(django_assert_num_queries):
138138
assert result.ret == 1
139139

140140

141+
@pytest.mark.django_db
142+
def test_django_assert_num_queries_db_connection(django_assert_num_queries):
143+
from django.db import connection
144+
145+
with django_assert_num_queries(1, connection=connection):
146+
Item.objects.create(name='foo')
147+
148+
with django_assert_num_queries(1, connection=None):
149+
Item.objects.create(name='foo')
150+
151+
with pytest.raises(AttributeError):
152+
with django_assert_num_queries(1, connection=False):
153+
pass
154+
155+
141156
class TestSettings:
142157
"""Tests for the settings fixture, order matters"""
143158

0 commit comments

Comments
 (0)