欢迎访问宙启技术站
智能推送

使用parameterized的expand()函数来生成多样化的测试输入

发布时间:2024-01-11 15:41:31

Parameterized expansion in testing allows for the generation of diverse test inputs by defining a list of parameters and their potential values. This approach enables the creation of a wide range of test cases without having to manually define each one. Let's explore how the expand() function can be used to generate diversified test inputs with an example.

import unittest
from parameterized import parameterized, parameterized_class

class MyTest(unittest.TestCase):
    
    # Example 1: Parameterized test with multiple input values
    @parameterized.expand([
        (1, 2),
        (3, 4),
        (5, 6),
    ])
    def test_addition(self, num1, num2):
        result = num1 + num2
        self.assertEqual(result, num1 + num2)
    
    # Example 2: Parameterized test with dictionary input
    @parameterized.expand([
        {"name": "John", "age": 25},
        {"name": "Jane", "age": 30},
        {"name": "Mark", "age": 40},
    ])
    def test_person(self, name, age):
        self.assertIsInstance(name, str)
        self.assertIsInstance(age, int)
    
    # Example 3: Parameterized test with dynamic generation of inputs
    @parameterized.expand([
        (i, i+1) for i in range(5)
    ])
    def test_sequence(self, num1, num2):
        self.assertTrue(num2 == num1 + 1)
        
if __name__ == '__main__':
    unittest.main()

In the example above, we have a MyTest class that contains multiple test cases using the parameterized.expand() function from the parameterized package. Let's break down each example:

1. **Example 1**: This test case demonstrates parameterized testing with multiple input values. Here, the test_addition method receives two parameters num1 and num2 from the input values defined inside the @parameterized.expand([]) decorator. The test compares the sum of num1 and num2 with the expected result.

2. **Example 2**: This test case showcases parameterized testing with dictionary input. The test_person method receives name and age parameters from the dictionaries defined in @parameterized.expand([]). It then asserts that the name is a string and the age is an integer.

3. **Example 3**: This test case demonstrates dynamic generation of inputs using a list comprehension inside the @parameterized.expand([]) decorator. It generates multiple test cases by iterating over a range of values and assigning them to num1 and num2 parameters of the test_sequence method. The test then verifies that num2 is always equal to num1 + 1.

By using parameterized.expand() function, we can easily define a list of test inputs and have them automatically expanded to generate a variety of test cases. This approach helps increase the test coverage, detects edge cases, and ensures the reliability and correctness of the code under test.