pytest fixture-Factories as fixtures
2022-03-18 14:16 更新
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")
以上内容是否对您有帮助:
更多建议: