mixer

Mixer -- Is a fixtures replacement. Supported Django, Flask, SqlAlchemy and custom python objects.

https://github.com/klen/mixer

Science Score: 23.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
  • DOI references
  • Academic publication links
  • Committers with academic emails
    2 of 43 committers (4.7%) from academic institutions
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (14.4%) to scientific vocabulary

Keywords

django flask sqlalchemy testing testing-tools

Keywords from Contributors

apps templates views asyncio aiohttp http-client http-server optimizing-compiler scheduling orchestration-framework
Last synced: 6 months ago · JSON representation

Repository

Mixer -- Is a fixtures replacement. Supported Django, Flask, SqlAlchemy and custom python objects.

Basic Info
  • Host: GitHub
  • Owner: klen
  • License: other
  • Language: Python
  • Default Branch: develop
  • Homepage:
  • Size: 1.02 MB
Statistics
  • Stars: 946
  • Watchers: 10
  • Forks: 95
  • Open Issues: 49
  • Releases: 0
Topics
django flask sqlalchemy testing testing-tools
Created almost 13 years ago · Last pushed almost 2 years ago
Metadata Files
Readme Changelog License

README.rst

.. image:: https://raw.github.com/klen/mixer/develop/docs/_static/logo.png
    :width: 100px

The **Mixer** is a helper to generate instances of Django or SQLAlchemy models.
It's useful for testing and fixture replacement. Fast and convenient test-data
generation.

Mixer supports:

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

.. _badges:

.. image:: https://github.com/klen/mixer/workflows/tests/badge.svg?style=flat-square
    :target: https://github.com/klen/mixer/actions
    :alt: Tests Status

.. 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

.. _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.html

.. important::

   From version 6.2 the Mixer library doesn't support Python 2.
   The latest version with python<3 support is mixer 6.1.3


.. _contents:

.. contents::


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

- Python 3.7+
- Django (3.0, 3.1) for Django ORM support;
- Flask-SQLALchemy for SQLAlchemy ORM support and integration as Flask application;
- Faker >= 0.7.3
- Mongoengine for Mongoengine ODM support;
- SQLAlchemy for SQLAlchemy ORM support;
- Peewee ORM support;


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

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

    pip install mixer


Usage
=====

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


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


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

.. code-block:: python

    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 SomeModel from SomeApp and skip the generation of money field
    some = mixer.blend('someapp.somemodel', money=mixer.SKIP)

    # 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:

.. code-block:: python

    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 SomeModel from SomeApp and skip the generation of money field
    some = mixer.blend('project.models.SomeModel', money=mixer.SKIP)

    # 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:

.. code-block:: python

    from mixer.backend.sqlalchemy import Mixer

    class MyOwnMixer(Mixer):

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

    mixer = MyOwnMixer()


SQLAlchemy workflow
-------------------

Example of initialization:

.. code-block:: python

    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 workflow
--------------------

Example usage:

.. code-block:: python

    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)
        username = 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')

Marshmallow workflow
--------------------

Example usage:

.. code-block:: python

    from mixer.backend.marshmallow import mixer
    import marshmallow as ma

    class User(ma.Schema):
        created_at = ma.fields.DateTime(required=True)
        email = ma.fields.Email(required=True)
        first_name = ma.fields.String(required=True)
        last_name = ma.fields.String(required=True)
        username = ma.fields.String(required=True)

    class Post(ma.Schema):
        title = ma.fields.String(required=True)
        author = ma.fields.Nested(User, required=True)

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


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

.. code-block:: python

    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 preventing this behavior init `mixer` manually:

.. code-block:: python

    from mixer.backend.django import Mixer

    mixer = Mixer(commit=False)


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

.. code-block:: python

    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
-------------

The mixer allows you to define generators for fields by manually.
Quick example:

