Django unittests - ImproperlyConfigured error

1.4k Views Asked by At

Im trying to write tests for my module. When i run:

python manage.py test my_module

Im getting message:

django.core.exceptions.ImproperlyConfigured: Please fill out the database NAME in the settings module before using the database.

I dont have any test yet, just BaseTest where im creating users, groups and assigning permissions.

Where could be the problem? Server normally works, configuration seems to be good. Do i need to define settings for test?


Ok. I think i know what was the problem :] I had lists with permissions stored in other module. So i were writting from module.perms import perms (normal python list). Its seems, that python is doing something more than just import that list from other module to my module. And that was the cause of failing.

Solution: Surround code after list definition with:

if __name__ == "__main__":
   ...

Then everything should be working good.

4

There are 4 best solutions below

0
On BEST ANSWER

Ok. I think i know what was the problem :] I had lists with permissions stored in other module. So i were writting from module.perms import perms (normal python list). Its seems, that python is doing something more than just import that list from other module to my module. And that was the cause of failing.

Solution: Surround code after list definition with:

if __name__ == "__main__":
   ...

Then everything should be working good.

2
On

You need to have your DATABASE setting in place in settings.py, and your app needs to be in installed apps. For example:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'database.sqlite',
1
On

python manage.py test doesn't use the NAME database defined in settings.py DATABASES. From the docs -

Tests that require a database (namely, model tests) will not use your "real" (production) database. Separate, blank databases are created for the tests.

Regardless of whether the tests pass or fail, the test databases are destroyed when all the tests have been executed.

By default the test databases get their names by prepending test_ to the value of the NAME settings for the databases defined in DATABASES. When using the SQLite database engine the tests will by default use an in-memory database (i.e., the database will be created in memory, bypassing the filesystem entirely!). If you want to use a different database name, specify TEST_NAME in the dictionary for any given database in DATABASES.

To answer your question. You can define a test database with the TEST_NAME setting. But you shouldn't have to.

0
On

Here's another potential solution for people finding this through search:

I was trying to define my own TestRunner class inside my settings file, which meant it had to import DjangoTestSuiteRunner. This import at the top of the file caused the ImproperlyConfigured error. Moving the custom TestRunner class to a separate file resolved the issue.