一、Pytestparametrize簡介
在編寫Python測試時,經常會遇到需要編寫多個測試用例的情況,這時我們可以使用pytestparametrize庫來簡化代碼,提高測試效率。pytestparametrize是Python中的一個參數化庫,可以通過參數化實現代碼重用,減少代碼量。該庫可以以參數化方式運行測試多次,只需要在測試方法上添加裝飾器「@pytest.mark.parametrize」,並提供測試數據即可,下面我們來看一下代碼示例:
import pytest @pytest.mark.parametrize("test_input,expected_output",[ (3,9), (2,4), (5,25), ]) def test_calculate_square(test_input, expected_output): assert test_input*test_input == expected_output
在測試用例中添加了「@pytest.mark.parametrize」裝飾器,後面的參數用列表的形式提供,在上面的代碼中,我們測試了三組數據,分別是(3,9)、(2,4)和(5,25),每組數據都是一個元組,第一個元素表示傳入測試方法的參數,第二個元素表示期望結果。pytestparametrize會將這幾組數據分別傳入測試方法test_calculate_square中,並驗證它們是否符合期望結果,從而完成測試。
二、使用pytestparametrize進行測試數據組合
在Python中,pytestparametrize可以方便地進行測試數據組合,即將多個測試數據進行組合,生成新的測試數據來測試代碼的各種邏輯。下面我們來看一個代碼示例:
import pytest @pytest.mark.parametrize("test_input1,test_input2,expected_output",[ (1,2,3), (2,5,7), (7,9,16), (9,10,19), (15,20,35), ]) def test_calculate_addition(test_input1,test_input2, expected_output): assert test_input1+test_input2 == expected_output
在測試用例「test_calculate_addition」中,我們利用pytestparametrize實現了多個測試數據的組合,每組數據都需要輸入兩個參數test_input1和test_input2,並提供期望的輸出結果expected_output。測試數據的組合,可以通過多個元素分別提供,以逗號區分,pytestparametrize會根據提供的測試數據集自動生成數據組合用於測試。在上面的代碼中,我們測試了5組數據,其中第一組數據(1,2,3)表示test_input1=1,test_input2=2,expected_output=3,即測試1+2是否等於3,依次類推,從而完成測試。
三、使用pytestparametrize進行複雜邏輯測試
在實際工作中,我們經常需要測試一些比較複雜的邏輯,這時我們可以利用pytestparametrize進行參數化測試,從而對複雜的代碼邏輯進行快速、準確的測試。下面我們來看一個實際代碼的例子:
import pytest def get_total_amount(discount_code, product_price, member_level): if discount_code=="ABC123": if member_level=="VIP": total_amount = product_price*0.7 elif member_level=="SVIP": total_amount = product_price*0.6 else: total_amount = product_price*0.8 elif discount_code=="XYZ456": if member_level == "VIP": total_amount = product_price * 0.9 elif member_level == "SVIP": total_amount = product_price * 0.8 else: total_amount = product_price * 0.95 else: total_amount = product_price return total_amount @pytest.mark.parametrize("discount_code, product_price, member_level, expected_total_amount",[ ("ABC123", 100, "VIP", 70), ("XYZ456", 100, "SVIP", 80), ("ABC123", 100, "NORMAL", 80), ("XYZ456", 100, "NORMAL", 95), ]) def test_total_amount(discount_code, product_price, member_level, expected_total_amount): assert get_total_amount(discount_code, product_price, member_level) == expected_total_amount
在上面的代碼中,我們實現了一個get_total_amount函數,該函數用於根據傳入的參數計算商品的總價並返回結果。我們通過pytestparametrize實現了多組參數化,其中包括折扣碼(discount_code)、商品價格(product_price)、會員等級(member_level)以及期望的總價(expected_total_amount)。我們測試了4組數據,pytestparametrize會將這些數據逐一傳入test_total_amount方法中,並驗證get_total_amount函數的輸出是否等於期望的total_amount,以驗證該代碼是否正確。通過利用pytestparametrize進行參數化測試,我們可以快速、準確地測試各種輸入情況下的代碼邏輯,提高測試效率。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/287073.html