pytest fixture-Factories as fixtures
factory as fixture模式可以帮助解决在一次测试中需要多次使用fixture的情况。该fixture不是直接返回数据,而是返回一个生成数据的函数。这个函数可以在测试中被多次调用。
Factories可以根据需要设置参数:
@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创建的数据需要管理,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")