diff --git a/pytest_django/plugin.py b/pytest_django/plugin.py index 8b4aa2f7..814e530c 100644 --- a/pytest_django/plugin.py +++ b/pytest_django/plugin.py @@ -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] diff --git a/tests/test_db_setup.py b/tests/test_db_setup.py index 9d6f0cfe..42a7224c 100644 --- a/tests/test_db_setup.py +++ b/tests/test_db_setup.py @@ -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*")