From 6fcbbe0b855d8701a4da1b65772ccf326f996b9e Mon Sep 17 00:00:00 2001 From: Natalia <124304+nessita@users.noreply.github.com> Date: Fri, 24 Oct 2025 09:50:01 -0300 Subject: [PATCH] Fixed IntegrityError in bulk_create.tests.BulkCreateTransactionTests due to duplicate primary keys. Some tests in BulkCreateTransactionTests were inserting Country objects with hardcoded primary keys, which could conflict with existing rows (if the sequence value wasn't bumped by another test). Updated the tests to dynamically select an unused primary key instead. Thanks to Simon Charette for the exhaustive and enlightening review. --- tests/bulk_create/tests.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/tests/bulk_create/tests.py b/tests/bulk_create/tests.py index 8ab918fff5..7b77ffed3d 100644 --- a/tests/bulk_create/tests.py +++ b/tests/bulk_create/tests.py @@ -889,19 +889,27 @@ class BulkCreateTests(TestCase): class BulkCreateTransactionTests(TransactionTestCase): available_apps = ["bulk_create"] + def get_unused_country_id(self): + # Find a serial ID that hasn't been used already and has enough of a + # buffer for the following `bulk_create` call without an explicit pk + # not to conflict. + return getattr(Country.objects.last(), "id", 10) + 100 + def test_no_unnecessary_transaction(self): + unused_id = self.get_unused_country_id() with self.assertNumQueries(1): Country.objects.bulk_create( - [Country(id=1, name="France", iso_two_letter="FR")] + [Country(id=unused_id, name="France", iso_two_letter="FR")] ) with self.assertNumQueries(1): Country.objects.bulk_create([Country(name="Canada", iso_two_letter="CA")]) def test_objs_with_and_without_pk(self): + unused_id = self.get_unused_country_id() with self.assertNumQueries(4): Country.objects.bulk_create( [ - Country(id=10, name="France", iso_two_letter="FR"), + Country(id=unused_id, name="France", iso_two_letter="FR"), Country(name="Canada", iso_two_letter="CA"), ] )