python-pytest學習(六)-參數化


一、前言

  pytest.mark.parameterize裝飾器可以實現測試用例參數化。

二、parametrizing

  1.這里是一個實現檢查一定的輸入和期望輸出測試功能的典型例子

import pytest

@pytest.mark.parametrize("test_input,expected",
                         [("3+5",8),
                          ("2+4",6),
                          ("6*9",42),
                          ])
def test_eval(test_input,expected):
    assert eval(test_input) == expected

if __name__=="__main__":
    pytest.main(["-s","test_param1.py"])

運行結果:

 

 

  在這個例子中設計的,只有一條輸入/輸出值的簡單測試功能。和往常一樣。

  函數的參數,你可以在運行結果看到在輸入和輸出值。

  2.它也可以標記單個測試實例再參數化,例如使用內置的mark.xfail

import pytest

@pytest.mark.parametrize("test_input,expected",
                         [("3+5",8),
                          ("2+4",6),
                          pytest.param("6*9",42,marks=pytest.mark.xfail),
                          ])
def test_eval(test_input,expected):
    print("---------------開始用例---------------")
    assert eval(test_input) == expected

if __name__=="__main__":
    pytest.main(["-s","test_param1.py"])

運行結果:

 

標記為失敗的用例就不運行了,直接跳過顯示xfailed

  3.參數組合

(1)若要獲得多個參數化參數的所有組合,可以堆疊參數化裝飾器

import pytest

@pytest.mark.parametrize("x",[0,1])
@pytest.mark.parametrize("y",[2,3])

def test_foo(x,y):
    print("測試數據組合:x->%s,y->%s" %(x,y))

if __name__=="__main__":
    pytest.mark(["-s","test_param2.py"])

運行結果:

 

 這將運行測試,參數設置為x=0/y=2,x=1/y=2,x=0/y=3,x=1/y=3組合參數。

 

參考文章:https://www.jianshu.com/p/983412a7c2ae


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM