pytest/mixer Django - fixture ignores field value when it's inherited from another model

296 Views Asked by At

All my models, including Report inherit from BaseModel:

class Report(BaseModel):
      ...

class BaseModel(models.Model):
    created_date = models.DateTimeField(auto_now_add=True, db_index=True)
    modified_date = models.DateTimeField(auto_now=True, db_index=True)

    class Meta:
        abstract = True

I'm trying to test a scheduled tasks that deletes old Report objects.

Below is a fixture:

@pytest.fixture(scope="function")
def old_dummy_report(request, db):
    ### set the date to far back
    old_date = datetime.datetime.now() - datetime.timedelta(days=900)
    return mixer.blend("core.report", , created_date=old_date, ios_report={'1': 1}, android_report={'1': 1})

However, when I run the test and inspect the created_date field for old_dummy_report, I always get the date at the time the test is run.

How can I rectify this, besides re-setting the date to old_date in the test function itself (which seems unpythonic).

1

There are 1 best solutions below

0
On BEST ANSWER

Found the solution. I guess this has to do with the auto_now_add=True parameter.

I've changed the pytest fixture function to this:

@pytest.fixture(scope="function")
def old_dummy_report(request, db):
    old_date = datetime.datetime.now() - datetime.timedelta(days=900)
    obj = mixer.blend("core.report", ios_report={'1': 1}, android_report={'1': 3}, created_date=old_date)
    obj.created_date = old_date
    obj.save()
    return obj

So, first create the object and let Django auto_now_add, then change the created_date manually.