回答重點
在 Pytest 中,我們可以通過使用共享夾具(fixtures)來調用和復用其他用例返回的接口參數。在 Pytest 中,fixtures 提供了一種靈活且有組織的方式來共享測試數據或對象。
具體步驟如下:
1)首先,在 conftest.py
文件中定義一個 fixture 函數,該函數會返回你希望共享的參數。這個 fixture 可以通過標識符傳遞給任何測試函數。
2)在需要復用該參數的測試函數中,通過傳遞相應的參數名來引用該 fixture。
下面是一個示例代碼,可以幫助你理解:
# conftest.py
import pytest@pytest.fixture
def api_response():# 假設這是你從接口獲取的參數response = {"token": "abc123","user_id": 1}return response# test_example.py
def test_first_example(api_response):assert api_response["token"] == "abc123"def test_second_example(api_response):assert api_response["user_id"] == 1# 你可以繼續使用 `api_response` 進行其他測試或接口調用
在上述示例中, api_response
是一個 fixture,它返回一個包含 token
和 user_id
的字典。任何需要這些數據的測試函數,只需聲明它們的參數即可自動獲取此數據,從而實現復用。
擴展知識
1) Fixture 的作用域
Fixture 可以設置不同的作用域級別(如 function, class, module, session),這決定了 fixture 的生命周期。作用域越大,fixture 的創建和銷毀次數越少。
@pytest.fixture(scope="module")
def api_response():# 模塊級別的 fixture,在整個模塊中共享...
2) Fixture 的依賴
Fixture 之間也可以相互調用,從而構建更加復雜的數據依賴。
@pytest.fixture
def auth_token():return "secret-token"@pytest.fixture
def api_response(auth_token):return {"token": auth_token,"user_id": 1}
3) 動態生成數據
有時我們需要為每個測試生成不同的數據,可以用 yield
關鍵字或者動態計算的方法來實現。
@pytest.fixture
def dynamic_response():token = generate_token()return {"token": token,"user_id": random_user_id()}