'Django testing: Got an error creating the test database: database "database_name" already exists

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?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1