{"id":15024386,"url":"https://github.com/factoryboy/factory_boy","last_synced_at":"2025-12-11T21:05:19.700Z","repository":{"id":1485085,"uuid":"1732211","full_name":"FactoryBoy/factory_boy","owner":"FactoryBoy","description":"A test fixtures replacement for Python","archived":false,"fork":false,"pushed_at":"2025-02-03T09:49:14.000Z","size":1896,"stargazers_count":3632,"open_issues_count":189,"forks_count":401,"subscribers_count":40,"default_branch":"master","last_synced_at":"2025-05-08T18:02:59.789Z","etag":null,"topics":["django","fixtures","hacktoberfest","python","sqlalchemy","testing"],"latest_commit_sha":null,"homepage":"https://factoryboy.readthedocs.io/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/FactoryBoy.png","metadata":{"files":{"readme":"README.rst","changelog":"ChangeLog","contributing":"CONTRIBUTING.rst","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":".github/SUPPORT.md","governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2011-05-11T08:26:59.000Z","updated_at":"2025-05-08T13:35:44.000Z","dependencies_parsed_at":"2024-04-25T09:51:45.497Z","dependency_job_id":"049699f8-65d3-493a-af85-014be83ace1d","html_url":"https://github.com/FactoryBoy/factory_boy","commit_stats":{"total_commits":978,"total_committers":137,"mean_commits":7.138686131386861,"dds":0.5725971370143149,"last_synced_commit":"d6349de49b647bb8b7f5d620757a919463f27f7e"},"previous_names":["rbarrois/factory_boy"],"tags_count":46,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FactoryBoy%2Ffactory_boy","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FactoryBoy%2Ffactory_boy/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FactoryBoy%2Ffactory_boy/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/FactoryBoy%2Ffactory_boy/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/FactoryBoy","download_url":"https://codeload.github.com/FactoryBoy/factory_boy/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253133347,"owners_count":21859150,"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","fixtures","hacktoberfest","python","sqlalchemy","testing"],"created_at":"2024-09-24T20:00:14.533Z","updated_at":"2025-12-11T21:05:14.653Z","avatar_url":"https://github.com/FactoryBoy.png","language":"Python","readme":"factory_boy\n===========\n\n.. image:: https://github.com/FactoryBoy/factory_boy/workflows/Test/badge.svg\n    :target: https://github.com/FactoryBoy/factory_boy/actions?query=workflow%3ATest\n\n.. image:: https://github.com/FactoryBoy/factory_boy/workflows/Check/badge.svg\n    :target: https://github.com/FactoryBoy/factory_boy/actions?query=workflow%3ACheck\n\n.. image:: https://img.shields.io/pypi/v/factory_boy.svg\n    :target: https://factoryboy.readthedocs.io/en/latest/changelog.html\n    :alt: Latest Version\n\n.. image:: https://img.shields.io/pypi/pyversions/factory_boy.svg\n    :target: https://pypi.org/project/factory-boy/\n    :alt: Supported Python versions\n\n.. image:: https://img.shields.io/pypi/wheel/factory_boy.svg\n    :target: https://pypi.org/project/factory-boy/\n    :alt: Wheel status\n\n.. image:: https://img.shields.io/pypi/l/factory_boy.svg\n    :target: https://github.com/FactoryBoy/factory_boy/blob/master/LICENSE\n    :alt: License\n\nfactory_boy is a fixtures replacement based on thoughtbot's `factory_bot \u003chttps://github.com/thoughtbot/factory_bot\u003e`_.\n\nAs a fixtures replacement tool, it aims to replace static, hard to maintain fixtures\nwith easy-to-use factories for complex objects.\n\nInstead of building an exhaustive test setup with every possible combination of corner cases,\n``factory_boy`` allows you to use objects customized for the current test,\nwhile only declaring the test-specific fields:\n\n.. code-block:: python\n\n    class FooTests(unittest.TestCase):\n\n        def test_with_factory_boy(self):\n            # We need a 200€, paid order, shipping to australia, for a VIP customer\n            order = OrderFactory(\n                amount=200,\n                status='PAID',\n                customer__is_vip=True,\n                address__country='AU',\n            )\n            # Run the tests here\n\n        def test_without_factory_boy(self):\n            address = Address(\n                street=\"42 fubar street\",\n                zipcode=\"42Z42\",\n                city=\"Sydney\",\n                country=\"AU\",\n            )\n            customer = Customer(\n                first_name=\"John\",\n                last_name=\"Doe\",\n                phone=\"+1234\",\n                email=\"john.doe@example.org\",\n                active=True,\n                is_vip=True,\n                address=address,\n            )\n            # etc.\n\nfactory_boy is designed to work well with various ORMs (Django, MongoDB, SQLAlchemy),\nand can easily be extended for other libraries.\n\nIts main features include:\n\n- Straightforward declarative syntax\n- Chaining factory calls while retaining the global context\n- Support for multiple build strategies (saved/unsaved instances, stubbed objects)\n- Multiple factories per class support, including inheritance\n\n\nLinks\n-----\n\n* Documentation: https://factoryboy.readthedocs.io/\n* Repository: https://github.com/FactoryBoy/factory_boy\n* Package: https://pypi.org/project/factory-boy/\n* Mailing-list: `factoryboy@googlegroups.com \u003cmailto:factoryboy@googlegroups.com\u003e`_ | https://groups.google.com/forum/#!forum/factoryboy\n\n\nDownload\n--------\n\nPyPI: https://pypi.org/project/factory-boy/\n\n.. code-block:: sh\n\n    $ pip install factory_boy\n\nSource: https://github.com/FactoryBoy/factory_boy/\n\n.. code-block:: sh\n\n    $ git clone git://github.com/FactoryBoy/factory_boy/\n    $ python setup.py install\n\n\nUsage\n-----\n\n\n.. note:: This section provides a quick summary of factory_boy features.\n          A more detailed listing is available in the full documentation.\n\n\nDefining factories\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\nFactories declare a set of attributes used to instantiate a Python object.\nThe class of the object must be defined in the ``model`` field of a ``class Meta:`` attribute:\n\n.. code-block:: python\n\n    import factory\n    from . import models\n\n    class UserFactory(factory.Factory):\n        class Meta:\n            model = models.User\n\n        first_name = 'John'\n        last_name = 'Doe'\n        admin = False\n\n    # Another, different, factory for the same object\n    class AdminFactory(factory.Factory):\n        class Meta:\n            model = models.User\n\n        first_name = 'Admin'\n        last_name = 'User'\n        admin = True\n\n\nORM integration\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\nfactory_boy integration with Object Relational Mapping (ORM) tools is provided\nthrough specific ``factory.Factory`` subclasses:\n\n* Django, with ``factory.django.DjangoModelFactory``\n* Mogo, with ``factory.mogo.MogoFactory``\n* MongoEngine, with ``factory.mongoengine.MongoEngineFactory``\n* SQLAlchemy, with ``factory.alchemy.SQLAlchemyModelFactory``\n\nMore details can be found in the ORM section.\n\n\nUsing factories\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\nfactory_boy supports several different instantiation strategies: build, create, and stub:\n\n.. code-block:: python\n\n    # Returns a User instance that's not saved\n    user = UserFactory.build()\n\n    # Returns a saved User instance.\n    # UserFactory must subclass an ORM base class, such as DjangoModelFactory.\n    user = UserFactory.create()\n\n    # Returns a stub object (just a bunch of attributes)\n    obj = UserFactory.stub()\n\n\nYou can use the Factory class as a shortcut for the default instantiation strategy:\n\n.. code-block:: python\n\n    # Same as UserFactory.create()\n    user = UserFactory()\n\n\nNo matter which strategy is used, it's possible to override the defined attributes by passing keyword arguments:\n\n.. code-block:: pycon\n\n    # Build a User instance and override first_name\n    \u003e\u003e\u003e user = UserFactory.build(first_name='Joe')\n    \u003e\u003e\u003e user.first_name\n    \"Joe\"\n\n\nIt is also possible to create a bunch of objects in a single call:\n\n.. code-block:: pycon\n\n    \u003e\u003e\u003e users = UserFactory.build_batch(10, first_name=\"Joe\")\n    \u003e\u003e\u003e len(users)\n    10\n    \u003e\u003e\u003e [user.first_name for user in users]\n    [\"Joe\", \"Joe\", \"Joe\", \"Joe\", \"Joe\", \"Joe\", \"Joe\", \"Joe\", \"Joe\", \"Joe\"]\n\n\nRealistic, random values\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\nDemos look better with random yet realistic values; and those realistic values can also help discover bugs.\nFor this, factory_boy relies on the excellent `faker \u003chttps://faker.readthedocs.io/en/latest/\u003e`_ library:\n\n.. code-block:: python\n\n    class RandomUserFactory(factory.Factory):\n        class Meta:\n            model = models.User\n\n        first_name = factory.Faker('first_name')\n        last_name = factory.Faker('last_name')\n\n.. code-block:: pycon\n\n    \u003e\u003e\u003e RandomUserFactory()\n    \u003cUser: Lucy Murray\u003e\n\n\nReproducible random values\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\nThe use of fully randomized data in tests is quickly a problem for reproducing broken builds.\nTo that purpose, factory_boy provides helpers to handle the random seeds it uses, located in the ``factory.random`` module:\n\n.. code-block:: python\n\n    import factory.random\n\n    def setup_test_environment():\n        factory.random.reseed_random('my_awesome_project')\n        # Other setup here\n\n\nLazy Attributes\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\nMost factory attributes can be added using static values that are evaluated when the factory is defined,\nbut some attributes (such as fields whose value is computed from other elements)\nwill need values assigned each time an instance is generated.\n\nThese \"lazy\" attributes can be added as follows:\n\n.. code-block:: python\n\n    class UserFactory(factory.Factory):\n        class Meta:\n            model = models.User\n\n        first_name = 'Joe'\n        last_name = 'Blow'\n        email = factory.LazyAttribute(lambda a: '{}.{}@example.com'.format(a.first_name, a.last_name).lower())\n        date_joined = factory.LazyFunction(datetime.now)\n\n.. code-block:: pycon\n\n    \u003e\u003e\u003e UserFactory().email\n    \"joe.blow@example.com\"\n\n\n.. note:: ``LazyAttribute`` calls the function with the object being constructed as an argument, when\n          ``LazyFunction`` does not send any argument.\n\n\nSequences\n\"\"\"\"\"\"\"\"\"\n\nUnique values in a specific format (for example, e-mail addresses) can be generated using sequences. Sequences are defined by using ``Sequence`` or the decorator ``sequence``:\n\n.. code-block:: python\n\n    class UserFactory(factory.Factory):\n        class Meta:\n            model = models.User\n\n        email = factory.Sequence(lambda n: 'person{}@example.com'.format(n))\n\n    \u003e\u003e\u003e UserFactory().email\n    'person0@example.com'\n    \u003e\u003e\u003e UserFactory().email\n    'person1@example.com'\n\n\nAssociations\n\"\"\"\"\"\"\"\"\"\"\"\"\n\nSome objects have a complex field, that should itself be defined from a dedicated factories.\nThis is handled by the ``SubFactory`` helper:\n\n.. code-block:: python\n\n    class PostFactory(factory.Factory):\n        class Meta:\n            model = models.Post\n\n        author = factory.SubFactory(UserFactory)\n\n\nThe associated object's strategy will be used:\n\n\n.. code-block:: python\n\n    # Builds and saves a User and a Post\n    \u003e\u003e\u003e post = PostFactory()\n    \u003e\u003e\u003e post.id is None  # Post has been 'saved'\n    False\n    \u003e\u003e\u003e post.author.id is None  # post.author has been saved\n    False\n\n    # Builds but does not save a User, and then builds but does not save a Post\n    \u003e\u003e\u003e post = PostFactory.build()\n    \u003e\u003e\u003e post.id is None\n    True\n    \u003e\u003e\u003e post.author.id is None\n    True\n\nSupport Policy\n--------------\n\n``factory_boy`` supports active Python versions as well as PyPy3.\n\n- **Python**'s `supported versions\n  \u003chttps://devguide.python.org/versions/#supported-versions\u003e`__.\n- **Django**'s `supported\n  versions \u003chttps://www.djangoproject.com/download/#supported-versions\u003e`__.\n- **SQLAlchemy**: `latest version on PyPI \u003chttps://pypi.org/project/SQLAlchemy/\u003e`__.\n- **MongoEngine**: `latest version on PyPI \u003chttps://pypi.org/project/mongoengine/\u003e`__.\n\nDebugging factory_boy\n---------------------\n\nDebugging factory_boy can be rather complex due to the long chains of calls.\nDetailed logging is available through the ``factory`` logger.\n\nA helper, `factory.debug()`, is available to ease debugging:\n\n.. code-block:: python\n\n    with factory.debug():\n        obj = TestModel2Factory()\n\n\n    import logging\n    logger = logging.getLogger('factory')\n    logger.addHandler(logging.StreamHandler())\n    logger.setLevel(logging.DEBUG)\n\nThis will yield messages similar to those (artificial indentation):\n\n.. code-block:: ini\n\n    BaseFactory: Preparing tests.test_using.TestModel2Factory(extra={})\n      LazyStub: Computing values for tests.test_using.TestModel2Factory(two=\u003cOrderedDeclarationWrapper for \u003cfactory.declarations.SubFactory object at 0x1e15610\u003e\u003e)\n        SubFactory: Instantiating tests.test_using.TestModelFactory(__containers=(\u003cLazyStub for tests.test_using.TestModel2Factory\u003e,), one=4), create=True\n        BaseFactory: Preparing tests.test_using.TestModelFactory(extra={'__containers': (\u003cLazyStub for tests.test_using.TestModel2Factory\u003e,), 'one': 4})\n          LazyStub: Computing values for tests.test_using.TestModelFactory(one=4)\n          LazyStub: Computed values, got tests.test_using.TestModelFactory(one=4)\n        BaseFactory: Generating tests.test_using.TestModelFactory(one=4)\n      LazyStub: Computed values, got tests.test_using.TestModel2Factory(two=\u003ctests.test_using.TestModel object at 0x1e15410\u003e)\n    BaseFactory: Generating tests.test_using.TestModel2Factory(two=\u003ctests.test_using.TestModel object at 0x1e15410\u003e)\n\nContributing\n------------\n\nfactory_boy is distributed under the MIT License.\n\nIssues should be opened through `GitHub Issues \u003chttps://github.com/FactoryBoy/factory_boy/issues/\u003e`_; whenever possible, a pull request should be included.\nQuestions and suggestions are welcome on the `mailing-list \u003cmailto:factoryboy@googlegroups.com\u003e`_.\n\nDevelopment dependencies can be installed in a `virtualenv\n\u003chttps://docs.python.org/3/tutorial/venv.html\u003e`_ with:\n\n.. code-block:: sh\n\n    $ pip install --editable '.[dev]'\n\nAll pull requests should pass the test suite, which can be launched simply with:\n\n.. code-block:: sh\n\n    $ make testall\n\n\n\nIn order to test coverage, please use:\n\n.. code-block:: sh\n\n    $ make coverage\n\n\nTo test with a specific framework version, you may use a ``tox`` target:\n\n.. code-block:: sh\n\n    # list all tox environments\n    $ tox --listenvs\n\n    # run tests inside a specific environment (django/mongoengine/SQLAlchemy are not installed)\n    $ tox -e py310\n\n    # run tests inside a specific environment (django)\n    $ tox -e py310-djangomain\n\n    # run tests inside a specific environment (alchemy)\n    $ tox -e py310-alchemy\n\n    # run tests inside a specific environment (mongoengine)\n    $ tox -e py310-mongo\n\n\nPackaging\n---------\n\nFor users interesting in packaging FactoryBoy into downstream distribution channels\n(e.g. ``.deb``, ``.rpm``, ``.ebuild``), the following tips might be helpful:\n\nDependencies\n\"\"\"\"\"\"\"\"\"\"\"\"\n\nThe package's run-time dependencies are listed in ``setup.cfg``.\nThe dependencies useful for building and testing the library are covered by the\n``dev`` and ``doc`` extras.\n\nMoreover, all development / testing tasks are driven through ``make(1)``.\n\nBuilding\n\"\"\"\"\"\"\"\"\n\nIn order to run the build steps (currently only for docs), run:\n\n.. code-block:: sh\n\n    python setup.py egg_info\n    make doc\n\nTesting\n\"\"\"\"\"\"\"\n\nWhen testing for the active Python environment, run the following:\n\n.. code-block:: sh\n\n    make test\n\n.. note::\n\n    You must make sure that the ``factory`` module is importable, as it is imported from\n    the testing code.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffactoryboy%2Ffactory_boy","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffactoryboy%2Ffactory_boy","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffactoryboy%2Ffactory_boy/lists"}