1π
The problem is that you are creating the user in the class definition. This runs when the test class is loaded, before the database has been created.
class ExampleTest(LiveServerTestCase):
user = User.objects.create_superuser('Testuser','test@user.com','1234')
user.save() # This save isn't required -- it has been saved already
You can fix the problem by moving the user creation into an individual test. Then the user will be created when the test method runs, after the database has been created.
class ExampleTest(LiveServerTestCase):
def test_user(self):
self.user = User.objects.create_superuser('Testuser','test@user.com','1234')
...
Django 1.8 has a setUpTestData
method where you can set up initial data once for the entire test case. This is quicker, and less repetitive.
class ExampleTest(LiveServerTestCase):
@classmethod
def setUpTestData(cls):
# Set up data for the whole TestCase
self.user = User.objects.create_superuser('Testuser','test@user.com','1234')
def test_user(self):
# access the user with self.user
...
In earlier versions of Django which donβt have setUpTestData
, you can create the user in the setUp
method.
class ExampleTest(LiveServerTestCase):
def setUp(self):
self.user = User.objects.create_superuser('Testuser','test@user.com','1234')
2π
You need to set up the database in your DATABASES
settings.
Django sets up a test database corresponding to every database that is
defined in theDATABASES
definition in your settings file.By default the test databases get their names by prepending
test_
to
the value of theNAME
settings for the databases defined inDATABASES
.
If you want to use a different database name, specify NAME
in the TEST
dictionary for any given database in DATABASES
.
An example test database configuration:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'USER': 'mydatabaseuser',
'NAME': 'mydatabase',
'TEST': { # test database settings
'NAME': 'mytestdatabase', # test database name
},
},
}