Skip to content

Commit 08de3da

Browse files
committed
Add factory fixture example to documentation.
Close #3461
1 parent 5748c5c commit 08de3da

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

changelog/3461.doc.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Added a section on how to use fixtures as factories to the fixture documentation.

doc/en/fixture.rst

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -465,6 +465,59 @@ Running it::
465465
voila! The ``smtp`` fixture function picked up our mail server name
466466
from the module namespace.
467467

468+
.. _`fixture-factory`:
469+
470+
Factories as fixtures
471+
-------------------------------------------------------------
472+
473+
The "factory as fixture" pattern can help in situations where the result
474+
of a fixture is needed multiple times in a single test. Instead of returning
475+
data directly, the fixture instead returns a function which generates the data.
476+
This function can then be called multiple times in the test.
477+
478+
Factories can have have parameters as needed::
479+
480+
@pytest.fixture
481+
def make_customer_record():
482+
483+
def _make_customer_record(name):
484+
return {
485+
"name": name,
486+
"orders": []
487+
}
488+
489+
return _make_customer_record
490+
491+
492+
def test_customer_records(make_customer_record):
493+
customer_1 = make_customer_record("Lisa")
494+
customer_2 = make_customer_record("Mike")
495+
customer_3 = make_customer_record("Meredith")
496+
497+
If the data created by the factory requires managing, the fixture can take care of that::
498+
499+
@pytest.fixture
500+
def make_customer_record():
501+
502+
created_records = []
503+
504+
def _make_customer_record(name):
505+
record = models.Customer(name=name, orders=[])
506+
created_records.append(record)
507+
return record
508+
509+
yield _make_customer_record
510+
511+
for record in created_records:
512+
record.destroy()
513+
514+
515+
def test_customer_records(make_customer_record):
516+
customer_1 = make_customer_record("Lisa")
517+
customer_2 = make_customer_record("Mike")
518+
customer_3 = make_customer_record("Meredith")
519+
520+
468521
.. _`fixture-parametrize`:
469522

470523
Parametrizing fixtures

0 commit comments

Comments
 (0)