Skip to content

Commit 7b319da

Browse files
flaeppebluetech
authored andcommitted
Avoid running database migrations for SimpleTestCase
1 parent b373db6 commit 7b319da

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

pytest_django/plugin.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -552,10 +552,14 @@ def _django_setup_unittest(
552552
def non_debugging_runtest(self) -> None:
553553
self._testcase(result=self)
554554

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

558-
request.getfixturevalue("django_db_setup")
561+
if request.cls.databases:
562+
request.getfixturevalue("django_db_setup")
559563

560564
with django_db_blocker.unblock():
561565
yield

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)