Skip to content
Advertisement

Django test with fixtures gives ForeignKeyViolation or IntegrityError

I am trying to write test cases for the Django RestAPI that we have but I have an issue with the fixtures loading. Everything works correctly when I have only one TestCase but when I add a second TestCase in a second django app I get django.db.utils.IntegrityError. My original intention was to create a general TestCase where I set up the most used objects in the setUpTestData function and make the other tests inherit from that one.

Things I have tried:

  • Using APITestCase from rest_framework and TestCase from django
  • Not using inheritance, and having both files using TestCase from django
  • Using setUp method instead of setUpTestData
  • Using call_command from django.core.management in the setUpTestData method instead of creating the fixtures in each class in the class variable
  • Declaring the fixtures only in the TestCase that is executed first (this makes the other TestCase have an empty DB, so it it clear that for each TestCase info is recreated)
  • Changed the order of the files in the fixtures variable

When I comment one of the test files the other works and vice-versa. When I used the call_command with verbose=2, the fixtures in the first file executed work perfectly, and it breaks just when trying to install the first fixture of the second file, with the error:

django.db.utils.IntegrityError: Problem installing fixtures: insert or update on table "preference_questions" violates foreign key constraint "preference_questi_preference_questi_64f61c66_fk_prefer" DETAIL:  Key (preference_question_category_id)=(2) is not present in table "preference_question_category"

Sometimes it gives ForeignKeyViolation depending on the case of the above mentioned.

Advertisement

Answer

Turns out the issue was that the fixtures had IDs on them, those IDs cannot be removed because objects had relations between them. In this case, there are two options I found:

  • Use natural keys as explained in this post, this makes you create new methods for the natural keys and dump your DB
  • Create the objects manually in the setUpTestData (labor intensive but won’t give you any problems)

Depending on your case it may be more interesting to use one or the other. Nonetheless, the first one is the best probably.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement