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

165
Vistas
Pytest patch field's default attribute for inherited django model

I have the following model in common/models.py:

from django.db import models
from uuid import uuid4

class BaseModel(models.Model):
    guid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False)

    class Meta:
       abstract = True

In app/models.py I have the following:

from django.db import models
from common.models import BaseModel

class Entity(BaseModel):
   name = models.CharField()

In tests I tried to patch uuid4 in the following ways:

def test_model_create(mocker):
   # Given
   mock_guid = mocker.patch("uuid.uuid4", return_value="some-guid")

   # When
   entity = Entity.objects.create(name="test_name")

   # Then
   mock_guid.assert_called_once()
   assert "some-guid" == entity.guid

mock_guid.assert_called_once() returns not called. What can be the issue here?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

I think the issue is that guid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) references the uuid.uuid4 function directly at parsing time. When you set up your mock, it's too late to replace this pointer.

Changing it to something like guid = models.UUIDField(unique=True, default=lambda: uuid.uuid4(), editable=False) should fix your issue, because the value is returned at runtime, and your mock will be setup properly before the function is referenced and called.

over 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