Skip to content
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

Avoid running database migrations for SimpleTestCase #1120

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 9 additions & 2 deletions pytest_django/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -552,12 +552,19 @@ def _django_setup_unittest(
def non_debugging_runtest(self) -> None:
self._testcase(result=self)

from django.test import SimpleTestCase

assert issubclass(request.cls, SimpleTestCase) # Guarded by 'is_django_unittest'
try:
TestCaseFunction.runtest = non_debugging_runtest # type: ignore[method-assign]

request.getfixturevalue("django_db_setup")
if request.cls.databases:
request.getfixturevalue("django_db_setup")
db_unblock = django_db_blocker.unblock()
else:
db_unblock = contextlib.nullcontext()

with django_db_blocker.unblock():
with db_unblock:
yield
finally:
TestCaseFunction.runtest = original_runtest # type: ignore[method-assign]
Expand Down
33 changes: 33 additions & 0 deletions tests/test_db_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -583,3 +583,36 @@ class Migration(migrations.Migration):
)
assert result.ret == 0
result.stdout.fnmatch_lines(["*mark_migrations_run*"])

def test_migrations_not_run_for_simple_test_case(
self, django_pytester: DjangoPytester
) -> None:
pytester = django_pytester
pytester.create_test_module(
"""
from django.test import SimpleTestCase

class MyTest(SimpleTestCase):
def test_something_without_db(self):
assert 1 == 1
"""
)

pytester.create_app_file(
"""
from django.db import migrations, models

def mark_migrations_run(apps, schema_editor):
print("mark_migrations_run")

class Migration(migrations.Migration):
atomic = False
dependencies = []
operations = [migrations.RunPython(mark_migrations_run)]
""",
"migrations/0001_initial.py",
)
result = pytester.runpytest_subprocess("--tb=short", "-v", "-s")
assert result.ret == 0
result.stdout.fnmatch_lines(["*test_something_without_db PASSED*"])
result.stdout.no_fnmatch_line("*mark_migrations_run*")