.. code-block:: python

        from mixer.main import mixer

        class Test:
            id = int
            name = str

        mixer.register(Test,
            name=lambda: 'John',
            id=lambda: str(mixer.faker.small_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:

.. code-block:: python

    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
-----------

You can add middleware layers to process generation:

.. code-block:: python

    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.

It's also possible to unregister a middleware:

.. code-block:: python

    mixer.unregister_middleware(encrypt_password)


Locales
-------

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

.. code-block:: python

    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:

.. code-block:: python

    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
============

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


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

* Antoine Bertin            (https://github.com/Diaoul)
* Benjamin Port             (https://github.com/bport)
* Dmitriy Moseev            (https://github.com/DmitriyMoseev)
* Eelke Hermens             (https://github.com/eelkeh)
* Esteban J. G. Gabancho    (https://github.com/egabancho)
* Felix Dreissig            (https://github.com/F30)
* Illia Volochii            (https://github.com/illia-v)
* Jannis                    (https://github.com/jnns)
* 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)
* Marigold                  (https://github.com/Marigold)
* Matt Caldwell             (https://github.com/mattcaldwell)
* Mikhail Porokhovnichenko  (https://github.com/marazmiki)
* Skylar Saveland           (https://github.com/skyl)
* Suriya Subramanian        (https://github.com/suriya)
* Gram                      (https://github.com/orsinium)
* Joshua                    (https://github.com/jomasti)
* Lucas Rangel Cezimbra     (https://github.com/lucasrcezimbra)
* avi-pomicell              (https://github.com/avi-pomicell)
* Jochen Brissier           (https://github.com/jbrissier)


License
========

Licensed under a `BSD license`_.


.. _links:

.. _Django: http://djangoproject.com/
.. _Flask: https://flask.palletsprojects.com/en/1.1.x/
.. _Flask-SQLAlchemy: http://flask-sqlalchemy.pocoo.org/
.. _SQLAlchemy: http://www.sqlalchemy.org/
.. _Marshmallow: http://marshmallow.readthedocs.io/en/latest/
.. _Mongoengine: http://mongoengine.org/
.. _Peewee: http://peewee.readthedocs.org/en/latest/
.. _Pony: http://ponyorm.com/
.. _klen: http://klen.github.io
.. _BSD license: http://www.linfo.org/bsdlicense.html

Owner

  • Name: Kirill Klenov
  • Login: klen
  • Kind: user
  • Location: Russia, Moscow
  • Company: home

More than 10 years of experience in software engineering. Working with different programming languages and in multiple fields of IT for more than 15 years.

GitHub Events

Total
  • Watch event: 11
  • Fork event: 2
Last Year
  • Watch event: 11
  • Fork event: 2

Committers

Last synced: 9 months ago

All Time
  • Total Commits: 573
  • Total Committers: 43
  • Avg Commits per committer: 13.326
  • Development Distribution Score (DDS): 0.192
Past Year
  • Commits: 0
  • Committers: 0
  • Avg Commits per committer: 0.0
  • Development Distribution Score (DDS): 0.0
Top Committers
Name Email Commits
Kirill Klenov h****s@g****m 463
Mikhail Porokhovnichenko m****i@g****m 39
Gram m****s@m****u 7
Kirill Pavlov k****v@p****u 7
Felix Dreissig f****g@n****t 4
Lucas Rangel Cezimbra l****a@g****m 4
Illia Volochii i****i@g****m 3
alexlanders a****s@m****m 3
Suriya Subramanian s****a@a****u 2
Mojmir Vinkler m****r@g****m 2
Joshua Stiefer f****k@g****m 2
Jannis j****n@g****m 2
Garrett Jenkins g****V 2
Emlyn Clay e****1@g****m 2
Eelke Hermens e****s@g****m 2
Kirill Pavlov kp@m****t 2
Ashish Saini a****i@o****n 1
Benjamin Port b****t@b****r 1
Diaoul d****l@g****m 1
Matt Caldwell m****l@g****m 1
Alexander Zelenyak z****i@g****m 1
Yan P Aung y****g@g****m 1
Tim Gates t****s@i****m 1
Skylar Saveland s****d@c****m 1
Ofer Nave o****y@g****m 1
Maxime 1****h 1
Mathilda 6****a 1
Matheus Oliveira m****o 1
Marek Baczyński i****k@g****m 1
Mahdi Yusuf y****i@g****m 1
and 13 more...

Issues and Pull Requests

Last synced: 9 months ago

All Time
  • Total issues: 37
  • Total pull requests: 66
  • Average time to close issues: over 1 year
  • Average time to close pull requests: 4 months
  • Total issue authors: 33
  • Total pull request authors: 27
  • Average comments per issue: 1.19
  • Average comments per pull request: 1.26
  • Merged pull requests: 15
  • Bot issues: 0
  • Bot pull requests: 35
Past Year
  • Issues: 1
  • Pull requests: 0
  • Average time to close issues: N/A
  • Average time to close pull requests: N/A
  • Issue authors: 1
  • Pull request authors: 0
  • Average comments per issue: 0.0
  • Average comments per pull request: 0
  • Merged pull requests: 0
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
  • jvllmr (2)
  • denisvolokh (2)
  • lucasrcezimbra (2)
  • rvinzent (2)
  • mbrochh (1)
  • AlwxSin (1)
  • giovanisleite (1)
  • capital-G (1)
  • ranahaani (1)
  • jnns (1)
  • mtilda (1)
  • alpden550 (1)
  • timgates42 (1)
  • austinnichols101 (1)
  • finsterwalder (1)
Pull Request Authors
  • dependabot[bot] (35)
  • lucasrcezimbra (2)
  • odigity (2)
  • orsinium (2)
  • danoctua (2)
  • cclauss (2)
  • timgates42 (2)
  • anis-campos (2)
  • mcbloch (1)
  • ephes (1)
  • richin13 (1)
  • ypa (1)
  • cholarajaa (1)
  • jbrissier (1)
  • jomasti (1)
Top Labels
Issue Labels
Pull Request Labels
dependencies (35) python (27) github_actions (8)

Packages

  • Total packages: 1
  • Total downloads:
    • pypi 200,388 last-month
  • Total docker downloads: 5,891
  • Total dependent packages: 9
  • Total dependent repositories: 1,776
  • Total versions: 156
  • Total maintainers: 1
pypi.org: mixer

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

  • Versions: 156
  • Dependent Packages: 9
  • Dependent Repositories: 1,776
  • Downloads: 200,388 Last month
  • Docker Downloads: 5,891
Rankings
Dependent repos count: 0.3%
Downloads: 1.0%
Dependent packages count: 1.0%
Docker downloads count: 1.8%
Average: 1.8%
Stargazers count: 2.1%
Forks count: 4.6%
Maintainers (1)
Last synced: 6 months ago

Dependencies

requirements-tests.txt pypi
  • Django >=3.0 test
  • Flask >=1.0 test
  • Marshmallow >=3.9 test
  • SQLAlchemy >=1.1.4 test
  • flask-sqlalchemy >=2.1 test
  • mongoengine >=0.10.1 test
  • peewee >=3.7.0 test
  • pony >=0.7 test
  • psycopg2-binary >=2.8.4 test
  • pytest * test
requirements.txt pypi
  • Faker >=5.4.0,<12.1
setup.py pypi
  • for *
  • if *
.github/workflows/release.yml actions
  • actions/checkout main composite
  • actions/download-artifact v2 composite
  • actions/setup-python main composite
  • actions/upload-artifact v2 composite
  • archive/github-actions-slack master composite
  • pypa/gh-action-pypi-publish master composite
.github/workflows/tests.yml actions
  • actions/cache v2 composite
  • actions/checkout v2 composite
  • actions/setup-python main composite
  • archive/github-actions-slack master composite