I have a problem with testing. It's my first time writing tests and I have a problem.
I just created a test folder inside my app users
, and test_urls.py
for testing the urls.
When I type:
python manage.py test users
It says:
Creating test database for alias 'default'... Got an error creating the test database: database "database_name" already exists
Type 'yes' if you would like to try deleting the test database 'database_name', or 'no' to cancel:
What does it mean? What happens if I type yes? Do I lose all my data in database?
When testing, Django creates a test database to work on so that your development database is not polluted. The error message says that Django is trying to create a test database named "database_name"
and that this database already exists. You should check the tables of the database software you are using and check what is in database_name
, it's probably been created by mistake.
If you type yes, the database database_name
will be deleted and it is unlikely that you will be able to recover the data. So try to understand what is going on first.
You should set the name of the test database in settings.py
. There is a specific TEST
dictionary in the DATABASE
settings for this:
settings.py
...
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'USER': 'mydatabaseuser',
'NAME': 'mydatabase',
'TEST': {
'NAME': 'mytestdatabase',
},
},
}
...
By default, the prefix test_
is added to the name of your development database. You should check your settings.py
to check what is going on.
From the docs:
The default test database names are created by prepending
test_
to the value of eachNAME
inDATABASES
. When using SQLite, the tests will use an in-memory database by default (i.e., the database will be created in memory, bypassing the filesystem entirely!). TheTEST
dictionary inDATABASES
offers a number of settings to configure your test database. For example, if you want to use a different database name, specify NAME in theTEST
dictionary for any given database inDATABASES
.
FWIW, in the event that you get such a warning when using the --keepdb
argument such as
python manage.py test --keepdb [appname]
then this would typically mean that multiple instances of the Client
were instantiated, perhaps one per test. The solution is to create one client for the test class and refer to it in all corresponding methods like so:
from django.test import TestCase, Client
class MyTest(TestCase):
def setUp(self):
self.client = Client()
def test_one(self):
response = self.client.get('/path/one/')
# assertions
def test_two(self):
response = self.client.post('/path/two/', {'some': 'data'})
# assertions
You could also (unverified) create a static client using the setUpClass
class method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With