factory_boy_ integration with the pytest_ runner
================================================
.. image:: https://img.shields.io/pypi/v/pytest-factoryboy.svg
:target: https://pypi.python.org/pypi/pytest-factoryboy
.. image:: https://img.shields.io/pypi/pyversions/pytest-factoryboy.svg
:target: https://pypi.python.org/pypi/pytest-factoryboy
.. image:: https://github.com/pytest-dev/pytest-factoryboy/actions/workflows/main.yml/badge.svg
:target: https://github.com/pytest-dev/pytest-factoryboy/actions?query=workflow%3Amain
.. image:: https://readthedocs.org/projects/pytest-factoryboy/badge/?version=latest
:target: https://readthedocs.org/projects/pytest-factoryboy/?badge=latest
:alt: Documentation Status
pytest-factoryboy makes it easy to combine ``factory`` approach to the test setup with the ``dependency`` injection,
heart of the `pytest fixtures`_.
.. _factory_boy: https://factoryboy.readthedocs.io
.. _pytest: https://pytest.org
.. _pytest fixtures: https://pytest.org/latest/fixture.html
.. _overridden: https://docs.pytest.org/en/latest/how-to/fixtures.html#overriding-fixtures-on-various-levels
Install pytest-factoryboy
-------------------------
::
pip install pytest-factoryboy
Concept
-------
Library exports a function to register factories as fixtures. Fixtures are contributed
to the same module where register function is called.
Model Fixture
-------------
Model fixture implements an instance of a model created by the factory. Name convention is model's lowercase-underscore
class name.
.. code-block:: python
import factory
from pytest_factoryboy import register
@register
class AuthorFactory(factory.Factory):
class Meta:
model = Author
name = "Charles Dickens"
def test_model_fixture(author):
assert author.name == "Charles Dickens"
Attributes are Fixtures
-----------------------
There are fixtures created automatically for factory attributes. Attribute names are prefixed with the model fixture name and
double underscore (similar to the convention used by factory_boy).
.. code-block:: python
@pytest.mark.parametrize("author__name", ["Bill Gates"])
def test_model_fixture(author):
assert author.name == "Bill Gates"
Multiple fixtures
-----------------
Model fixtures can be registered with specific names. For example, if you address instances of some collection
by the name like "first", "second" or of another parent as "other":
.. code-block:: python
register(AuthorFactory) # author
register(AuthorFactory, "second_author") # second_author
@register # book
@register(_name="second_book") # second_book
@register(_name="other_book") # other_book, book of another author
class BookFactory(factory.Factory):
class Meta:
model = Book
@pytest.fixture
def other_book__author(second_author):
"""Make the relation of the `other_book.author` to `second_author`."""
return second_author
def test_book_authors(book, second_book, other_book, author, second_author):
assert book.author == second_book.author == author
assert other_book.author == second_author
SubFactory
----------
Sub-factory attribute points to the model fixture of the sub-factory.
Attributes of sub-factories are injected as dependencies to the model fixture and can be overridden_ via
the parametrization.
Related Factory
---------------
Related factory attribute points to the model fixture of the related factory.
Attributes of related factories are injected as dependencies to the model fixture and can be overridden_ via
the parametrization.
post-generation
---------------
Post-generation attribute fixture implements only the extracted value for the post generation function.
Factory Fixture
---------------
`pytest-factoryboy` also registers factory fixtures, to allow their use without importing them. The fixture name convention is to use the lowercase-underscore form of the class name.
.. code-block:: python
import factory
from pytest_factoryboy import register
class AuthorFactory(factory.Factory):
class Meta:
model = Author
register(AuthorFactory) # => author_factory
def test_factory_fixture(author_factory):
author = author_factory(name="Charles Dickens")
assert author.name == "Charles Dickens"
Integration
-----------
An example of factory_boy_ and pytest_ integration.
.. code-block:: python
# tests/factories.py
import factory
from app import models
from faker import Factory as FakerFactory
faker = FakerFactory.create()
class AuthorFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Author
name = factory.LazyFunction(lambda: faker.name())
class BookFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Book
title = factory.LazyFunction(lambda: faker.sentence(nb_words=4))
author = factory.SubFactory(AuthorFactory)
.. code-block:: python
# tests/conftest.py
from pytest_factoryboy import register
from . import factories
register(factories.AuthorFactory)
register(factories.BookFactory)
.. code-block:: python
# tests/test_models.py
from app.models import Book
from .factories import BookFactory
def test_book_factory(book_factory):
"""Factories become fixtures automatically."""
assert book_factory is BookFactory
def test_book(book):
"""Instances become fixtures automatically."""
assert isinstance(book, Book)
@pytest.mark.parametrize("book__title", ["PyTest for Dummies"])
@pytest.mark.parametrize("author__name", ["Bill Gates"])
def test_parametrized(book):
"""You can set any factory attribute as a fixture using naming convention."""
assert book.title == "PyTest for Dummies"
assert book.author.name == "Bill Gates"
Fixture partial specialization
------------------------------
There is a possibility to pass keyword parameters in order to override factory attribute values during fixture
registration. This comes in handy when your test case is requesting a lot of fixture flavors. Too much for the
regular pytest parametrization.
In this case, you can register fixture flavors in the local test module and specify value deviations inside ``register``
function calls.
.. code-block:: python
register(AuthorFactory, "male_author", gender="M", name="John Doe")
register(AuthorFactory, "female_author", gender="F")
@pytest.fixture
def female_author__name():
"""Override female author name as a separate fixture."""
return "Jane Doe"
@pytest.mark.parametrize("male_author__age", [42]) # Override even more
def test_partial(male_author, female_author):
"""Test fixture partial specialization."""
assert male_author.gender == "M"
assert male_author.name == "John Doe"
assert male_author.age == 42
assert female_author.gender == "F"
assert female_author.name == "Jane Doe"
Fixture attributes
------------------
Sometimes it is necessary to pass an instance of another fixture as an attribute value to the factory.
It is possible to override the generated attribute fixture where desired values can be requested as
fixture dependencies. There is also a lazy wrapper for the fixture that can be used in the parametrization
without defining fixtures in a module.
LazyFixture constructor accepts either existing fixture name or callable with dependencies:
.. code-block:: python
import pytest
from pytest_factoryboy import register, LazyFixture
@pytest.mark.parametrize("book__author", [LazyFixture("another_author")])
def test_lazy_fixture_name(book, another_author):
"""Test that book author is replaced with another author by fixture name."""
assert book.author == another_author
@pytest.mark.parametrize("book__author", [LazyFixture(lambda another_author: another_author)])
def test_lazy_fixture_callable(book, another_author):
"""Test that book author is replaced with another author by callable."""
assert book.author == another_author
# Can also be used in the partial specialization during the registration.
register(BookFactory, "another_book", author=LazyFixture("another_author"))
Generic container classes as models
-----------------------------------
It's often useful to create factories for ``dict`` or other common generic container classes.
In that case, you should wrap the container class around ``named_model(...)``, so that pytest-factoryboy can correctly determine the model name when using it in a SubFactory or RelatedFactory.
Pytest-factoryboy will otherwise raise a warning.
For example:
.. code-block:: python
import factory
from pytest_factoryboy import named_model, register
@register
class JSONPayload(factory.Factory):
class Meta:
model = named_model("JSONPayload", dict)
name = "foo"
def test_foo(json_payload):
assert json_payload.name == "foo"
As a bonus, factory is automatically registering the ``json_payload`` fixture (rather than ``dict``), so there is no need to override ``@register(_name="json_payload"))``.
Post-generation dependencies
============================
Unlike factory_boy which binds related objects using an internal container to store results of lazy evaluations,
pytest-factoryboy relies on the PyTest request.
Circular dependencies between objects can be resolved using post-generation hooks/related factories in combination with
passing the SelfAttribute, but in the case of PyTest request fixture functions have to return values in order to be cached
in the request and to become available to other fixtures.
That's why evaluation of the post-generation declaration in pytest-factoryboy is deferred until calling
the test function.
This solves circular dependency resolution for situations like:
::
o->[ A ]-->[ B ]<--[ C ]-o
| |
o----(C depends on A)----o
On the other hand, deferring the evaluation of post-generation declarations evaluation makes their result unavailable during the generation
of objects that are not in the circular dependency, but they rely on the post-generation action.
pytest-factoryboy is trying to detect cycles and resolve post-generation dependencies automatically.
.. code-block:: python
from pytest_factoryboy import register
class Foo(object):
def __init__(self, value):
self.value = value
class Bar(object):
def __init__(self, foo):
self.foo = foo
@register
class FooFactory(factory.Factory):
class Meta:
model = Foo
value = 0
@factory.post_generation
def set1(foo, create, value, **kwargs):
foo.value = 1
@register
class BarFactory(factory.Factory):
class Meta:
model = Bar
foo = factory.SubFactory(FooFactory)
@classmethod
def _create(cls, model_class, foo):
assert foo.value == 1 # Assert that set1 is evaluated before object generation
return super(BarFactory, cls)._create(model_class, foo=foo)
# Forces 'set1' to be evaluated first.
def test_depends_on_set1(bar):
"""Test that post-generation hooks are done and the value is 2."""
assert bar.foo.value == 1
Hooks
-----
pytest-factoryboy exposes several `pytest hooks <http://pytest.org/latest/plugins.html#well-specified-hooks>`_
which might be helpful for e.g. controlling database transaction, for reporting etc:
* pytest_factoryboy_done(request) - Called after all factory-based fixtures and their post-generation actions have been evaluated.
License
-------
This software is licensed under the `MIT license <http://en.wikipedia.org/wiki/MIT_License>`_.
© 2015 Oleg Pidsadnyi, Anatoly Bubenkov and others
Raw data
{
"_id": null,
"home_page": "https://pytest-factoryboy.readthedocs.io/",
"name": "pytest-factoryboy",
"maintainer": "Alessio Bogon",
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": "778703+youtux@users.noreply.github.com",
"keywords": "",
"author": "Oleg Pidsadnyi",
"author_email": "oleg.pidsadnyi@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/a6/bc/179653e8cce651575ac95377e4fdf9afd3c4821ab4bba101aae913ebcc27/pytest_factoryboy-2.7.0.tar.gz",
"platform": null,
"description": "factory_boy_ integration with the pytest_ runner\n================================================\n\n.. image:: https://img.shields.io/pypi/v/pytest-factoryboy.svg\n :target: https://pypi.python.org/pypi/pytest-factoryboy\n.. image:: https://img.shields.io/pypi/pyversions/pytest-factoryboy.svg\n :target: https://pypi.python.org/pypi/pytest-factoryboy\n.. image:: https://github.com/pytest-dev/pytest-factoryboy/actions/workflows/main.yml/badge.svg\n :target: https://github.com/pytest-dev/pytest-factoryboy/actions?query=workflow%3Amain\n.. image:: https://readthedocs.org/projects/pytest-factoryboy/badge/?version=latest\n :target: https://readthedocs.org/projects/pytest-factoryboy/?badge=latest\n :alt: Documentation Status\n\n\npytest-factoryboy makes it easy to combine ``factory`` approach to the test setup with the ``dependency`` injection,\nheart of the `pytest fixtures`_.\n\n.. _factory_boy: https://factoryboy.readthedocs.io\n.. _pytest: https://pytest.org\n.. _pytest fixtures: https://pytest.org/latest/fixture.html\n.. _overridden: https://docs.pytest.org/en/latest/how-to/fixtures.html#overriding-fixtures-on-various-levels\n\n\nInstall pytest-factoryboy\n-------------------------\n\n::\n\n pip install pytest-factoryboy\n\n\nConcept\n-------\n\nLibrary exports a function to register factories as fixtures. Fixtures are contributed\nto the same module where register function is called.\n\n\nModel Fixture\n-------------\n\nModel fixture implements an instance of a model created by the factory. Name convention is model's lowercase-underscore\nclass name.\n\n\n.. code-block:: python\n\n import factory\n from pytest_factoryboy import register\n\n @register\n class AuthorFactory(factory.Factory):\n class Meta:\n model = Author\n\n name = \"Charles Dickens\"\n\n\n def test_model_fixture(author):\n assert author.name == \"Charles Dickens\"\n\n\nAttributes are Fixtures\n-----------------------\n\nThere are fixtures created automatically for factory attributes. Attribute names are prefixed with the model fixture name and\ndouble underscore (similar to the convention used by factory_boy).\n\n\n.. code-block:: python\n\n @pytest.mark.parametrize(\"author__name\", [\"Bill Gates\"])\n def test_model_fixture(author):\n assert author.name == \"Bill Gates\"\n\n\nMultiple fixtures\n-----------------\n\nModel fixtures can be registered with specific names. For example, if you address instances of some collection\nby the name like \"first\", \"second\" or of another parent as \"other\":\n\n\n.. code-block:: python\n\n register(AuthorFactory) # author\n register(AuthorFactory, \"second_author\") # second_author\n\n\n @register # book\n @register(_name=\"second_book\") # second_book\n @register(_name=\"other_book\") # other_book, book of another author\n class BookFactory(factory.Factory):\n class Meta:\n model = Book\n\n\n @pytest.fixture\n def other_book__author(second_author):\n \"\"\"Make the relation of the `other_book.author` to `second_author`.\"\"\"\n return second_author\n\n\n def test_book_authors(book, second_book, other_book, author, second_author):\n assert book.author == second_book.author == author\n assert other_book.author == second_author\n\n\nSubFactory\n----------\n\nSub-factory attribute points to the model fixture of the sub-factory.\nAttributes of sub-factories are injected as dependencies to the model fixture and can be overridden_ via\nthe parametrization.\n\nRelated Factory\n---------------\n\nRelated factory attribute points to the model fixture of the related factory.\nAttributes of related factories are injected as dependencies to the model fixture and can be overridden_ via\nthe parametrization.\n\n\npost-generation\n---------------\n\nPost-generation attribute fixture implements only the extracted value for the post generation function.\n\nFactory Fixture\n---------------\n\n`pytest-factoryboy` also registers factory fixtures, to allow their use without importing them. The fixture name convention is to use the lowercase-underscore form of the class name.\n\n.. code-block:: python\n\n import factory\n from pytest_factoryboy import register\n\n class AuthorFactory(factory.Factory):\n class Meta:\n model = Author\n\n\n register(AuthorFactory) # => author_factory\n\n\n def test_factory_fixture(author_factory):\n author = author_factory(name=\"Charles Dickens\")\n assert author.name == \"Charles Dickens\"\n\n\nIntegration\n-----------\n\nAn example of factory_boy_ and pytest_ integration.\n\n.. code-block:: python\n\n # tests/factories.py\n\n import factory\n from app import models\n from faker import Factory as FakerFactory\n\n faker = FakerFactory.create()\n\n\n class AuthorFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = models.Author\n\n name = factory.LazyFunction(lambda: faker.name())\n\n\n class BookFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = models.Book\n\n title = factory.LazyFunction(lambda: faker.sentence(nb_words=4))\n author = factory.SubFactory(AuthorFactory)\n\n\n.. code-block:: python\n\n # tests/conftest.py\n\n from pytest_factoryboy import register\n\n from . import factories\n\n register(factories.AuthorFactory)\n register(factories.BookFactory)\n\n\n.. code-block:: python\n\n # tests/test_models.py\n\n from app.models import Book\n from .factories import BookFactory\n\n\n def test_book_factory(book_factory):\n \"\"\"Factories become fixtures automatically.\"\"\"\n assert book_factory is BookFactory\n\n\n def test_book(book):\n \"\"\"Instances become fixtures automatically.\"\"\"\n assert isinstance(book, Book)\n\n\n @pytest.mark.parametrize(\"book__title\", [\"PyTest for Dummies\"])\n @pytest.mark.parametrize(\"author__name\", [\"Bill Gates\"])\n def test_parametrized(book):\n \"\"\"You can set any factory attribute as a fixture using naming convention.\"\"\"\n assert book.title == \"PyTest for Dummies\"\n assert book.author.name == \"Bill Gates\"\n\n\nFixture partial specialization\n------------------------------\n\nThere is a possibility to pass keyword parameters in order to override factory attribute values during fixture\nregistration. This comes in handy when your test case is requesting a lot of fixture flavors. Too much for the\nregular pytest parametrization.\nIn this case, you can register fixture flavors in the local test module and specify value deviations inside ``register``\nfunction calls.\n\n\n.. code-block:: python\n\n register(AuthorFactory, \"male_author\", gender=\"M\", name=\"John Doe\")\n register(AuthorFactory, \"female_author\", gender=\"F\")\n\n\n @pytest.fixture\n def female_author__name():\n \"\"\"Override female author name as a separate fixture.\"\"\"\n return \"Jane Doe\"\n\n\n @pytest.mark.parametrize(\"male_author__age\", [42]) # Override even more\n def test_partial(male_author, female_author):\n \"\"\"Test fixture partial specialization.\"\"\"\n assert male_author.gender == \"M\"\n assert male_author.name == \"John Doe\"\n assert male_author.age == 42\n\n assert female_author.gender == \"F\"\n assert female_author.name == \"Jane Doe\"\n\n\nFixture attributes\n------------------\n\nSometimes it is necessary to pass an instance of another fixture as an attribute value to the factory.\nIt is possible to override the generated attribute fixture where desired values can be requested as\nfixture dependencies. There is also a lazy wrapper for the fixture that can be used in the parametrization\nwithout defining fixtures in a module.\n\n\nLazyFixture constructor accepts either existing fixture name or callable with dependencies:\n\n.. code-block:: python\n\n import pytest\n from pytest_factoryboy import register, LazyFixture\n\n\n @pytest.mark.parametrize(\"book__author\", [LazyFixture(\"another_author\")])\n def test_lazy_fixture_name(book, another_author):\n \"\"\"Test that book author is replaced with another author by fixture name.\"\"\"\n assert book.author == another_author\n\n\n @pytest.mark.parametrize(\"book__author\", [LazyFixture(lambda another_author: another_author)])\n def test_lazy_fixture_callable(book, another_author):\n \"\"\"Test that book author is replaced with another author by callable.\"\"\"\n assert book.author == another_author\n\n\n # Can also be used in the partial specialization during the registration.\n register(BookFactory, \"another_book\", author=LazyFixture(\"another_author\"))\n\n\nGeneric container classes as models\n-----------------------------------\nIt's often useful to create factories for ``dict`` or other common generic container classes.\nIn that case, you should wrap the container class around ``named_model(...)``, so that pytest-factoryboy can correctly determine the model name when using it in a SubFactory or RelatedFactory.\n\nPytest-factoryboy will otherwise raise a warning.\n\nFor example:\n\n.. code-block:: python\n\n import factory\n from pytest_factoryboy import named_model, register\n\n @register\n class JSONPayload(factory.Factory):\n class Meta:\n model = named_model(\"JSONPayload\", dict)\n\n name = \"foo\"\n\n\n def test_foo(json_payload):\n assert json_payload.name == \"foo\"\n\nAs a bonus, factory is automatically registering the ``json_payload`` fixture (rather than ``dict``), so there is no need to override ``@register(_name=\"json_payload\"))``.\n\nPost-generation dependencies\n============================\n\nUnlike factory_boy which binds related objects using an internal container to store results of lazy evaluations,\npytest-factoryboy relies on the PyTest request.\n\nCircular dependencies between objects can be resolved using post-generation hooks/related factories in combination with\npassing the SelfAttribute, but in the case of PyTest request fixture functions have to return values in order to be cached\nin the request and to become available to other fixtures.\n\nThat's why evaluation of the post-generation declaration in pytest-factoryboy is deferred until calling\nthe test function.\nThis solves circular dependency resolution for situations like:\n\n::\n\n o->[ A ]-->[ B ]<--[ C ]-o\n | |\n o----(C depends on A)----o\n\n\nOn the other hand, deferring the evaluation of post-generation declarations evaluation makes their result unavailable during the generation\nof objects that are not in the circular dependency, but they rely on the post-generation action.\n\npytest-factoryboy is trying to detect cycles and resolve post-generation dependencies automatically.\n\n\n.. code-block:: python\n\n from pytest_factoryboy import register\n\n\n class Foo(object):\n def __init__(self, value):\n self.value = value\n\n\n class Bar(object):\n def __init__(self, foo):\n self.foo = foo\n\n\n @register\n class FooFactory(factory.Factory):\n class Meta:\n model = Foo\n\n value = 0\n\n @factory.post_generation\n def set1(foo, create, value, **kwargs):\n foo.value = 1\n\n @register\n class BarFactory(factory.Factory):\n class Meta:\n model = Bar\n\n foo = factory.SubFactory(FooFactory)\n\n @classmethod\n def _create(cls, model_class, foo):\n assert foo.value == 1 # Assert that set1 is evaluated before object generation\n return super(BarFactory, cls)._create(model_class, foo=foo)\n\n\n # Forces 'set1' to be evaluated first.\n def test_depends_on_set1(bar):\n \"\"\"Test that post-generation hooks are done and the value is 2.\"\"\"\n assert bar.foo.value == 1\n\n\nHooks\n-----\n\npytest-factoryboy exposes several `pytest hooks <http://pytest.org/latest/plugins.html#well-specified-hooks>`_\nwhich might be helpful for e.g. controlling database transaction, for reporting etc:\n\n* pytest_factoryboy_done(request) - Called after all factory-based fixtures and their post-generation actions have been evaluated.\n\n\nLicense\n-------\n\nThis software is licensed under the `MIT license <http://en.wikipedia.org/wiki/MIT_License>`_.\n\n\u00a9 2015 Oleg Pidsadnyi, Anatoly Bubenkov and others\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Factory Boy support for pytest.",
"version": "2.7.0",
"project_urls": {
"Documentation": "https://pytest-factoryboy.readthedocs.io/",
"Homepage": "https://pytest-factoryboy.readthedocs.io/",
"Repository": "https://github.com/pytest-dev/pytest-factoryboy"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "c756d3ef25286dc8df9d1da0b325ee4b1b1ffd9736e44f9b30cfbe464e9f4f14",
"md5": "5e95a27ccfdea9514b23fbbdaac19fb8",
"sha256": "bf3222db22d954fbf46f4bff902a0a8d82f3fc3594a47c04bbdc0546ff4c59a6"
},
"downloads": -1,
"filename": "pytest_factoryboy-2.7.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "5e95a27ccfdea9514b23fbbdaac19fb8",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 16268,
"upload_time": "2024-03-05T07:32:09",
"upload_time_iso_8601": "2024-03-05T07:32:09.981140Z",
"url": "https://files.pythonhosted.org/packages/c7/56/d3ef25286dc8df9d1da0b325ee4b1b1ffd9736e44f9b30cfbe464e9f4f14/pytest_factoryboy-2.7.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "a6bc179653e8cce651575ac95377e4fdf9afd3c4821ab4bba101aae913ebcc27",
"md5": "b0a3278f068b0830698de0955a039eb0",
"sha256": "67fc54ec8669a3feb8ac60094dd57cd71eb0b20b2c319d2957873674c776a77b"
},
"downloads": -1,
"filename": "pytest_factoryboy-2.7.0.tar.gz",
"has_sig": false,
"md5_digest": "b0a3278f068b0830698de0955a039eb0",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 17398,
"upload_time": "2024-03-05T07:32:12",
"upload_time_iso_8601": "2024-03-05T07:32:12.675088Z",
"url": "https://files.pythonhosted.org/packages/a6/bc/179653e8cce651575ac95377e4fdf9afd3c4821ab4bba101aae913ebcc27/pytest_factoryboy-2.7.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-03-05 07:32:12",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "pytest-dev",
"github_project": "pytest-factoryboy",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"tox": true,
"lcname": "pytest-factoryboy"
}