Search code examples
djangopostgresqlunit-testingdjango-testing

How to prepopulate test database by necessary data?


I need to do some unit tests in my Django project. The problem is that almost every use case depends on prepopulated database objects.

For example, I want to create a product and test, if there were all pre_save signals successful.

from django.contrib.auth.models import User
from django.test import TestCase

from .models import Product


class ProductTestCase(TestCase):
    def setUp(self):
        self.user = User.objects.create(username='test_user')
        self.product = Product.objects.create(name='Test product',user=self.user)


    def test_product_exists(self):
        self.assertIsNotNone(self.product)

    def product_is_active_by_default(self):
        ...

I can't do that because product has to have User object related. But I can't create a User object because User has to have related plan object. There are multiple plans in my production database from which one is default but there are no plans inside test database.

So to be able to do unit tests I need to prepopulate test database with multiple objects from multiple apps.

How can I do that?


Solution

  • you can simply use django fixtures for that :-)

    first populate a sample db with data then export data with python manage.py dumpdata

    then in one of your apps create a directory named fixtures and put exported json file there (named tests.json or something else)

    in your test class load fixtures like this

    class ProductTestCase(TestCase):
        fixtures = ['tests.json', ]
    

    checkout django docs

    PS: checkout factory boy too (@Gabriel Muj) answer