Search code examples
pythondjangounit-testingfactory-boy

Using Factory Boy SelfAttribute + relativedelta


I'm using Factory Boy in my tests and want to achieve the following:

  • Make first_period_end_date dependent on first_period_date and add 12 months to it.

I'm trying to use SelfAttribute in combination with relativedelta but the way I'm currently applying it doesn't work. My code:

import datetime

import factory
from dateutil import relativedelta

from somewhere.models import Contract

class ContractFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Contract

    start_date = factory.LazyFunction(datetime.date.today)
    first_period_date = factory.SelfAttribute('start_date')
    first_period_end_date = (
        factory.SelfAttribute('first_period_date')
        + relativedelta.relativedelta(months=12)
    )

But in runtime I get the following error:

TypeError: unsupported operand type(s) for +: 'SelfAttribute' and 'relativedelta'

So that is apparently not how it's done. But how do I do it?


Solution

  • The answer is LazyAttribute; SelfAttribute is only helpful for copying a field.

    You should do:

    class ContractFactory(factory.django.DjangoModelFactory):
        class Meta:
            model = Contract
    
        start_date = factory.LazyFunction(datetime.date.today)
        first_period_date = factory.SelfAttribute('start_date')
        first_period_end_date = factory.LazyAttribute(
            lambda self: self.first_period_date + relativedelta.relativedelta(months=12)
        )