Factory Boy’s internals

declarations

class factory.declarations.CircularSubFactory(module_name, factory_name, **kwargs)[source]

Use to solve circular dependencies issues.

get_factory()[source]

Retrieve the factory.Factory subclass.

Its value is cached in the ‘factory’ attribute, and retrieved through the factory_getter callable.

class factory.declarations.ContainerAttribute(function, strict=True, *args, **kwargs)[source]

Variant of LazyAttribute, also receives the containers of the object.

Attributes:
function (function): A function, expecting the current LazyStub and the
(optional) object having a subfactory containing this attribute.
strict (bool): Whether evaluating should fail when the containers are
not passed in (i.e used outside a SubFactory).
evaluate(sequence, obj, containers=())[source]

Evaluate the current ContainerAttribute.

Args:
obj (LazyStub): a lazy stub of the object being constructed, if
needed.
containers (list of LazyStub): a list of lazy stubs of factories
being evaluated in a chain, each item being a future field of next one.
class factory.declarations.InfiniteIterator(iterator)[source]

Same as Iterator, but make the iterator infinite by cycling at the end.

Attributes:
iterator (iterable): the iterator, once made infinite.
class factory.declarations.Iterator(iterator)[source]

Fill this value using the values returned by an iterator.

Warning: the iterator should not end !

Attributes:
iterator (iterable): the iterator whose value should be used.
class factory.declarations.LazyAttribute(function, *args, **kwargs)[source]

Specific OrderedDeclaration computed using a lambda.

Attributes:
function (function): a function, expecting the current LazyStub and
returning the computed value.
class factory.declarations.LazyAttributeSequence(function, type=<type 'str'>)[source]

Composite of a LazyAttribute and a Sequence.

Attributes:
function (function): A function, expecting the current LazyStub and the
current sequence counter.
type (function): A function converting an integer into the expected kind
of counter for the ‘function’ attribute.
class factory.declarations.OrderedDeclaration[source]

A factory declaration.

Ordered declarations mark an attribute as needing lazy evaluation. This allows them to refer to attributes defined by other OrderedDeclarations in the same factory.

evaluate(sequence, obj, containers=())[source]

Evaluate this declaration.

Args:
sequence (int): the current sequence counter to use when filling
the current instance
obj (containers.LazyStub): The object holding currently computed
attributes
containers (list of containers.LazyStub): The chain of SubFactory
which led to building this object.
class factory.declarations.ParameteredAttribute(**kwargs)[source]

Base class for attributes expecting parameters.

Attributes:
defaults (dict): Default values for the paramters.
May be overridden by call-time parameters.
Class attributes:
CONTAINERS_FIELD (str): name of the field, if any, where container
information (e.g for SubFactory) should be stored. If empty, containers data isn’t merged into generate() parameters.
evaluate(create, extra, containers)[source]

Evaluate the current definition and fill its attributes.

Uses attributes definition in the following order: - values defined when defining the ParameteredAttribute - additional values defined when instantiating the containing factory

Args:
create (bool): whether the parent factory is being ‘built’ or
‘created’
extra (containers.DeclarationDict): extra values that should
override the defaults
containers (list of LazyStub): List of LazyStub for the chain of
factories being evaluated, the calling stub being first.
generate(create, params)[source]

Actually generate the related attribute.

Args:
create (bool): whether the calling factory was in ‘create’ or
‘build’ mode
params (dict): parameters inherited from init and evaluation-time
overrides.
Returns:
Computed value for the current declaration.
class factory.declarations.PostGeneration(function, extract_prefix=None)[source]

Calls a given function once the object has been generated.

class factory.declarations.PostGenerationDeclaration(extract_prefix=None)[source]

Declarations to be called once the target object has been generated.

Attributes:
extract_prefix (str): prefix to use when extracting attributes from
the factory’s declaration for this declaration. If empty, uses the attribute name of the PostGenerationDeclaration.
call(obj, create, extracted=None, **kwargs)[source]

Call this hook; no return value is expected.

Args:

