@@ -475,6 +475,59 @@ Running it::
475
475
voila! The ``smtp `` fixture function picked up our mail server name
476
476
from the module namespace.
477
477
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
+
478
531
.. _`fixture-parametrize` :
479
532
480
533
Parametrizing fixtures
0 commit comments