【python學(xué)習(xí)】13.pytest框架演練_2

pytest fixture

[pytest fixture 官網(wǎng)]https://docs.pytest.org/en/stable/fixture.html#fixture)
Fixture 的作用

  • 定義傳入測(cè)試中的數(shù)據(jù)集
  • 配置測(cè)試前系統(tǒng)的初始狀態(tài)
  • 為批量測(cè)試提供數(shù)據(jù)源等

Fixture 是pytest 用于將測(cè)試前后進(jìn)行預(yù)備,清理工作的代碼分離出核心測(cè)試邏輯的一種機(jī)制,使用方法

import pytest

@pytest.fixture()
def test_login():
    print('登錄')
    username = [1,2,3]
    return username
    # 調(diào)用fixture裝飾的方法,傳入方法名即可
def test_search(test_login):
    print('搜索')
  # 獲取返回的參數(shù)
    print(test_login[1])
  • fixture作用域
    # fixture 作用域,module模塊,class類
@pytest.fixture(scope='module')

# yield 關(guān)鍵字,前面相當(dāng)于 setup,后面的相當(dāng)于teardown
@pytest.fixture()
def test_c():
    print('fangfac')
    yield 'fanhuihoumian d jieguo'# 返回后面的結(jié)果,相當(dāng)于return
    print('duankai')# 相當(dāng)于teardown操作

def test_d(test_c):
    print('方法d')
    print(f'testC的返回值{test_c}')

把所有 fixtrure 方法寫在 conftest文件中,無(wú)需import 就可以使用

  • conftest 名字不可更改,會(huì)從當(dāng)前目錄到根目錄向上找,不會(huì)在兄弟節(jié)點(diǎn)中找
  • fixture參數(shù)化
    @ pytest.fixture(params=[[0.1,0, 0.1],[1,1,2],[2,2,4]])
    def get_div_datas(self,request):
        return request.param
    def test_add_fixtrue(self,get_div_datas):
        print(f'a={get_div_datas[0]};b={get_div_datas[1]};excpet={get_div_datas[2]}')
        assert get_div_datas[2] == self.calc.add(get_div_datas[0], get_div_datas[1])

#pytest 插件
pip install pytest-ordering  控制用例的執(zhí)行順序
pip install pytest-dependency   控制用例的依賴關(guān)系
pip install pytest-xdist    分布式并發(fā)執(zhí)行測(cè)試用例
pip install pytest-rerunfailures   失敗重跑
pip install pytest-assume              多重較驗(yàn)
pip install pytest-random-order  用例隨機(jī)執(zhí)行
pip install  pytest-html                    測(cè)試報(bào)告 
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容