Skip to content

Unblock DB in case of error for reports #778

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions pytest_django/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,16 @@ def pytest_runtest_setup(item):
_disable_class_methods(item.cls)


@pytest.hookimpl(hookwrapper=True, tryfirst=True)
def pytest_runtest_makereport(item):
if _blocking_manager._cm_exit_error:
with _blocking_manager.unblock():
yield
_blocking_manager._cm_exit_error = None
else:
yield


def pytest_collection_modifyitems(session, config, items):
def get_order_number(test):
marker_db = test.get_closest_marker('django_db')
Expand Down Expand Up @@ -747,6 +757,8 @@ def __enter__(self):
pass

def __exit__(self, exc_type, exc_value, traceback):
if exc_type:
self._db_blocker._cm_exit_error = (exc_type, exc_value, traceback)
self._db_blocker.restore()


Expand All @@ -759,6 +771,14 @@ class _DatabaseBlocker(object):
def __init__(self):
self._history = []
self._real_ensure_connection = None
self._cm_exit_error = None

@property
def _is_blocked(self):
if self._real_ensure_connection is None:
# Skip loading Django if not used.
return False
return self._dj_db_wrapper.ensure_connection == self._blocking_wrapper

@property
def _dj_db_wrapper(self):
Expand Down
29 changes: 29 additions & 0 deletions tests/test_db_access_in_repr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@


def test_db_access_with_repr_in_report(django_testdir):
django_testdir.create_test_module(
"""
import pytest

from .app.models import Item

def test_via_db_blocker(django_db_setup, django_db_blocker):
with django_db_blocker.unblock():
Item.objects.get(name='This one is not there')

def test_via_db_fixture(db):
Item.objects.get(name='This one is not there')
"""
)

result = django_testdir.runpytest_subprocess("--tb=auto")
result.stdout.fnmatch_lines([
"tpkg/test_the_test.py FF",
"E *DoesNotExist: Item matching query does not exist.",
"tpkg/test_the_test.py:8: ",
"self = <QuerySet []>, args = (), kwargs = {'name': 'This one is not there'}",
"E *DoesNotExist: Item matching query does not exist.",
"* 2 failed in *",
])
assert "INTERNALERROR" not in str(result.stdout) + str(result.stderr)
assert result.ret == 1