From 08de3dad3343bde7c855914ea0ca45b60b091b92 Mon Sep 17 00:00:00 2001 From: Niklas Meinzer Date: Thu, 31 May 2018 11:14:53 +0200 Subject: [PATCH] Add factory fixture example to documentation. Close https://github.com/pytest-dev/pytest/issues/3461 --- changelog/3461.doc.rst | 1 + doc/en/fixture.rst | 53 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 changelog/3461.doc.rst diff --git a/changelog/3461.doc.rst b/changelog/3461.doc.rst new file mode 100644 index 000000000..930b6565f --- /dev/null +++ b/changelog/3461.doc.rst @@ -0,0 +1 @@ +Added a section on how to use fixtures as factories to the fixture documentation. diff --git a/doc/en/fixture.rst b/doc/en/fixture.rst index f2c5d2e96..938f120fe 100644 --- a/doc/en/fixture.rst +++ b/doc/en/fixture.rst @@ -465,6 +465,59 @@ Running it:: voila! The ``smtp`` fixture function picked up our mail server name 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`: Parametrizing fixtures