Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

250
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda