@@ -465,6 +465,59 @@ Running it::
465
465
voila! The ``smtp `` fixture function picked up our mail server name
466
466
from the module namespace.
467
467
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
+
468
521
.. _`fixture-parametrize` :
469
522
470
523
Parametrizing fixtures
0 commit comments