{"id":13421675,"url":"https://github.com/klen/mixer","last_synced_at":"2025-05-14T20:04:12.616Z","repository":{"id":8536824,"uuid":"10156090","full_name":"klen/mixer","owner":"klen","description":"Mixer -- Is a fixtures replacement. Supported Django, Flask, SqlAlchemy and custom python objects. ","archived":false,"fork":false,"pushed_at":"2024-03-08T09:29:07.000Z","size":1073,"stargazers_count":946,"open_issues_count":49,"forks_count":95,"subscribers_count":10,"default_branch":"develop","last_synced_at":"2025-04-06T22:01:36.251Z","etag":null,"topics":["django","flask","sqlalchemy","testing","testing-tools"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/klen.png","metadata":{"files":{"readme":"README.rst","changelog":"Changelog","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2013-05-19T13:49:50.000Z","updated_at":"2025-04-04T06:39:59.000Z","dependencies_parsed_at":"2024-04-28T01:57:21.276Z","dependency_job_id":"cf1e552b-49f6-41aa-9dd0-c6f17ba5b3cf","html_url":"https://github.com/klen/mixer","commit_stats":{"total_commits":573,"total_committers":43,"mean_commits":"13.325581395348838","dds":"0.19197207678883077","last_synced_commit":"431ca2756af5571efc4d08d743fa8ab2a8619183"},"previous_names":[],"tags_count":166,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/klen%2Fmixer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/klen%2Fmixer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/klen%2Fmixer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/klen%2Fmixer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/klen","download_url":"https://codeload.github.com/klen/mixer/tar.gz/refs/heads/develop","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248804781,"owners_count":21164131,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["django","flask","sqlalchemy","testing","testing-tools"],"created_at":"2024-07-30T23:00:28.065Z","updated_at":"2025-04-14T00:52:50.186Z","avatar_url":"https://github.com/klen.png","language":"Python","readme":".. image:: https://raw.github.com/klen/mixer/develop/docs/_static/logo.png\n    :width: 100px\n\nThe **Mixer** is a helper to generate instances of Django or SQLAlchemy models.\nIt's useful for testing and fixture replacement. Fast and convenient test-data\ngeneration.\n\nMixer supports:\n\n* Django_;\n* SQLAlchemy_;\n* Flask-SQLAlchemy_;\n* Peewee_;\n* Pony_;\n* Mongoengine_;\n* Marshmallow_;\n* Custom schemes;\n\n.. _badges:\n\n.. image:: https://github.com/klen/mixer/workflows/tests/badge.svg?style=flat-square\n    :target: https://github.com/klen/mixer/actions\n    :alt: Tests Status\n\n.. image:: http://img.shields.io/pypi/v/mixer.svg?style=flat-square\n    :target: https://pypi.python.org/pypi/mixer\n    :alt: Version\n\n.. image:: http://img.shields.io/pypi/dm/mixer.svg?style=flat-square\n    :target: https://pypi.python.org/pypi/mixer\n    :alt: Downloads\n\n.. image:: http://img.shields.io/pypi/l/mixer.svg?style=flat-square\n    :target: https://pypi.python.org/pypi/mixer\n    :alt: License\n\n.. _documentation:\n\n\n**Docs are available at https://mixer.readthedocs.org/. Pull requests with\ndocumentation enhancements and/or fixes are awesome and most welcome.**\n\nОписание на русском языке: http://klen.github.io/mixer.html\n\n.. important::\n\n   From version 6.2 the Mixer library doesn't support Python 2.\n   The latest version with python\u003c3 support is mixer 6.1.3\n\n\n.. _contents:\n\n.. contents::\n\n\nRequirements\n=============\n\n- Python 3.7+\n- Django (3.0, 3.1) for Django ORM support;\n- Flask-SQLALchemy for SQLAlchemy ORM support and integration as Flask application;\n- Faker \u003e= 0.7.3\n- Mongoengine for Mongoengine ODM support;\n- SQLAlchemy for SQLAlchemy ORM support;\n- Peewee ORM support;\n\n\nInstallation\n=============\n\n**Mixer** should be installed using pip: ::\n\n    pip install mixer\n\n\nUsage\n=====\n\n |   By default Mixer tries to generate fake (human-friendly) data.\n |   If you want to randomize the generated values initialize the Mixer\n |   by manual: Mixer(fake=False)\n\n\n |   By default Mixer saves the generated objects in a database. If you want to disable\n |   this, initialize the Mixer by manual like Mixer(commit=False)\n\n\nDjango workflow\n---------------\nQuick example:\n\n.. code-block:: python\n\n    from mixer.backend.django import mixer\n    from customapp.models import User, UserMessage\n\n    # Generate a random user\n    user = mixer.blend(User)\n\n    # Generate an UserMessage\n    message = mixer.blend(UserMessage, user=user)\n\n    # Generate an UserMessage and an User. Set username for generated user to 'testname'.\n    message = mixer.blend(UserMessage, user__username='testname')\n\n    # Generate SomeModel from SomeApp and select FK or M2M values from db\n    some = mixer.blend('someapp.somemodel', somerelation=mixer.SELECT)\n\n    # Generate SomeModel from SomeApp and force a value of money field from default to random\n    some = mixer.blend('someapp.somemodel', money=mixer.RANDOM)\n    \n    # Generate SomeModel from SomeApp and skip the generation of money field\n    some = mixer.blend('someapp.somemodel', money=mixer.SKIP)\n\n    # Generate 5 SomeModel's instances and take company field's values from custom generator\n    some_models = mixer.cycle(5).blend('somemodel', company=(name for name in company_names))\n\n\nFlask, Flask-SQLAlchemy\n-----------------------\nQuick example:\n\n.. code-block:: python\n\n    from mixer.backend.flask import mixer\n    from models import User, UserMessage\n\n    mixer.init_app(self.app)\n\n    # Generate a random user\n    user = mixer.blend(User)\n\n    # Generate an userMessage\n    message = mixer.blend(UserMessage, user=user)\n\n    # Generate an UserMessage and an User. Set username for generated user to 'testname'.\n    message = mixer.blend(UserMessage, user__username='testname')\n\n    # Generate SomeModel and select FK or M2M values from db\n    some = mixer.blend('project.models.SomeModel', somerelation=mixer.SELECT)\n\n    # Generate SomeModel from SomeApp and force a value of money field from default to random\n    some = mixer.blend('project.models.SomeModel', money=mixer.RANDOM)\n    \n    # Generate SomeModel from SomeApp and skip the generation of money field\n    some = mixer.blend('project.models.SomeModel', money=mixer.SKIP)\n\n    # Generate 5 SomeModel's instances and take company field's values from custom generator\n    some_models = mixer.cycle(5).blend('project.models.SomeModel', company=(company for company in companies))\n\n\nSupport for Flask-SQLAlchemy models that have `__init__` arguments\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nFor support this scheme, just create your own mixer class, like this:\n\n.. code-block:: python\n\n    from mixer.backend.sqlalchemy import Mixer\n\n    class MyOwnMixer(Mixer):\n\n        def populate_target(self, values):\n            target = self.__scheme(**values)\n            return target\n\n    mixer = MyOwnMixer()\n\n\nSQLAlchemy workflow\n-------------------\n\nExample of initialization:\n\n.. code-block:: python\n\n    from mixer.backend.sqlalchemy import Mixer\n\n    ENGINE = create_engine('sqlite:///:memory:')\n    BASE = declarative_base()\n    SESSION = sessionmaker(bind=ENGINE)\n\n    mixer = Mixer(session=SESSION(), commit=True)\n    role = mixer.blend('package.models.Role')\n\n\nAlso, see `Flask`_, `Flask-SQLAlchemy`_.\n\n\nMongoengine workflow\n--------------------\n\nExample usage:\n\n.. code-block:: python\n\n    from mixer.backend.mongoengine import mixer\n\n    class User(Document):\n        created_at = DateTimeField(default=datetime.datetime.now)\n        email = EmailField(required=True)\n        first_name = StringField(max_length=50)\n        last_name = StringField(max_length=50)\n        username = StringField(max_length=50)\n\n    class Post(Document):\n        title = StringField(max_length=120, required=True)\n        author = ReferenceField(User)\n        tags = ListField(StringField(max_length=30))\n\n    post = mixer.blend(Post, author__username='foo')\n\nMarshmallow workflow\n--------------------\n\nExample usage:\n\n.. code-block:: python\n\n    from mixer.backend.marshmallow import mixer\n    import marshmallow as ma\n\n    class User(ma.Schema):\n        created_at = ma.fields.DateTime(required=True)\n        email = ma.fields.Email(required=True)\n        first_name = ma.fields.String(required=True)\n        last_name = ma.fields.String(required=True)\n        username = ma.fields.String(required=True)\n\n    class Post(ma.Schema):\n        title = ma.fields.String(required=True)\n        author = ma.fields.Nested(User, required=True)\n\n    post = mixer.blend(Post, author__username='foo')\n\n\nCommon usage\n------------\nQuick example:\n\n.. code-block:: python\n\n    from mixer.main import mixer\n\n    class Test:\n        one = int\n        two = int\n        name = str\n\n    class Scheme:\n        name = str\n        money = int\n        male = bool\n        prop = Test\n\n    scheme = mixer.blend(Scheme, prop__one=1)\n\n\nDB commits\n----------\n\nBy default 'django', 'flask', 'mongoengine' backends tries to save objects in\ndatabase. For preventing this behavior init `mixer` manually:\n\n.. code-block:: python\n\n    from mixer.backend.django import Mixer\n\n    mixer = Mixer(commit=False)\n\n\nOr you can temporary switch context use the mixer as context manager:\n\n.. code-block:: python\n\n    from mixer.backend.django import mixer\n\n    # Will be save to db\n    user1 = mixer.blend('auth.user')\n\n    # Will not be save to db\n    with mixer.ctx(commit=False):\n        user2 = mixer.blend('auth.user')\n\n\n.. _custom:\n\nCustom fields\n-------------\n\nThe mixer allows you to define generators for fields by manually.\nQuick example:\n\n.. code-block:: python\n\n        from mixer.main import mixer\n\n        class Test:\n            id = int\n            name = str\n\n        mixer.register(Test,\n            name=lambda: 'John',\n            id=lambda: str(mixer.faker.small_positive_integer())\n        )\n\n        test = mixer.blend(Test)\n        test.name == 'John'\n        isinstance(test.id, str)\n\n        # You could pinned just a value to field\n        mixer.register(Test, name='Just John')\n        test = mixer.blend(Test)\n        test.name == 'Just John'\n\nAlso, you can make your own factory for field types:\n\n.. code-block:: python\n\n    from mixer.backend.django import Mixer, GenFactory\n\n    def get_func(*args, **kwargs):\n        return \"Always same\"\n\n    class MyFactory(GenFactory):\n        generators = {\n            models.CharField: get_func\n        }\n\n    mixer = Mixer(factory=MyFactory)\n\nMiddlewares\n-----------\n\nYou can add middleware layers to process generation:\n\n.. code-block:: python\n\n    from mixer.backend.django import mixer\n\n    # Register middleware to model\n    @mixer.middleware('auth.user')\n    def encrypt_password(user):\n        user.set_password('test')\n        return user\n\nYou can add several middlewares. Each middleware should get one argument\n(generated value) and return them.\n\nIt's also possible to unregister a middleware:\n\n.. code-block:: python\n\n    mixer.unregister_middleware(encrypt_password)\n\n\nLocales\n-------\n\nBy default mixer uses 'en' locale. You could switch mixer default locale by\ncreating your own mixer:\n\n.. code-block:: python\n\n    from mixer.backend.django import Mixer\n\n    mixer = Mixer(locale='it')\n    mixer.faker.name()          ## u'Acchisio Conte'\n\nAt any time you could switch mixer current locale:\n\n.. code-block:: python\n\n    mixer.faker.locale = 'cz'\n    mixer.faker.name()          ## u'Miloslava Urbanov\\xe1 CSc.'\n\n    mixer.faker.locale = 'en'\n    mixer.faker.name()          ## u'John Black'\n\n    # Use the mixer context manager\n    mixer.faker.phone()         ## u'1-438-238-1116'\n    with mixer.ctx(locale='fr'):\n        mixer.faker.phone()     ## u'08 64 92 11 79'\n\n    mixer.faker.phone()         ## u'1-438-238-1116'\n\n.. _bugtracker:\n\nBug tracker\n===========\n\nIf you have any suggestions, bug reports or\nannoyances please report them to the issue tracker\nat https://github.com/klen/mixer/issues\n\n\nContributing\n============\n\nDevelopment of mixer happens at Github: https://github.com/klen/mixer\n\n\nContributors\n=============\n\n* Antoine Bertin            (https://github.com/Diaoul)\n* Benjamin Port             (https://github.com/bport)\n* Dmitriy Moseev            (https://github.com/DmitriyMoseev)\n* Eelke Hermens             (https://github.com/eelkeh)\n* Esteban J. G. Gabancho    (https://github.com/egabancho)\n* Felix Dreissig            (https://github.com/F30)\n* Illia Volochii            (https://github.com/illia-v)\n* Jannis                    (https://github.com/jnns)\n* Kirill Pavlov             (https://github.com/pavlov99)\n* Kwok-kuen Cheung          (https://github.com/cheungpat)\n* Mahdi Yusuf               (https://github.com/myusuf3)\n* Marek Baczyński           (https://github.com/imbaczek)\n* Marigold                  (https://github.com/Marigold)\n* Matt Caldwell             (https://github.com/mattcaldwell)\n* Mikhail Porokhovnichenko  (https://github.com/marazmiki)\n* Skylar Saveland           (https://github.com/skyl)\n* Suriya Subramanian        (https://github.com/suriya)\n* Gram                      (https://github.com/orsinium)\n* Joshua                    (https://github.com/jomasti)\n* Lucas Rangel Cezimbra     (https://github.com/lucasrcezimbra)\n* avi-pomicell              (https://github.com/avi-pomicell)\n* Jochen Brissier           (https://github.com/jbrissier)\n\n\nLicense\n========\n\nLicensed under a `BSD license`_.\n\n\n.. _links:\n\n.. _Django: http://djangoproject.com/\n.. _Flask: https://flask.palletsprojects.com/en/1.1.x/\n.. _Flask-SQLAlchemy: http://flask-sqlalchemy.pocoo.org/\n.. _SQLAlchemy: http://www.sqlalchemy.org/\n.. _Marshmallow: http://marshmallow.readthedocs.io/en/latest/\n.. _Mongoengine: http://mongoengine.org/\n.. _Peewee: http://peewee.readthedocs.org/en/latest/\n.. _Pony: http://ponyorm.com/\n.. _klen: http://klen.github.io\n.. _BSD license: http://www.linfo.org/bsdlicense.html\n","funding_links":[],"categories":["Python","Testing","资源列表","测试","File Manipulation","Testing [🔝](#readme)","Object Factories","Utils","Awesome Python","介绍","Uncategorized"],"sub_categories":["测试","HTTP Clients","Testing","Uncategorized"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fklen%2Fmixer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fklen%2Fmixer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fklen%2Fmixer/lists"}