Skip to content

Commit

Permalink
Avoid running database migrations for SimpleTestCase (#1120)
Browse files Browse the repository at this point in the history
  • Loading branch information
flaeppe authored Sep 2, 2024
1 parent 8502a12 commit c746a46
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 2 deletions.
13 changes: 11 additions & 2 deletions pytest_django/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -553,12 +553,21 @@ 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")
# Don't set up the DB if the unittest does not require DB.
# The `databases` propery seems like the best indicator for that.
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*")

0 comments on commit c746a46

Please sign in to comment.