前言
在一個測試用例中需要多次調用同一個fixture的時候,工廠化的 fixture 的模式對於一個 fixture 在單一的測試中需要被多次調用非常有用。
之前寫fixture是直接return一個數據,在測試用例中可以直接使用,現在我們需要返回一個生成數據的函數,這樣就能在用例中多次調用了。
Factories as fixtures
“Factories as fixtures”模式可以幫助在一次測試中多次需要一個fixture的結果的情況下。
fixture不是直接返回數據,而是返回一個生成數據的函數。然后可以在測試中多次調用此函數。
使用示例
import pytest
@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")
如果工廠創建的數據需要管理,那么fixture可以處理:
import pytest
@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")
場景案例
有個場景案例:當用戶第一次注冊的時候,可以注冊成功,第二次注冊的時候,提示用戶已被注冊了
import pytest
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
@pytest.fixture()
def register():
def _register(user):
# 調用注冊接口,返回結果
print("注冊用戶:%s" % user)
result = {"code": 0,
"message": "success"}
return result
return _register
def test_case_1(register):
'''測試重復注冊接口案例'''
# 第一次調用注冊
result1 = register("yoyo")
assert result1["message"] == "success"
# 第二次調用
result2 = register("yoyo")
# 真實場景可以斷言 已被注冊了
這種場景把注冊寫到fixture的話,在測試用例里面就需要調用兩次