jeudi 28 juillet 2016

How to get results from python unit tests in Django using custom settings

I am trying to generate a report from the unit tests in Django. For running the tests and retrieving the results I am using a custom TestResult class, which works fine:

results = TestResult()
loader = unittest.TestLoader()
suites = loader.discover('test_folder')
for suite in suites:
    suite(results)

My only issue is that I can't override the settings file to use in memory database. I decorated my test cases with override_settings from django.test, which works for me only in the command line. When I run it using the loader it uses the my_app.settings file, however, it looks like it is overridden:

>>> from django.conf import settings   
>>> settings.DATABASES   
{'default': {'TEST_CHARSET': 'UTF8', 'NAME': ':memory:', 'ENGINE': 'django.db.backends.sqlite3', 'TEST_NAME': ':memory:'}}

I also created my own override_settings file to override any function in my project and the result is the same. I tried to override the DJANGO_SETTINGS_MODULE in os.environ, but still having the same issue. Maybe I am missing some django.setup() function to load the settings file again.

I want to be able to:

  • get results from the unit tests
  • use custom settings
  • load specific test module (just like with the loader.discover(start_dir))

TestCase example:

from rest_framework import status  
from rest_framework.test import APITestCase  

class TestCase(APITestCase):  
    fixtures = ('dump',)
    url = '/api/post'

    def test_post(self):
         # returns post from existing database not from fixture
         post = Post.objects.get(pk=3)
         data = {
            'name': 'test',
            'post': post.content
        }
        response = self.client.post(self.url + '/1', data=data)
        self.assertEquals(response.status_code, status.HTTP_201_CREATED)

Using:

  • Python 3.4
  • Django 1.9

Thanks for your help.

Aucun commentaire:

Enregistrer un commentaire