Skip to content

Commit cc793a8

Browse files
authored
Merge pull request #3522 from NiklasMM/fix/3461_factory-fixture-doc
Add factory fixture example to documentation.
2 parents 7f5cb46 + 08de3da commit cc793a8

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
@@ -475,6 +475,59 @@ Running it::
475475
voila! The ``smtp`` fixture function picked up our mail server name
476476
from the module namespace.
477477

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

480533
Parametrizing fixtures

0 commit comments

Comments
 (0)