Skip to content

Commit c746a46

Browse files
authored
Avoid running database migrations for SimpleTestCase (#1120)
1 parent 8502a12 commit c746a46

File tree

2 files changed

+44
-2
lines changed

2 files changed

+44
-2
lines changed

pytest_django/plugin.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -553,12 +553,21 @@ def _django_setup_unittest(
553553
def non_debugging_runtest(self) -> None:
554554
self._testcase(result=self)
555555

556+
from django.test import SimpleTestCase
557+
558+
assert issubclass(request.cls, SimpleTestCase) # Guarded by 'is_django_unittest'
556559
try:
557560
TestCaseFunction.runtest = non_debugging_runtest # type: ignore[method-assign]
558561

559-
request.getfixturevalue("django_db_setup")
562+
# Don't set up the DB if the unittest does not require DB.
563+
# The `databases` propery seems like the best indicator for that.
564+
if request.cls.databases:
565+
request.getfixturevalue("django_db_setup")
566+
db_unblock = django_db_blocker.unblock()
567+
else:
568+
db_unblock = contextlib.nullcontext()
560569

561-
with django_db_blocker.unblock():
570+
with db_unblock:
562571
yield
563572
finally:
564573
TestCaseFunction.runtest = original_runtest # type: ignore[method-assign]

tests/test_db_setup.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -583,3 +583,36 @@ class Migration(migrations.Migration):
583583
)
584584
assert result.ret == 0
585585
result.stdout.fnmatch_lines(["*mark_migrations_run*"])
586+
587+
def test_migrations_not_run_for_simple_test_case(
588+
self, django_pytester: DjangoPytester
589+
) -> None:
590+
pytester = django_pytester
591+
pytester.create_test_module(
592+
"""
593+
from django.test import SimpleTestCase
594+
595+
class MyTest(SimpleTestCase):
596+
def test_something_without_db(self):
597+
assert 1 == 1
598+
"""
599+
)
600+
601+
pytester.create_app_file(
602+
"""
603+
from django.db import migrations, models
604+
605+
def mark_migrations_run(apps, schema_editor):
606+
print("mark_migrations_run")
607+
608+
class Migration(migrations.Migration):
609+
atomic = False
610+
dependencies = []
611+
operations = [migrations.RunPython(mark_migrations_run)]
612+
""",
613+
"migrations/0001_initial.py",
614+
)
615+
result = pytester.runpytest_subprocess("--tb=short", "-v", "-s")
616+
assert result.ret == 0
617+
result.stdout.fnmatch_lines(["*test_something_without_db PASSED*"])
618+
result.stdout.no_fnmatch_line("*mark_migrations_run*")

0 commit comments

Comments
 (0)