51Testing软件测试论坛

标题: python ddt 数据驱动测试 [打印本页]

作者: 测试积点老人    时间: 2018-12-12 14:15
标题: python ddt 数据驱动测试
  1. # -*- coding: utf-8 -*-
  2. import unittest
  3. from ddt import ddt, data, unpack
  4. import csv
  5. from collections import namedtuple


  6. def add(a,b):
  7.     c = a+b
  8.     return c


  9. def addstr(a,b):
  10.     c = a + b
  11.     return c


  12. def get_csv_data():
  13.     value_rows = []
  14.     with open('./mfile.csv') as f:      
  15.         f_csv = csv.reader(f)
  16.         next(f_csv)
  17.         for r in f_csv:
  18.             value_rows.append(r)
  19.             
  20.     return value_rows
  21.             


  22. @ddt
  23. class Test(unittest.TestCase):


  24.     @data((1,1,2), (1,2,3))
  25.     @unpack
  26.     def test_addnum(self,a, b, expected_value):
  27.         self.assertEqual(add(a,b),expected_value)
  28.         
  29.     @data(*get_csv_data())
  30.     @unpack
  31.     def test_addstr(self,a,b,expected_value):
  32.         self.assertEqual(addstr(a,b), expected_value)
  33.         
  34. if __name__ == "__main__":
  35.     suite = unittest.TestLoader().loadTestsFromTestCase(Test)
  36.     unittest.TextTestRunner(verbosity=2).run(suite)



  37. csv文件:

  38. value1,value2,result
  39. aa,bb,aabb
  40. ww,r,wwr
  41. 111,222,111222
  42. 1,2,3
复制代码
运行结果:
  1. test_addnum_1__1__1__2_ (__main__.Test) ... ok
  2. test_addnum_2__1__2__3_ (__main__.Test) ... ok
  3. test_addstr_1___aa____bb____aabb__ (__main__.Test) ... ok
  4. test_addstr_2___ww____r____wwr__ (__main__.Test) ... ok
  5. test_addstr_3___111____222____111222__ (__main__.Test) ... ok
  6. test_addstr_4___1____2____3__ (__main__.Test) ... FAIL
复制代码







欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) Powered by Discuz! X3.2