obj (object): the newly generated object create (bool): whether the object was ‘built’ or ‘created’ extracted (object): the value given for <extract_prefix> in the

object definition, or None if not provided.
kwargs (dict): declarations extracted from the object
definition for this hook
extract(name, attrs)[source]

Extract relevant attributes from a dict.

Args:
name (str): the name at which this PostGenerationDeclaration was
defined in the declarations
attrs (dict): the attribute dict from which values should be
extracted
Returns:
(object, dict): a tuple containing the attribute at ‘name’ (if
provided) and a dict of extracted attributes
class factory.declarations.PostGenerationMethodCall(method_name, extract_prefix=None, *args, **kwargs)[source]

Calls a method of the generated object.

Attributes:
method_name (str): the method to call method_args (list): arguments to pass to the method method_kwargs (dict): keyword arguments to pass to the method
Example:
class UserFactory(factory.Factory):
... password = factory.PostGenerationMethodCall(‘set_password’, password=’‘)
class factory.declarations.RelatedFactory(factory, name='', **defaults)[source]

Calls a factory once the object has been generated.

Attributes:

factory (Factory): the factory to call defaults (dict): extra declarations for calling the related factory name (str): the name to use to refer to the generated object when

calling the related factory
class factory.declarations.SelfAttribute(attribute_name, default=<class 'factory.declarations._UNSPECIFIED'>, *args, **kwargs)[source]

Specific OrderedDeclaration copying values from other fields.

Attributes:

attribute_name (str): the name of the attribute to copy. default (object): the default value to use if the attribute doesn’t

exist.
class factory.declarations.Sequence(function, type=<type 'str'>)[source]

Specific OrderedDeclaration to use for ‘sequenced’ fields.

These fields are typically used to generate increasing unique values.

Attributes:
function (function): A function, expecting the current sequence counter
and returning the computed value.
type (function): A function converting an integer into the expected kind
of counter for the ‘function’ attribute.
class factory.declarations.SubFactory(factory, **kwargs)[source]

Base class for attributes based upon a sub-factory.

Attributes:
defaults (dict): Overrides to the defaults defined in the wrapped
factory

factory (base.Factory): the wrapped factory

generate(create, params)[source]

Evaluate the current definition and fill its attributes.

Args:
create (bool): whether the subfactory should call ‘build’ or
‘create’
params (containers.DeclarationDict): extra values that should
override the wrapped factory’s defaults
get_factory()[source]

Retrieve the wrapped factory.Factory subclass.

factory.declarations.deepgetattr(obj, name, default=<class 'factory.declarations._UNSPECIFIED'>)[source]

Try to retrieve the given attribute of an object, digging on ‘.’.

This is an extended getattr, digging deeper if ‘.’ is found.

Args:
obj (object): the object of which an attribute should be read name (str): the name of an attribute to look up. default (object): the default value to use if the attribute wasn’t found
Returns:
the attribute pointed to by ‘name’, splitting on ‘.’.
Raises:
AttributeError: if obj has no ‘name’ attribute.
factory.declarations.infinite_iterator(func)[source]

Turn a generator function into an infinite iterator attribute.

factory.declarations.iterator(func)[source]

Turn a generator function into an iterator attribute.

containers

class factory.containers.AttributeBuilder(factory, extra=None, *args, **kwargs)[source]

Builds attributes from a factory and extra data.

Attributes:
factory (base.Factory): the Factory for which attributes are being
built

_attrs (DeclarationDict): the attribute declarations for the factory _subfields (dict): dict mapping an attribute name to a dict of

overridden default values for the related SubFactory.
build(create)[source]

Build a dictionary of attributes.

Args:
create (bool): whether to ‘build’ or ‘create’ the subfactories.
exception factory.containers.CyclicDefinitionError[source]

Raised when cyclic definition were found.

class factory.containers.DeclarationDict[source]

Slightly extended dict to work with OrderedDeclaration.

copy(extra=None)[source]

Copy this DeclarationDict into another one, including extra values.

Args:
extra (dict): additional attributes to include in the copy.
is_declaration(name, value)[source]

