Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 866
Milano Avatar asked Apr 30 '17 16:04

Milano


2 Answers

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

like image 194
aliva Avatar answered Nov 04 '22 00:11

aliva


I don't recommend using fixture since you will need to maintain them each time you make changes to the model. Here is a better approach on creating objects for tests by using this library https://factoryboy.readthedocs.io/en/latest/ which is more flexible.

like image 20
Gabriel Muj Avatar answered Nov 04 '22 02:11

Gabriel Muj