Skip to content

Commit d96a0a3

Browse files
committed
Display the number of queries executed by the fixtures
when --querycount is used with --setup-show
1 parent b735a05 commit d96a0a3

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
@@ -323,6 +323,32 @@ def pytest_runtest_setup(item):
323323
_disable_class_methods(cls)
324324

325325

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