Add factory fixture example to documentation.

Close https://github.com/pytest-dev/pytest/issues/3461
This commit is contained in:
Niklas Meinzer 2018-05-31 11:14:53 +02:00
parent 5748c5ce8f
commit 08de3dad33
2 changed files with 54 additions and 0 deletions

1
changelog/3461.doc.rst Normal file
View File

@ -0,0 +1 @@
Added a section on how to use fixtures as factories to the fixture documentation.

View File

@ -465,6 +465,59 @@ Running it::
voila! The ``smtp`` fixture function picked up our mail server name voila! The ``smtp`` fixture function picked up our mail server name
from the module namespace. from the module namespace.
.. _`fixture-factory`:
Factories as fixtures
-------------------------------------------------------------
The "factory as fixture" pattern can help in situations where the result
of a fixture is needed multiple times in a single test. Instead of returning
data directly, the fixture instead returns a function which generates the data.
This function can then be called multiple times in the test.
Factories can have have parameters as needed::
@pytest.fixture
def make_customer_record():
def _make_customer_record(name):
return {
"name": name,
"orders": []
}
return _make_customer_record
def test_customer_records(make_customer_record):
customer_1 = make_customer_record("Lisa")
customer_2 = make_customer_record("Mike")
customer_3 = make_customer_record("Meredith")
If the data created by the factory requires managing, the fixture can take care of that::
@pytest.fixture
def make_customer_record():
created_records = []
def _make_customer_record(name):
record = models.Customer(name=name, orders=[])
created_records.append(record)
return record
yield _make_customer_record
for record in created_records:
record.destroy()
def test_customer_records(make_customer_record):
customer_1 = make_customer_record("Lisa")
customer_2 = make_customer_record("Mike")
customer_3 = make_customer_record("Meredith")
.. _`fixture-parametrize`: .. _`fixture-parametrize`:
Parametrizing fixtures Parametrizing fixtures