python数据驱动_ddt入门

https://blog.csdn.net/u013440574/article/details/81903666

官网文档:https://ddt.readthedocs.io/en/latest/

DDT (Data-Driven Tests) allows you to multiply one test case by running it with different test data, and make it appear as multiple test cases.一个测试用例可以用不同的测试数据执行多次。

DDT consists of a class decorator ddt (for your TestCase subclass) and two method decorators (for your tests that want to be multiplied):

  • data: contains as many arguments as values you want to feed to the test.
  • file_data: will load test data from a JSON or YAML file.

有一个类装饰器 ddt,两个方法装饰器 data, file_data 支持jason和yaml文件

 加了unpack装饰器是把元祖,列表,字典拆开传给测试案例

通常情况下,data中的数据按照一个参数传递给测试用例,如果data中含有:  元组,列表,字典等数据,默认是pack(包裹一起的),即一个列表作为一个变量  传给函数里的变量。如果把列表的数据进行分解,必须加上@unpack。

@data([a,b],[c,d]) 
无@unpack,那么[a,b]一个列表,作为一个参数传给测试用例 
有@unpack,那么[a,b]被分解开,作为两个参数a,b 分别传给测试用例

import unittest
from ddt import ddt,data,unpack

@ddt
class MyTesting(unittest.TestCase):
    def setUp(self):
        pass
    @data([1,2,3])
    def test_1(self,value):
        print('test_1 value is ',value)
    '''
        打印的值是[1,2,3]
    '''

    @data([1,2,3])
    @unpack
    def test_2(self,a,b,c):
        print('unpack test ',a,b,c)
    '''
        打印值为1,2,3
    '''
    def tearDown(self):
        pass

if __name__ == '__main__':
    unittest.main(verbosity=2)

官方举例代码

import unittest
from ddt import ddt, data, file_data, unpack
from test.mycode import larger_than_two, has_three_elements, is_a_greeting

try:
    import yaml
except ImportError:  # pragma: no cover
    have_yaml_support = False
else:
    have_yaml_support = True
    del yaml

# A good-looking decorator
needs_yaml = unittest.skipUnless(
    have_yaml_support, "Need YAML to run this test"
)


class Mylist(list):
    pass


def annotated(a, b):
    r = Mylist([a, b])
    setattr(r, "__name__", "test_%d_greater_than_%d" % (a, b))
    return r


def annotated2(listIn, name, docstring):
    r = Mylist(listIn)
    setattr(r, "__name__", name)
    setattr(r, "__doc__", docstring)
    return r


@ddt
class FooTestCase(unittest.TestCase):
    def test_undecorated(self):
        self.assertTrue(larger_than_two(24))

    @data(3, 4, 12, 23)
    def test_larger_than_two(self, value):
        self.assertTrue(larger_than_two(value))

    @data(1, -3, 2, 0)
    def test_not_larger_than_two(self, value):
        self.assertFalse(larger_than_two(value))

    @data(annotated(2, 1), annotated(10, 5))
    def test_greater(self, value):
        a, b = value
        self.assertGreater(a, b)

    @data(annotated2([2, 1], 'Test_case_1', """Test docstring 1"""),
          annotated2([10, 5], 'Test_case_2', """Test docstring 2"""))
    def test_greater_with_name_docstring(self, value):
        a, b = value
        self.assertGreater(a, b)
        self.assertIsNotNone(getattr(value, "__name__"))
        self.assertIsNotNone(getattr(value, "__doc__"))

    @file_data("test_data_dict_dict.json")
    def test_file_data_json_dict_dict(self, start, end, value):
        self.assertLess(start, end)
        self.assertLess(value, end)
        self.assertGreater(value, start)

    @file_data('test_data_dict.json')
    def test_file_data_json_dict(self, value):
        self.assertTrue(has_three_elements(value))

    @file_data('test_data_list.json')
    def test_file_data_json_list(self, value):
        self.assertTrue(is_a_greeting(value))

    @needs_yaml
    @file_data("test_data_dict_dict.yaml")
    def test_file_data_yaml_dict_dict(self, start, end, value):
        self.assertLess(start, end)
        self.assertLess(value, end)
        self.assertGreater(value, start)

    @needs_yaml
    @file_data('test_data_dict.yaml')
    def test_file_data_yaml_dict(self, value):
        self.assertTrue(has_three_elements(value))

    @needs_yaml
    @file_data('test_data_list.yaml')
    def test_file_data_yaml_list(self, value):
        self.assertTrue(is_a_greeting(value))

    @data((3, 2), (4, 3), (5, 3))
    @unpack
    def test_tuples_extracted_into_arguments(self, first_value, second_value):
        self.assertTrue(first_value > second_value)

    @data([3, 2], [4, 3], [5, 3])
    @unpack
    def test_list_extracted_into_arguments(self, first_value, second_value):
        self.assertTrue(first_value > second_value)

    @unpack
    @data({'first': 1, 'second': 3, 'third': 2},
          {'first': 4, 'second': 6, 'third': 5})
    def test_dicts_extracted_into_kwargs(self, first, second, third):
        self.assertTrue(first < third < second)

    @data(u'ascii', u'non-ascii-\N{SNOWMAN}')
    def test_unicode(self, value):
        self.assertIn(value, (u'ascii', u'non-ascii-\N{SNOWMAN}'))

    @data(3, 4, 12, 23)
    def test_larger_than_two_with_doc(self, value):
        """Larger than two with value {0}"""
        self.assertTrue(larger_than_two(value))

    @data(3, 4, 12, 23)
    def test_doc_missing_args(self, value):
        """Missing args with value {0} and {1}"""
        self.assertTrue(larger_than_two(value))

    @data(3, 4, 12, 23)
    def test_doc_missing_kargs(self, value):
        """Missing kargs with value {value} {value2}"""
        self.assertTrue(larger_than_two(value))

    @data([3, 2], [4, 3], [5, 3])
    @unpack
    def test_list_extracted_with_doc(self, first_value, second_value):
        """Extract into args with first value {} and second value {}"""
        self.assertTrue(first_value > second_value)

test_data_dict_dict.json:

{
    "positive_integer_range": {
        "start": 0,
        "end": 2,
        "value": 1
    },
    "negative_integer_range": {
        "start": -2,
        "end": 0,
        "value": -1
    },
    "positive_real_range": {
        "start": 0.0,
        "end": 1.0,
        "value": 0.5
    },
    "negative_real_range": {
        "start": -1.0,
        "end": 0.0,
        "value": -0.5
    }
}

test_data_dict_dict.yaml

positive_integer_range:
    start: 0
    end: 2
    value: 1

negative_integer_range:
    start: -2
    end: 0
    value: -1

positive_real_range:
    start: 0.0
    end: 1.0
    value: 0.5

negative_real_range:
    start: -1.0
    end: 0.0
    value: -0.5

test_data_dict.json

{
    "unsorted_list": [ 10, 12, 15 ],
    "sorted_list": [ 15, 12, 50 ]
}

test_data_dict.yaml

unsorted_list:
  - 10
  - 15
  - 12

sorted_list: [ 15, 12, 50 ]

test_data_list.json

[
    "Hello",
    "Goodbye"
]
test_data_list.yaml
- "Hello"
- "Goodbye"

猜你喜欢

转载自blog.csdn.net/lelemom/article/details/84312732