Builders¶
Builders provide a powerful way to customize getting fixture. You can define
your own builders and provide them as arguments when you instantiate
charlatan.FixturesManager.
Example¶
Here’s an example inspired by the schematics library, which expects a dict of attributes as a single instantiation argument:
from charlatan import FixturesManager
from charlatan.builder import Builder
class Toaster(object):
def __init__(self, attrs):
self.slots = attrs['slots']
class DictBuilder(Builder):
def __call__(self, fixtures, klass, params, **kwargs):
# A "normal" object would be instantiated this way:
# return klass(**params)
# Yet schematics object expect a dict of attributes as only argument.
# So we'll do:
return klass(params)
def test_custom_builder():
manager = FixturesManager(get_builder=DictBuilder())
manager.load('./charlatan/tests/example/data/custom_builder.yaml')
assert manager.get_fixture('toaster').slots == 3
YAML file:
toaster:
model: charlatan.tests.example.test_custom_builder:Toaster
fields:
slots: 3
color: blue
API¶
-
class
charlatan.builder.Builder¶ -
__call__(fixtures, klass, params, **kwargs)¶ Build a fixture.
Parameters: - fixtures (FixturesManager) –
- klass – the fixture’s class (
modelin the definition file) - params – the fixture’s params (
fieldsin the definition file) - kwargs (dict) –
kwargsallows passing arguments to the builder to change its behavior.
-
-
class
charlatan.builder.DeleteAndCommit¶ -
__call__(fixtures, instance, **kwargs)¶
-
delete(instance, session)¶ Delete instance.
-
-
class
charlatan.builder.InstantiateAndSave¶ -
__call__(fixtures, klass, params, **kwargs)¶ Save a fixture instance.
If it’s a SQLAlchemy model, it will be added to the session and the session will be committed.
Otherwise, a
save()method will be run if the instance has one. If it does not have one, nothing will happen.Before and after the process, the
before_save()andafter_save()hook are run.
-
instantiate(klass, params)¶ Return instantiated instance.
-
save(instance, fixtures, session)¶ Save instance.
-