Search code examples
pythondjangotestingpytestfactory-boy

Factory-boy property attributes?


I have a recipe like this:

import factory
from models import Foobar


class MenuItemFactory(factory.Factory):
    class Meta:
        model = MenuItem

    name = 'Default Foobar'
    url = factory.LazyAttribute(lambda o: '/%s' % o.name)

I want to add dynamic properties, like slug, but I want to do it in a separate method. I want this, since writing any more complex logic in lambda one-liners would be, well, ugly.

One thought came to mind, using a property method, like they do in Django models. For example:

class MenuItemFactory(factory.Factory):
    ...

    @property
    def url(self):
        return '/%s' % self.name

Is there a way, similar to this, that will accomplish what I'm trying to do?

EDIT

What I want to accomplish in the end is this:

menu_item = MenuItemFactory(name='foobar')

menu_item.name = 'foobar'
menu_item.url = '/foobar'

Where slug acts as a dynamic attribute. In other words, I'm looking for a proper place to store my dynamic attribute logic.


Solution

  • Turns out its pretty simple, took me a while to find it in the docs.

    @factory.lazy_attribute
    def url(self):
        return '/%s' % self.name