Skip to main content

Mixer -- Is a fixtures replacement. Supported Django ORM, SqlAlchemy ORM, Mongoengine ODM and custom python objects.

Project description

Home-page: http://github.com/klen/mixer
Author: Kirill Klenov
Author-email: horneds@gmail.com
License: BSD
Description: |logo| Mixer
############

.. _description:

Mixer is an application to generate instances of Django or SQLAlchemy models.
It's useful for testing and fixtures replacement. Fast and convenient test-data
generation.

Mixer supports:

* Django_;
* SQLAlchemy_;
* Flask-SqlAlchemy;
* Peewee_;
* Pony_;
* Mongoengine_;
* Custom schemes;

.. _badges:

.. image:: http://img.shields.io/travis/klen/mixer.svg?style=flat-square
:target: http://travis-ci.org/klen/mixer
:alt: Build Status

.. image:: http://img.shields.io/coveralls/klen/mixer.svg?style=flat-square
:target: https://coveralls.io/r/klen/mixer
:alt: Coverals

.. image:: http://img.shields.io/pypi/v/mixer.svg?style=flat-square
:target: https://pypi.python.org/pypi/mixer
:alt: Version

.. image:: http://img.shields.io/pypi/dm/mixer.svg?style=flat-square
:target: https://pypi.python.org/pypi/mixer
:alt: Downloads

.. image:: http://img.shields.io/pypi/l/mixer.svg?style=flat-square
:target: https://pypi.python.org/pypi/mixer
:alt: License

.. image:: http://img.shields.io/gratipay/klen.svg?style=flat-square
:target: https://www.gratipay.com/klen/
:alt: Donate


.. _documentation:


**Docs are available at https://mixer.readthedocs.org/. Pull requests with
documentation enhancements and/or fixes are awesome and most welcome.**

Описание на русском языке: http://klen.github.io/mixer-ru.html


.. _contents:

.. contents::


.. _requirements:

Requirements
=============

- python (2.6, 2.7, 3.2, 3.3, 3.4)
- fake-factory >= 0.4.2
- Django (1.5, 1.6, 1.7) for django ORM suport;
- SQLAlchemy for SQLAlchemy ORM suport;
- Mongoengine for Mongoengine ODM support;
- Flask-SQLALchemy for SQLAlchemy ORM suport and integration as Flask application;


.. _installation:

Installation
=============

**Mixer** should be installed using pip: ::

pip install mixer


.. _usage:

Usage
=====

| By default Mixer tries to generate a fake (human-friendly) data.
| If you want randomize the generated values initialize the Mixer
| by manual: Mixer(fake=False)


| By default Mixer saves the generated objects in database. If you want disable
| this, initialize the Mixer by manual like: Mixer(commit=False)


Django
------
Quick example: ::

from mixer.backend.django import mixer
from customapp.models import User, UserMessage

# Generate a random user
user = mixer.blend(User)

# Generate an UserMessage
message = mixer.blend(UserMessage, user=user)

# Generate an UserMessage and an User. Set username for generated user to 'testname'.
message = mixer.blend(UserMessage, user__username='testname')

# Generate SomeModel from SomeApp and select FK or M2M values from db
some = mixer.blend('someapp.somemodel', somerelation=mixer.SELECT)

# Generate SomeModel from SomeApp and force a value of money field from default to random
some = mixer.blend('someapp.somemodel', money=mixer.RANDOM)

# Generate 5 SomeModel's instances and take company field's values from custom generator
some_models = mixer.cycle(5).blend('somemodel', company=(name for name in company_names))


Flask, Flask-SQLAlchemy
-----------------------
Quick example: ::

from mixer.backend.flask import mixer
from models import User, UserMessage

mixer.init_app(self.app)

# Generate a random user
user = mixer.blend(User)

# Generate an userMessage
message = mixer.blend(UserMessage, user=user)

# Generate an UserMessage and an User. Set username for generated user to 'testname'.
message = mixer.blend(UserMessage, user__username='testname')

# Generate SomeModel and select FK or M2M values from db
some = mixer.blend('project.models.SomeModel', somerelation=mixer.SELECT)

# Generate SomeModel from SomeApp and force a value of money field from default to random
some = mixer.blend('project.models.SomeModel', money=mixer.RANDOM)

# Generate 5 SomeModel's instances and take company field's values from custom generator
some_models = mixer.cycle(5).blend('project.models.SomeModel', company=(company for company in companies))


Support for Flask-SQLAlchemy models that have `__init__` arguments
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

For support this scheme, just create your own mixer class, like this: ::

from mixer.backend.sqlalchemy import Mixer

class MyOwnMixer(Mixer):

def populate_target(self, values):
target = self.__scheme(**values)
return target

mixer = MyOwnMixer()


SQLAlchemy
----------

Example of initialization: ::

from mixer.backend.sqlalchemy import Mixer

ENGINE = create_engine('sqlite:///:memory:')
BASE = declarative_base()
SESSION = sessionmaker(bind=ENGINE)

mixer = Mixer(session=SESSION(), commit=True)
role = mixer.blend('package.models.Role')


Also see `Flask, Flask-SQLALchemy`_.


Mongoengine
-----------

Example usage: ::

from mixer.backend.mongoengine import mixer

class User(Document):
created_at = DateTimeField(default=datetime.datetime.now)
email = EmailField(required=True)
first_name = StringField(max_length=50)
last_name = StringField(max_length=50)

class Post(Document):
title = StringField(max_length=120, required=True)
author = ReferenceField(User)
tags = ListField(StringField(max_length=30))

post = mixer.blend(Post, author__username='foo')


