parameterized參數化測試

1、官網:https://pypi.org/project/parameterized/

2、parameterized:可以使用任何Python測試框架進行參數化測試。比如nose的參數化測試,py.test的參數化測試,unittest的參數化測試。

3、安裝parameterized:pip install parameterized

4、安裝nose:pip install nose

5、安裝pytest:pip install pytest

6、官網例子:

導入相應的包:

from nose.tools import assert_equal

from parameterized import parameterized, parameterized_class

import unittest

import math

6.1、@parameterized 裝飾符接受一個由tuples或param(...)組成的列表等:

@parameterized([

    (2, 2, 4),

    (2, 3, 8),

    (1, 9, 1),

    (0, 9, 0),

])

#參數化3個參數base,exponent,expected,4組參數,傳入具體數值。

def test_pow(base, exponent, expected):#測試冪函數,傳入3個參數值

   assert_equal(math.pow(base, exponent), expected)

6.2、@parameterized.expand 裝飾符接受一個由tuples或param(...)組成的列表等,unittest僅支持這種@parameterized.expand 的用法,@parameterized.expand 可以用來在無法使用測試生成器的情況下生成測試方法(例如,當測試類是unittest.TestCase的子類時:

class TestMathUnitTest(unittest.TestCase):#測試math的測試用例

   @parameterized.expand([

       ("negative", -1.5, -2.0),

       ("integer", 1, 1.0),

       ("large fraction", 1.6, 1),

   ])#參數化3個參數,name, input, expected,3組參數。傳入測試方法名字和具體數值

   def test_floor(self, name, input, expected):##測試floor函數,傳入3個參數值

       assert_equal(math.floor(input), expected)

   '''

   floor函數:Return the floor of x as an Integral.This is the largest integer <= x.

   '''

6.3、加法和乘法測試:

@parameterized_class(('a', 'b', 'expected_sum', 'expected_product'), [

   (1, 2, 3, 2),

   (5, 5, 10, 25),

])#參數化4個參數,'a', 'b', 'expected_sum', 'expected_product',2組參數。傳入變量和具體數值

class TestMathClass(unittest.TestCase):

   def test_add(self):#加法測試

      assert_equal(self.a + self.b, self.expected_sum)

   def test_multiply(self):#乘法測試

      assert_equal(self.a * self.b, self.expected_product)

6.4、減法測試:

@parameterized_class([

   { "a": 3, "expected": 2 },#3-1=2

   { "b": 5, "expected": -4 },#1-5=-4

])#參數化2個參數,2組參數。傳入變量和具體數值

class TestMathClassDict(unittest.TestCase):

   a = 1

   b = 1

   def test_subtract(self):#減法測試

      assert_equal(self.a - self.b, self.expected)

7、參數化參數

7.1、nose的參數化測試:nosetests -v test_math.py

7.2、py.test的參數化測試:py.test -v test_math.py()

7.3、unittest的參數化測試:python -m unittest -v test_math.py

備註: 因爲unittest不支持測試裝飾符,所以只有用@parameterized.expand創建的測試纔會執行。

8、兼容性:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章