??factory as fixture
??模式可以幫助解決在一次測(cè)試中需要多次使用??fixture
??的情況。該??fixture
??不是直接返回?cái)?shù)據(jù),而是返回一個(gè)生成數(shù)據(jù)的函數(shù)。這個(gè)函數(shù)可以在測(cè)試中被多次調(diào)用。
??Factories
??可以根據(jù)需要設(shè)置參數(shù):
@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")
如果??factory
??創(chuàng)建的數(shù)據(jù)需要管理,??fixture
??可以處理:
@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")
更多建議: