day94 pytest的fixture詳解
學習日期:20241210
學習目標:pytest基礎用法 -- pytest的fixture詳解
學習筆記:
fixture的介紹
fixture是 pytest 用于將測試前后進行預備、清理工作的代碼處理機制。
fixture相對于setup和teardown來說有以下幾點優勢:
- fixure命名更加靈活,局限性比較小
- conftest.py 配置里面可以實現數據共享,不需要import就能自動找到一些配置
fixture夾具
@pytest.fixture,scope作用域的意思
- (scop="function") 每一個函數或方法都會調用,默認就是function
- 只有調用了func函數的才會運行func
import pytest
import requests#默認scope是function
@pytest.fixture()
def func():print("我是前置步驟")def test_getmobile(func):print("測試get請求")params = {'key1': 'value1', 'key2': 'value2'}r=requests.get('https://httpbin.org/get',params=params)print(r.status_code)assert r.status_code == 200res = r.json()assert res['url'] == 'https://httpbin.org/get?key1=value1&key2=value2'assert res['origin'] == '163.125.202.248'assert res['args']['key1'] == 'value1'assert res['args']['key2'] == 'value2'def test_postmobile():print("測試post請求")params = {'key': 'value'}r = requests.post('https://httpbin.org/post', data=params)print(r.status_code)assert r.status_code == 200print(r.json())res=r.json()assert res['args'] == {}assert res['data'] == ''assert res['form']['key'] == 'value'if __name__ == '__main__':pytest.main()
總結
- fixture是 pytest 用于將測試前后進行預備、清理工作的代碼處理機制
- scope作用域(scop="function") 每一個函數或方法都會調用,默認就是function