Skip to content

Commit

Permalink
Monkeypatch pytest instead of Django to workaround pytest bug (#782)
Browse files Browse the repository at this point in the history
  • Loading branch information
beyondgeeks committed Nov 9, 2019
1 parent 1e5afcc commit 6823ae9
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 34 deletions.
37 changes: 16 additions & 21 deletions pytest_django/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -518,29 +518,24 @@ def _django_setup_unittest(request, django_db_blocker):
yield
return

request.getfixturevalue("django_db_setup")
from _pytest.unittest import TestCaseFunction

cls = request.node.cls
if "debug" in TestCaseFunction.runtest.__code__.co_names:
# Fix pytest (https://github.com/pytest-dev/pytest/issues/5991), only
# if "self._testcase.debug()" is being used (forward compatible).
from _pytest.monkeypatch import MonkeyPatch

# Implement missing debug() wrapper/method for Django's TestCase (< 3.1.0).
# See pytest-dev/pytest-django#406.
import django
monkeypatch_debug = django.VERSION < (3, 1)
if monkeypatch_debug:
def _cleaning_debug(self):
testMethod = getattr(self, self._testMethodName)
skipped = getattr(self.__class__, "__unittest_skip__", False) or getattr(
testMethod, "__unittest_skip__", False
)
def non_debugging_runtest(self):
self._testcase(result=self)

if not skipped:
self._pre_setup()
super(cls, self).debug()
if not skipped:
self._post_teardown()
mp_debug = MonkeyPatch()
mp_debug.setattr("_pytest.unittest.TestCaseFunction.runtest", non_debugging_runtest)
else:
mp_debug = None

orig_debug = cls.debug
cls.debug = _cleaning_debug
request.getfixturevalue("django_db_setup")

cls = request.node.cls

with django_db_blocker.unblock():
if _handle_unittest_methods:
Expand All @@ -555,8 +550,8 @@ def _cleaning_debug(self):
else:
yield

if monkeypatch_debug:
cls.debug = orig_debug
if mp_debug:
mp_debug.undo()


@pytest.fixture(scope="function", autouse=True)
Expand Down
18 changes: 5 additions & 13 deletions tests/test_unittest.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,7 +458,7 @@ def tearDown(self):
assert result.ret == 0


def test_debug_restored(django_testdir):
def test_debug_not_used(django_testdir):
django_testdir.create_test_module(
"""
from django.test import TestCase
Expand All @@ -468,22 +468,14 @@ def test_debug_restored(django_testdir):
class TestClass1(TestCase):
def test_method(self):
pass
class TestClass2(TestClass1):
def _pre_setup(self):
global pre_setup_count
pre_setup_count += 1
super(TestClass2, self)._pre_setup()
def debug(self):
assert 0, "should not be called"
def test_method(self):
assert pre_setup_count == 1
pass
"""
)

result = django_testdir.runpytest_subprocess("--pdb")
result.stdout.fnmatch_lines(["*= 2 passed in *"])
result.stdout.fnmatch_lines(["*= 1 passed in *"])
assert result.ret == 0

0 comments on commit 6823ae9

Please sign in to comment.