This commit is contained in:
사재혁 2025-11-16 02:23:39 +02:00 committed by GitHub
commit 442c0303e4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 39 additions and 1 deletions

View file

@ -7,7 +7,7 @@ import sys
import threading
import unittest
from collections import Counter
from contextlib import contextmanager
from contextlib import contextmanager, suppress
from copy import copy, deepcopy
from difflib import get_close_matches
from functools import wraps
@ -1163,6 +1163,11 @@ class TransactionTestCase(SimpleTestCase):
try:
cls._fixture_setup()
except Exception:
# Attempt to teardown fixtures on exception during setup as
# _post_teardown won't be triggered to cleanup state when an
# an exception is surfaced to SimpleTestCase._pre_setup.
with suppress(Exception):
cls("setUp")._fixture_teardown()
if cls.available_apps is not None:
apps.unset_available_apps()
setting_changed.send(

View file

@ -1,5 +1,6 @@
import pickle
from functools import wraps
from unittest.mock import patch
from django.db import IntegrityError, connections, transaction
from django.test import TestCase, skipUnlessDBFeature
@ -168,3 +169,35 @@ class SetupTestDataIsolationTests(TestCase):
self.assertEqual(self.car.name, "Volkswagen Beetle")
self.car.name = "Volkswagen Coccinelle"
self.car.save()
class SetupTestDataExceptionTest(TestCase):
def test_cleanup_on_setup_exception_without_transactions(self):
with patch.object(
connections["default"].features, "supports_transactions", False
):
class FailingSetupTestCase(TestCase):
@classmethod
def setUpTestData(cls):
Car.objects.create(name="Should be cleaned up")
raise ValueError("Simulated exception in setUpTestData")
def test_dummy(self):
pass
test_instance = FailingSetupTestCase("test_dummy")
initial_count = Car.objects.count()
with self.assertRaises(ValueError):
test_instance._pre_setup()
final_count = Car.objects.count()
self.assertEqual(
initial_count,
final_count,
"Data was not cleaned up after setUpTestData exception. "
f"Cars before: {initial_count}, after: {final_count}",
)