Skip to content

Commit 843a9e5

Browse files
committed
Display the number of queries executed by the fixtures
when --querycount is used with --setup-show
1 parent 40eb9b6 commit 843a9e5

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

pytest_django/plugin.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,32 @@ def pytest_runtest_setup(item):
324324
_disable_class_methods(cls)
325325

326326

327+
@pytest.hookimpl(hookwrapper=True)
328+
def pytest_fixture_setup(fixturedef, request):
329+
config = request.config
330+
331+
if config.option.querycount is None or not config.option.setupshow:
332+
yield
333+
return
334+
335+
from django.test.utils import CaptureQueriesContext
336+
from django.db import connection
337+
338+
with CaptureQueriesContext(connection) as context:
339+
yield
340+
341+
querycount = len(context.captured_queries)
342+
343+
if querycount:
344+
capman = config.pluginmanager.getplugin('capturemanager')
345+
capman.suspendcapture()
346+
347+
tw = config.get_terminal_writer()
348+
tw.write(' (# queries executed: {})'.format(querycount))
349+
350+
capman.resumecapture()
351+
352+
327353
@pytest.hookimpl(hookwrapper=True)
328354
def pytest_runtest_call(item):
329355
count_parameter = item.config.option.querycount

tests/test_report.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,3 +88,25 @@ def test_two_queries():
8888
)
8989
assert 'test_two_queries' in lines[0]
9090
assert 'test_one_query' in lines[1]
91+
92+
def test_should_report_fixture_queries(self, django_testdir):
93+
django_testdir.create_test_module('''
94+
import pytest
95+
from django.db import connection
96+
97+
@pytest.fixture
98+
def one_query():
99+
with connection.cursor() as cursor:
100+
cursor.execute('SELECT 1')
101+
102+
@pytest.mark.django_db
103+
def test_without_queries(one_query):
104+
pass
105+
''')
106+
107+
result = django_testdir.runpytest_subprocess(
108+
'--setup-show',
109+
'--querycount=5'
110+
)
111+
112+
assert '(# queries executed: 1)' in result.stdout.str()

0 commit comments

Comments
 (0)