pytest文件9 引數化parametrize

2022-06-14 05:42:11 字數 2780 閱讀 1061

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

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

# content of test_expectation.py

# coding:utf-8

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_canshu1.py"])

執行結果

******************************==== failures ***********************************

_____________________________ test_eval[6 * 9-42] _____________________________

test_input = '6 * 9', expected = 42

@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

e assertionerror: assert 54 == 42

e + where 54 = eval('6 * 9')

test_canshu1.py:11: assertionerror

********************= 1 failed, 2 passed in 1.98 seconds ********************==

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

函式的引數,你可以在執行結果看到在輸入和輸出值

2.它也可以標記單個測試例項在引數化,例如使用內建的mark.xfail

# content of test_expectation.py

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_canshu1.py"])

執行結果:

test_canshu1.py -------開始用例------

.-------開始用例------

.-------開始用例------

x********************= 2 passed, 1 xfailed in 1.84 seconds ********************=

標記為失敗的用例,預期結果是失敗,實際執行也是失敗,顯示xfailed

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.main(["-s", "test_canshu1.py"])

執行結果

test_canshu1.py 測試資料組合:x->0, y->2

.測試資料組合:x->1, y->2

.測試資料組合:x->0, y->3

.測試資料組合:x->1, y->3

.*************************= 4 passed in 1.75 seconds *************************==

這將執行測試,引數設定為x=0/y=2,x=1/y=2,x=0/y=3,x=1/y=3組合引數。

---------------------------------pytest結合selenium自動化完整版-------------------------

全書購買位址

pytest文件9 引數化parametrize

pytest.mark.parametrize裝飾器可以實現測試用例引數化。1.這裡是乙個實現檢查一定的輸入和期望輸出測試功能的典型例子 content of test expectation.py coding utf 8 import pytest pytest.mark.parametrize...

pytest文件9 引數化parametrize

pytest.mark.parametrize裝飾器可以實現測試用例引數化。1.這裡是乙個實現檢查一定的輸入和期望輸出測試功能的典型例子 content of test expectation.py coding utf 8 import pytest pytest.mark.parametrize...

Pytest框架引數化

本文主要介紹第二種引數化方式 pytest.mark.parametrize 引數名稱 lists or tuple or set 傳入單個引數。引數名稱僅作為引數名稱,便於記憶,可隨意起。引數不管是lists或是tuple型別都可以執行成功,另外集合型別set 順便試了一下也是成功的不過沒有特殊研...