Search code examples
pythondjangounit-testingdjango-fixturesdjango-unittest

Django 1.6.1 Fixtures not getting loaded for Unittest


Django is not loading fixtures for the following test.

from django.test import TestCase

class DevViewsTests(TestCase):

    fixtures = ['device/fixtures/test_device.json']

    def setUp(self):
        self.client = Client()
        self.username = 'cws'
        self.email = 'alain.sturzenegger@gmail.com'
        self.password = 'cws123'
        self.test_user = User.objects.create_user(self.username, self.email, self.password)
        login = self.client.login(username=self.username, password=self.password)
        self.assertEqual(login, True)

    def test_device_list(self):

        url = reverse('device-overview')
        response = self.client.get(url)
        logger.debug('GET[%s]:[%s]', url, response.status_code)

        self.assertQuerysetEqual(response.context['device_list'], ['<device: Device Test 1>'])

This directs to the following view But from that view I am not able to retrieve device_list

def overview(request):
    device_list = device.objects.all()
    print "List of devices"
    print device_list # getting blank list []
    context = {'device_list': device_list}
    return render(request, 'device/index.html', context)

My test_device.json file is as follows

[
{
    "pk": 1, 
    "model": "device.device", 
    "fields": {
        "owner": 1, 
        "phone": "+41765687755", 
        "name": "Device Test 1", 
        "access_code": "1234"
    }
}
]

File Structure is

cws
--device
--fixtures
----test_device.json

Any Idea what I am doing wrong? Please provide suggestion..


Solution

  • According to fixture loading documentation:

    Once you’ve created a fixture and placed it in a fixtures directory in one of your INSTALLED_APPS, you can use it in your unit tests by specifying a fixtures class attribute on your django.test.TestCase subclass:

    ...

    Just specify the filename, not relative path from project directory:

    fixtures = ['test_device.json']