Determines if a class attribute is a field value declaration.

Based on the name and value of the class attribute, return True if it looks like a declaration of a default field value, False if it is private (name starts with ‘_’) or a classmethod or staticmethod.

update_with_public(d)[source]

Updates the DeclarationDict from a class definition dict.

Takes into account all public attributes and OrderedDeclaration instances; ignores all class/staticmethods and private attributes (starting with ‘_’).

Returns a dict containing all remaining elements.

class factory.containers.LazyStub(attrs, containers=(), target_class=<type 'object'>)[source]

A generic container that only allows getting attributes.

Attributes are set at instantiation time, values are computed lazily.

Attributes:
__initialized (bool): whether this object’s __init__ as run. If set,
setting any attribute will be prevented.

__attrs (dict): maps attribute name to their declaration __values (dict): maps attribute name to computed value __pending (str list): names of the attributes whose value is being

computed. This allows to detect cyclic lazy attribute definition.
__containers (LazyStub list): “parents” of the LazyStub being built.
This allows to have the field of a field depend on the value of another field

__target_class (type): the target class to build.

class factory.containers.LazyValue[source]

Some kind of “lazy evaluating” object.

evaluate(obj, containers=())[source]

Compute the value, using the given object.

class factory.containers.OrderedDeclarationWrapper(declaration, sequence, *args, **kwargs)[source]

Lazy wrapper around an OrderedDeclaration.

Attributes:
declaration (declarations.OrderedDeclaration): the OrderedDeclaration
being wrapped
sequence (int): the sequence counter to use when evaluatin the
declaration
evaluate(obj, containers=())[source]

Lazily evaluate the attached OrderedDeclaration.

Args:

obj (LazyStub): the object being built containers (object list): the chain of containers of the object

being built, its immediate holder being first.
class factory.containers.PostGenerationDeclarationDict[source]

Alternate DeclarationDict for PostGenerationDeclaration.

is_declaration(name, value)[source]

Captures instances of PostGenerationDeclaration.

class factory.containers.StubObject[source]

A generic container.

class factory.containers.SubFactoryWrapper(subfactory, subfields, create, *args, **kwargs)[source]

Lazy wrapper around a SubFactory.

Attributes:

subfactory (declarations.SubFactory): the SubFactory being wrapped subfields (DeclarationDict): Default values to override when evaluating

the SubFactory

create (bool): whether to ‘create’ or ‘build’ the SubFactory.

base

class factory.base.BaseFactory[source]

Factory base support for sequences, attributes and stubs.

classmethod attributes(create=False, extra=None)[source]

Build a dict of attribute values, respecting declaration order.

The process is: - Handle ‘orderless’ attributes, overriding defaults with provided

kwargs when applicable
  • Handle ordered attributes, overriding them with provided kwargs when

    applicable; the current list of computed attributes is available to the currently processed object.

classmethod build(**kwargs)[source]

Build an instance of the associated class, with overriden attrs.

classmethod build_batch(size, **kwargs)[source]

Build a batch of instances of the given class, with overriden attrs.

Args:
size (int): the number of instances to build
Returns:
object list: the built instances
classmethod create(**kwargs)[source]

Create an instance of the associated class, with overriden attrs.

classmethod create_batch(size, **kwargs)[source]

Create a batch of instances of the given class, with overriden attrs.

Args:
size (int): the number of instances to create
Returns:
object list: the created instances
classmethod declarations(extra_defs=None)[source]

Retrieve a copy of the declared attributes.

Args:
extra_defs (dict): additional definitions to insert into the
retrieved DeclarationDict.
classmethod generate(strategy, **kwargs)[source]

Generate a new instance.

The instance will be created with the given strategy (one of BUILD_STRATEGY, CREATE_STRATEGY, STUB_STRATEGY).

Args:
strategy (str): the strategy to use for generating the instance.
Returns:
object: the generated instance
classmethod generate_batch(strategy, size, **kwargs)[source]

Generate a batch of instances.

The instances will be created with the given strategy (one of BUILD_STRATEGY, CREATE_STRATEGY, STUB_STRATEGY).

