Thijs
Thijs

Reputation: 717

Using Factory Boy SelfAttribute + relativedelta

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

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?

Upvotes: 3

Views: 754

Answers (1)

Xelnor
Xelnor

Reputation: 3589

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

Upvotes: 4

Related Questions