Common usage
------------
Quick example: ::

from mixer.main import mixer

class Test:
one = int
two = int
name = str

class Scheme:
name = str
money = int
male = bool
prop = Test

scheme = mixer.blend(Scheme, prop__one=1)


DB commits
----------

By default 'django', 'flask', 'mongoengine' backends tries to save objects in
database. For prevent this behaviour init `mixer` manually: ::

from mixer.backend.django import Mixer

mixer = Mixer(commit=False)


Or you can temporary switch context use the mixer as context manager: ::

from mixer.backend.django import mixer

# Will be save to db
user1 = mixer.blend('auth.user')

# Will not be save to db
with mixer.ctx(commit=False):
user2 = mixer.blend('auth.user')


.. _custom:

Custom fields
-------------

Mixer allows you to define generators for fields by manualy.

Quick example: ::

from mixer.main import mixer

class Test:
id = int
name = str

mixer.register(Test,
name=lambda: 'John',
id=lambda: str(mixer.g.get_positive_integer())
)

test = mixer.blend(Test)
test.name == 'John'
isinstance(test.id, str)

# You could pinned just a value to field
mixer.register(Test, name='Just John')
test = mixer.blend(Test)
test.name == 'Just John'

Also you can make your own factory for field types: ::

from mixer.backend.django import Mixer, GenFactory

def get_func(*args, **kwargs):
return "Always same"

class MyFactory(GenFactory):
generators = {
models.CharField: get_func
}

mixer = Mixer(factory=MyFactory)

.. _middlewares:

Middlewares
-----------

You can add middleware layers to process generation: ::

from mixer.backend.django import mixer

# Register middleware to model
@mixer.middleware('auth.user')
def encrypt_password(user):
user.set_password('test')
return user

You can add several middlewares. Each middleware should get one argument
(generated value) and return them.

Locales
-------

By default mixer uses 'en' locale. You could switch mixer default locale by
creating your own mixer: ::

from mixer.backend.django import Mixer

mixer = Mixer(locale='it')
mixer.faker.name() ## u'Acchisio Conte'

At any time you could switch mixer current locale: ::

mixer.faker.locale = 'cz'
mixer.faker.name() ## u'Miloslava Urbanov\xe1 CSc.'

mixer.faker.locale = 'en'
mixer.faker.name() ## u'John Black'

# Use the mixer context manager
mixer.faker.phone() ## u'1-438-238-1116'
with mixer.ctx(locale='fr'):
mixer.faker.phone() ## u'08 64 92 11 79'

mixer.faker.phone() ## u'1-438-238-1116'

.. _bugtracker:

Bug tracker
===========

If you have any suggestions, bug reports or
annoyances please report them to the issue tracker
at https://github.com/klen/mixer/issues


.. _contributing:

Contributing
============

Development of mixer happens at github: https://github.com/klen/mixer


.. _contributors:

Contributors
=============

* Kirill Klenov (https://github.com/klen, horneds@gmail.com)

* Antoine Bertin (https://github.com/Diaoul)
* Dmitriy Moseev (https://github.com/DmitriyMoseev)
* Esteban J. G. Gabancho (https://github.com/egabancho)
* Kirill Pavlov (https://github.com/pavlov99)
* Kwok-kuen Cheung (https://github.com/cheungpat)
* Mahdi Yusuf (https://github.com/myusuf3)
* Marek Baczyński (https://github.com/imbaczek)
* Matt Caldwell (https://github.com/mattcaldwell)
* Skylar Saveland (https://github.com/skyl)


.. _license:

License
=======

Licensed under a `BSD license`_.


.. _links:

.. _BSD license: http://www.linfo.org/bsdlicense.html
.. _klen: http://klen.github.io
.. _SQLAlchemy: http://www.sqlalchemy.org/
.. _Flask: http://flask.pocoo.org/
.. _Peewee: http://peewee.readthedocs.org/en/latest/
.. _Pony: http://ponyorm.com/
.. _Django: http://djangoproject.org/
.. _Mongoengine: http://mongoengine.org/
.. |logo| image:: https://raw.github.com/klen/mixer/develop/docs/_static/logo.png
:width: 100

Keywords: django,flask,sqlalchemy,testing,mock,stub,mongoengine,data
Platform: Any
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: BSD License
Classifier: Natural Language :: English
Classifier: Natural Language :: Russian
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Software Development :: Testing
Classifier: Topic :: Utilities

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

mixer-5.0.5.tar.gz (114.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

mixer-5.0.5-py2.py3-none-any.whl (127.2 kB view details)

Uploaded Python 2Python 3

File details

Details for the file mixer-5.0.5.tar.gz.

File metadata

  • Download URL: mixer-5.0.5.tar.gz
  • Upload date:
  • Size: 114.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for mixer-5.0.5.tar.gz
Algorithm Hash digest
SHA256 3b6c60b0b1f298f6a759541093d1c1e9038349c344245166a36e1dbf6725323d
MD5 9491cd055fd17fc3259d54b6ad001ef8
BLAKE2b-256 7e60258c13465606fa418fa7706f6ed042e1b391560c02bc1476c80aa3ef1a97

See more details on using hashes here.

File details

Details for the file mixer-5.0.5-py2.py3-none-any.whl.

File metadata

File hashes

Hashes for mixer-5.0.5-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 8634d2004232d269f79cf66017b1c00b286bf5ed80e3b2bb29c79bdab37ef0a3
MD5 03a871bc888d4858b15a9779e5924f20
BLAKE2b-256 6b6cb81bfa948ff7b6705b76a3ee913f76318e85aef98b65daf1d851891db337

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page