pytest fixture-Factories as fixtures

2022-03-18 14:16 更新

??factory as fixture??模式可以幫助解決在一次測試中需要多次使用??fixture??的情況。該??fixture??不是直接返回數(shù)據(jù),而是返回一個生成數(shù)據(jù)的函數(shù)。這個函數(shù)可以在測試中被多次調用。

??Factories??可以根據(jù)需要設置參數(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")


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號