factory-boy

Is it possible to put regular methods on a FactoryBoy factory?


If I use the same logic in two lazy attributes, it would be nice to share that code.

A naive attempt to do this confuses FactoryBoy into thinking that the class method is a parameter for the factory (which is obviously fair enough!):

class SomeFactory(factory.Factory):

    def some_complex_logic(self, with_arg):
        ...

    @factory.lazy_attribute
    def foo(self):
        return self.some_complex_logic(with_arg="foo")

    @factory.lazy_attribute
    def bar(self):
        return self.some_complex_logic(with_arg="bar")

This gives you a message like:

AttributeError: The parameter 'some_complex_logic' is unknown. Evaluated attributes are {...}

Is there something I can decorate some_complex_logic with to tell FactoryBoy to ignore it? Is this maybe what exclude is for?


Solution

  • This is not formally documented, but FactoryBoy considers all attributes / methods as "declarations", except:

    Thus, you could use:

    class SomeFactory(factory.Factory):
      ...
    
      @classmethod
      def some_complex_logic(cls, x):
        ...
    
      foo = factory.LazyAttribute(lambda o: o.some_complex_logic(x=1))
      bar = factory.LazyAttribute(lambda o: o.some_complex_logic(x=2))