Multiple testing problems with Django & Django Rest Framework test cases

Recently have been using Django and can’t quite wrap my head around testing within Django.

  1. When I run python manage.py test the application runs 0 tests.
  2. When I run python manage.py test api.tests.tests it returns Got an error creating the test database: permission denied to create database. My app name is api (I have 2 other apps as well). The app has a folder tests with a file tests.py.
  3. How can I add multiple testing files and folders in the future if I want to create a large test suite and organise it? I have had problems with Django not recognising them.
  4. I use PyCharm for editing and when I use PyCharm to run unit tests, it does execute it and prints an output but it also gives this error.

django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details.

However, I open the shell with python manage.py shell and I am sure the engine value is there and the database is there. I can create objects with the shell as well.

Please help in solving multitudes of problems which I feel are all linked.

This is my test file at the current stage:

from rest_framework.test import APITestCase, APIRequestFactory, force_authenticate
from rest_framework import status
from django.contrib.auth.models import User
import api.endpoints.analysis as a

class TestCase(APITestCase):

  def test_1(self):
    data_input = {"ticker": "AAPL"}
    request = APIRequestFactory().post('/api/analysis', data_input, format='json')
    # user = User.objects.get(username='test')
    force_authenticate(request, None)
    response = a.AnalysisList.as_view()(request)
    print(response.status_code)

# class AnalysisTests(APITestCase):
#   def setUp(self):
#     self.factory = APIRequestFactory()
#     self.user = User.objects.create(username='test', email='test@example.com', password='lukas')
#     self.analysis_list_view = a.AnalysisList.as_view()
#     self.input = {"ticker": "AAPL"}
#     # request = factory.get('/accounts/django-superstars/')
#     # force_authenticate(request, user=user)
#     # response = analysis_list_view(request)
#
#   # Creation
#   def test_create_analysis_simple(self):
#     request = self.factory.post('/api/analysis/', self.input, format='json')
#     force_authenticate(request, user=self.user)
#     response = self.analysis_list_view(request)
#     self.assertEquals(response.status_code, status.HTTP_201_CREATED)

My database settings:

DATABASES = {}
if DEBUG:
  DATABASES = {
    'default': {
      'ENGINE': 'django.db.backends.postgresql_psycopg2',
      'NAME': 'qlocal',
      'USER': 'qlocaluser',
      'PASSWORD': '*',
      'HOST': 'localhost',
      'PORT': '',
      'TEST': {
        'NAME': 'test_finance',
      },
    }
  }
else:
  DATABASES = {
    'default': dj_database_url.config(conn_max_age=600, ssl_require=True),
  }

I’ll try answering number 2/3 of your questions if that’s OK.

When I run python manage.py test api.tests.tests it returns Got an error creating the test database: permission denied to create database . My app name is api (I have 2 other apps as well). The app has a folder tests with a file tests.py.

Have you added a __init__.py file to the tests directory? For django/python to recognize the folder as a python package/module and then go on to recognize the directory’s files as containing tests, you must have a __init__.py file. (if you don’t already have a __init__.py file, I don’t know how PyCharm does things differently when scanning for tests)

How can I add multiple testing files and folders in the future if I want to create a large test suite and organise it? I have had problems with Django not recognising them.

I found this recommendation from the MDN’s django tutorial to be helpful, where they use this setup:

app_folder/
  /tests/
    __init__.py
    test_models.py
    test_forms.py
    test_views.py

The resolution for a multi-file test suite described by @datalowe is the preferred implementation. It’s super simple, clean, and is very scalable when it comes to adding tests in the future. Also, if you’re using postgres, you may need to give yourself special permissions within the database. From my own experience, I’ve run this command inside the postgres shell to grant the test code access to database creation:
ALTER USER <DB_USERNAME_IN_SETTINGS.PY> CREATEDB;

Hope this helps. Let us know if you have anymore questions!

– Austin

of course, how could I forget! Thank you for the tutorial, pretty embarrassed with how long I’ve spent on this problem.

Thanks for this as well, this has solved the permission problem and combined with @datalowe’s answer solved everything apart from the mysterious Pycharm issue. If anyone knows what might be wrong with Pycharm, I’m very interested in hearing it.

I don’t believe that’s a Pycharm issue due to it being a Django exception. Try getting rid of the TEST attribute of the db, or slowly remove and add other attributes and see what line is specifically causing the error.