pythonfactory-boy

factory_boy: make a factory that returns the result of a function


I have a function that generates a list of objects. The objects have complex relationships that are handled in the generator function.

How do I make a factory (not a SubFactory!) that, when asked to generate a value, just calls this function?


Solution

  • Under the hood, a simple factory.Factory will simply call its Meta.model, using the parameters as kwargs.

    For instance, in order to call subprocess.run, one could use the following factory:

    class ProcessFactory(factory.Factory):
      class Meta:
        model = subprocess.run
    
      class Params:
        # Require the program being passed separately from its options.
        program = "ls"
        opts = ()
    
      args = factory.LazyAttribute(lambda o: [o.program] + list(o.opts))
    
      check = True
      capture_output = True
    

    and use it as:

    >>> ProcessFactory(opts=["-a", "-h", "."], cwd="/tmp")
    CompletedProcess(...)
    

    As you can see:

    If your function expects positional arguments, the Meta.inline_args option can be used to convert kwargs into positional arguments.