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

159
Views
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 answers
Answer question

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 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!