Howto use the library

Its easy to get started with the loadtestdata management command but its quite limited if you want to have more control of how your test data should be created. This chapter describes how you use the library in your python environment like the shell, a custom script or in unittests.

Creating model instances

The autofixture module contains a few shortcuts to make the creation of test data as fast as possible.

autofixture.create(model, count, *args, **kwargs)

Create count instances of model using the either an appropiate autofixture that was registry or fall back to the default:class:AutoFixture class. model can be a model class or its string representation (e.g. "app.ModelClass").

All positional and keyword arguments are passed to the autofixture constructor. It is demonstrated in the example below which will create ten superusers:

import autofixture
admins = autofixture.create('auth.User', 10, field_values={'is_superuser': True})

Note

See Using the AutoFixture class for more information.

create() will return a list of the created objects.

autofixture.create_one(model, *args, **kwargs)

create_one() is exactly the as the create() function but a shortcut if you only want to generate one model instance.

The function returns the instanciated model.

Using the AutoFixture class

class autofixture.base.AutoFixture(model, field_values=None, none_p=None, overwrite_defaults=None, constraints=None, follow_fk=None, generate_fk=None, follow_m2m=None, generate_m2m=None)
__init__(model, field_values=None, none_p=None, overwrite_defaults=None, constraints=None, follow_fk=None, generate_fk=None, follow_m2m=None, generate_m2m=None)
Parameters:

model: A model class which is used to create the test data.

field_values: A dictionary with field names of model as keys. Values may be static values that are assigned to the field, a Generator instance that generates a value on the fly or a callable which takes no arguments and returns the wanted value.

none_p: The chance (between 0 and 1, 1 equals 100%) to assign None to nullable fields.

overwrite_defaults: All default values of fields are preserved by default. If set to True, default values will be treated like any other field.

constraints: A list of callables. The constraints are used to verify if the created model instance may be used. The callable gets the actual model as first and the instance as second parameter. The instance is not populated yet at this moment. The callable may raise an InvalidConstraint exception to indicate which fields violate the constraint.

follow_fk: A boolean value indicating if foreign keys should be set to random, already existing, instances of the related model.

generate_fk: A boolean which indicates if related models should also be created with random values. The follow_fk parameter will be ignored if generate_fk is set to True.

follow_m2m: A tuple containing minium and maximum of model instances that are assigned to ManyToManyField. No new instances will be created. Default is (1, 5). You can ignore ManyToManyField fields by setting this parameter to False.

generate_m2m: A tuple containing minimum and maximum number of model instance that are newly created and assigned to the ManyToManyField. Default is False which disables the generation of new related instances. The value of follow_m2m will be ignored if this parameter is set.

add_constraint(constraint)

Add a constraint to the autofixture.

add_field_value(name, value)

Pass a value that should be assigned to the field called name. Thats the same as specifying it in the field_values argument of the constructor.

create(count=1, commit=True, **kwargs)

Create and return count model instances. If commit is False the instances will not be saved and many to many relations will not be processed.

May raise CreateInstanceError if constraints are not satisfied.

The method internally calls create_one() to generate instances.

create_one(commit=True)

Create and return one model instance. If commit is False the instance will not be saved and many to many relations will not be processed.

Subclasses that override create_one can specify arbitrary keyword arguments. They will be passed through by the autofixture.base.AutoFixture.create() method and the helper functions autofixture.create() and autofixture.create_one().

May raise CreateInstanceError if constraints are not satisfied.

The AutoFixture registry

Since AutoFixture is designed to fit for almost all models, its very generic and doesn’t know anything about the actual logic and meanings of relations or the purpose of your model fields. This makes it sometimes a bit difficult to provide the correct field_values in all places where you want autofixture to instanciate your models.

So there is a registry to register custom AutoFixture subclasses with specific models. These subclasses are then used by default if you generate test data either with the loadtestdata management command or with one of the shortcuts in autofixture.

autofixture.register(model, autofixture, overwrite=False, fail_silently=False)

Register a model with the registry.

Arguments:

model can be either a model class or a string that contains the model’s app label and class name seperated by a dot, e.g. "app.ModelClass".

autofixture is the AutoFixture subclass that shall be used to generated instances of model.

By default register() will raise ValueError if the given model is already registered. You can overwrite the registered model if you pass True to the overwrite argument.

The ValueError that is usually raised if a model is already registered can be suppressed by passing True to the fail_silently argument.

autofixture.unregister(model_or_iterable, fail_silently=False)

Remove one or more models from the autofixture registry.

autofixture.get(model, *args, **kwargs)

Get an autofixture instance for the passed in model sing the either an appropiate autofixture that was registry or fall back to the default:class:AutoFixture class. model can be a model class or its string representation (e.g. "app.ModelClass").

All positional and keyword arguments are passed to the autofixture constructor.

Subclassing AutoFixture

In most cases it will by sufficient to provide a different logic to generate the values for your model fields in AutoFixture subclasses. This can be simply done by a nested Values class:

class EntryFixture(AutoFixture):
    class Values:
        title = 'My static title'
        status = staticmethod(lambda: random.choice((1,2)))
        pub_date = generators.DateTimeGenerator(
            min_date=datetime(2009,1,1),
            max_date=datetime(2009,12,31))

This will make sure that title is always 'My static title', status is either 1 or 2 and that pub_date is in the somewhere in 2009.

Like you can see in the example you can apply static values, simple callables or specific generators to specific fields. However remember to use the staticmethod decorator when using a method as callable - like the lambda statement in the example. It’s in fact also just a shorter definition of a method.

A note on subclassing subclasses and turtles all the way down: Some times it’s usefull for a project to have a common base class for all the registered AutoFixtures. This is ofcourse possible and very usable since you don’t need to re-define all the field definitions in the nested Values class. The AutoFixture class is caring about this and will collect all Values of base classes and merge them together. For clarification here a short example:

class CommonFixture(AutoFixture):
    class Values:
        tags = generators.ChoicesGenerator(
            values=('apple', 'banana', 'orange'))

class EntryFixture(AutoFixture):
    class Values:
        title = 'My static title'

# all created entries will have the same title 'My static title' and one
# tag out of apple, banana and orange.
EntryFixture(Entry).create(5)

If you want to digg deeper and need to customize more logic of model creation, you can override some handy methods of the AutoFixture class:

AutoFixture.prepare_class()

This method is called after the __init__() method. It has no semantic by default.

AutoFixture.post_process_instance(instance, commit)

Overwrite this method to modify the created instance before it gets returned by the create() or create_one(). It gets the generated instance and must return the modified instance. The commit parameter indicates the commit value that the user passed into the create() method. It defaults to True and should be respected, which means if it is set to False, the instance should not be saved.

AutoFixture.get_generator(field)

Return a value generator based on the field instance that is passed to this method. This function may return None which means that the specified field will be ignored (e.g. if no matching generator was found).