Args:
strategy (str): the strategy to use for generating the instance. size (int): the number of instances to generate
Returns:
object list: the generated instances
classmethod simple_generate(create, **kwargs)[source]

Generate a new instance.

The instance will be either ‘built’ or ‘created’.

Args:
create (bool): whether to ‘build’ or ‘create’ the instance.
Returns:
object: the generated instance
classmethod simple_generate_batch(create, size, **kwargs)[source]

Generate a batch of instances.

These instances will be either ‘built’ or ‘created’.

Args:
size (int): the number of instances to generate create (bool): whether to ‘build’ or ‘create’ the instances.
Returns:
object list: the generated instances
classmethod stub(**kwargs)[source]

Retrieve a stub of the associated class, with overriden attrs.

This will return an object whose attributes are those defined in this factory’s declarations or in the extra kwargs.

classmethod stub_batch(size, **kwargs)[source]

Stub a batch of instances of the given class, with overriden attrs.

Args:
size (int): the number of instances to stub
Returns:
object list: the stubbed instances
class factory.base.BaseFactoryMetaClass[source]

Factory metaclass for handling ordered declarations.

class factory.base.DjangoModelFactory[source]

Factory for Django models.

This makes sure that the ‘sequence’ field of created objects is an unused id.

Possible improvement: define a new ‘attribute’ type, AutoField, which would handle those for non-numerical primary keys.

class factory.base.Factory[source]

Factory base with build and create support.

This class has the ability to support multiple ORMs by using custom creation functions.

classmethod get_building_function()[source]

Retrieve the building function for this class.

Returns:
function: A function that takes one parameter, the class for which
an instance will be created, and keyword arguments for the value of the fields of the instance.
classmethod get_creation_function()[source]

Retrieve the creation function for this class.

Returns:
function: A function that takes one parameter, the class for which
an instance will be created, and keyword arguments for the value of the fields of the instance.
classmethod set_building_function(building_function)[source]

Set the building function for this class.

Args:
building_function (function): the new building function. That
function should take one non-keyword argument, the ‘class’ for which an instance will be built. The value of the various fields are passed as keyword arguments.
classmethod set_creation_function(creation_function)[source]

Set the creation function for this class.

Args:
creation_function (function): the new creation function. That
function should take one non-keyword argument, the ‘class’ for which an instance will be created. The value of the various fields are passed as keyword arguments.
class factory.base.FactoryMetaClass[source]

Factory metaclass for handling class association and ordered declarations.

factory.base.build(klass, **kwargs)[source]

Create a factory for the given class, and build an instance.

factory.base.build_batch(klass, size, **kwargs)[source]

Create a factory for the given class, and build a batch of instances.

factory.base.create(klass, **kwargs)[source]

Create a factory for the given class, and create an instance.

factory.base.create_batch(klass, size, **kwargs)[source]

Create a factory for the given class, and create a batch of instances.

factory.base.generate(klass, strategy, **kwargs)[source]

Create a factory for the given class, and generate an instance.

factory.base.generate_batch(klass, strategy, size, **kwargs)[source]

Create a factory for the given class, and generate instances.

factory.base.get_factory_bases(bases)[source]

Retrieve all BaseFactoryMetaClass-derived bases from a list.

factory.base.make_factory(klass, **kwargs)[source]

Create a new, simple factory for the given class.

factory.base.simple_generate(klass, create, **kwargs)[source]

Create a factory for the given class, and simple_generate an instance.

factory.base.simple_generate_batch(klass, create, size, **kwargs)[source]

Create a factory for the given class, and simple_generate instances.

factory.base.stub(klass, **kwargs)[source]

Create a factory for the given class, and stub an instance.

factory.base.stub_batch(klass, size, **kwargs)[source]

Create a factory for the given class, and stub a batch of instances.

factory.base.use_strategy(new_strategy)[source]

Force the use of a different strategy.

This is an alternative to setting default_strategy in the class definition.

Table Of Contents

Previous topic

PostGenerationHook

This Page