Skip to content
Permalink
Browse files

Add factory fixture example to documentation.

  • Loading branch information...
NiklasMM committed May 31, 2018
1 parent 5748c5c commit 7279a5a5fc8ae697c0a1f636779eafadd6237113
Showing with 53 additions and 0 deletions.
  1. +53 −0 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

0 comments on commit 7279a5a

Please sign in to comment.
You can’t perform that action at this time.