Skip to content

Commit

Permalink
Add parameter info to fixture assert_num_queries to display additiona…
Browse files Browse the repository at this point in the history
…l message on failure.
  • Loading branch information
MrtnBckr authored and blueyed committed Oct 30, 2018
1 parent 39d3e5c commit 9f334a0
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 3 deletions.
6 changes: 4 additions & 2 deletions docs/helpers.rst
Original file line number Diff line number Diff line change
Expand Up @@ -286,8 +286,10 @@ Example
This fixture allows to check for an expected number of DB queries.

It wraps `django.test.utils.CaptureQueriesContext`. A non-default DB
connection can be passed in using the `connection` keyword argument, and it
will yield the wrapped CaptureQueriesContext instance.
connection can be passed in using the `connection` keyword argument, an
additional info message which is displayed on fail can be passed in using
the `info` keyword argument, and it will yield the wrapped
CaptureQueriesContext instance.


Example
Expand Down
4 changes: 3 additions & 1 deletion pytest_django/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,7 @@ def _live_server_helper(request):


@contextmanager
def _assert_num_queries(config, num, exact=True, connection=None):
def _assert_num_queries(config, num, exact=True, connection=None, info=None):
from django.test.utils import CaptureQueriesContext

if connection is None:
Expand All @@ -429,6 +429,8 @@ def _assert_num_queries(config, num, exact=True, connection=None):
num_performed == 1 and "1 was" or "%d were" % (num_performed,)
),
)
if info:
msg += "\n{}".format(info)
if verbose:
sqls = (q["sql"] for q in context.captured_queries)
msg += "\n\nQueries:\n========\n\n%s" % "\n\n".join(sqls)
Expand Down
26 changes: 26 additions & 0 deletions tests/test_fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,32 @@ def test_django_assert_num_queries_db_connection(django_assert_num_queries):
pass


@pytest.mark.django_db
def test_django_assert_num_queries_output_info(django_testdir):
django_testdir.create_test_module("""
from django.contrib.contenttypes.models import ContentType
import pytest
@pytest.mark.django_db
def test_queries(django_assert_num_queries):
with django_assert_num_queries(
num=2,
info="Expected: 1 for select all, 1 for count"
):
list(ContentType.objects.all())
ContentType.objects.count()
ContentType.objects.first() # additional wrong query
""")
result = django_testdir.runpytest_subprocess('--tb=short', '-v')
result.stdout.fnmatch_lines([
'*Expected to perform 2 queries but 3 were done*',
'*Expected: 1 for select all, 1 for count*',
'*Queries:*',
'*========*',
])
assert result.ret == 1


class TestSettings:
"""Tests for the settings fixture, order matters"""

Expand Down

0 comments on commit 9f334a0

Please sign in to comment.