0

I am attempting to write test cases in Django using Selenium. I want to use existent fixtures so my test database (SQLite3) has test data for every test.

I have some model test cases (just using the TestCase class) as follows;

from django.test import TestCase
from django.test import LiveServerTestCases
from missions.models import Mission, MissionDataRecord


class MissionModelTests(TestCase):
    fixtures = ['myproject_common/fixtures/auth_initial_load.json', 'worklog/fixtures/worklogs_initial_load',
                'missions_initial_load.json']

    def test_object_name_is_mission_title(self):
        mission = Mission.objects.get(id=1)
        self.assertEqual(mission.title, str(mission))

    def test_object_name_is_mission_title_again(self):
        mission = Mission.objects.get(id=1)
        self.assertEqual(mission.title, str(mission))

This works as expected when run like this (I get two test passes). However, for Selenium testing I need to use LiveServerTestCase instead of TestCase.

The simple example above is a model test, but for illustrative purposes of the issue I'm facing with Selenium, if I simply replace "TestCase" with "LiveServerTestCase" the first test passes, but the second test fails, with the error

django.db.utils.IntegrityError: Problem installing fixture '[...]/fixtures/auth_initial_load.json': Could not load auth.User(pk=1): UNIQUE constraint failed: auth_user.username

This error occurs in the _fixture_setup of /django/test/testcases.py. This seems to suggests that my fixtures (specifically the auth_initial_load fixture) is attempting to load again ON TOP of existing data. However, from django docs reading this should not be taking place, because each test should run in its own transaction (which I believe means the fixtures are loaded for each transaction).

What is going on here, and more importantly, how can I use LiveServerTestCase with my existing fixtures (similar to how I am using TestCase currently)? In reality I need to use StaticLiveServerTestCase, but Im guessing the code will be the same.

n00b
  • 4,341
  • 5
  • 31
  • 57

1 Answers1

2

It turns out the way I was loading fixtures correctly after all. The issue was with my fixtures themselves, using hard coded primary (and foreign) keys. In my case two users were being created before the fixtures were loaded, so when fixtures tried to load with the same primary key, a UNIQUE constraint violation occurred. The solution was to re-generate my fixtures using the --natural-primary and --natural-foreign flags as suggested in this SO answer.

n00b
  • 4,341
  • 5
  • 31
  • 57