Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

249
Views
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?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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

about 4 years ago · Santiago Trujillo Report

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!