python ddt实现数据驱动
首先安装ddt模块,命令:pip install ddt
通常情况下,data中的数据按照一个参数传递给测试用例,如果data中含有多个数据,以元组,列表,字典等数据,需要自行在脚本中对数据进行分解或者使用unpack分解数据。
@data(a,b)
那么a和b各运行一次用例
@data([a,d],[c,d])
如果没有@unpack,那么[a,b]当成一个参数传入用例运行
如果有@unpack,那么[a,b]被分解开,按照用例中的两个参数传递
一:
1 import unittest
2 from ddt import ddt,data,unpack
3 from time import sleep
4 from selenium import webdriver
5 @ddt
6 class MyTesting(unittest.TestCase):
7 def setUp(self):
8 self.dr = webdriver.Chrome()
9 self.dr.get('http://www.baidu.com')
10
11 @data(['python','python_百度搜索'],['java','java_百度搜索'])
12 @unpack
13 def test_baidu(self,a,b):
14 self.dr.find_element_by_id('kw').send_keys(a)
15 self.dr.find_element_by_id('su').click()
16 sleep(2)
17 c = self.dr.title
18 self.assertEqual(b,c)
19
20
21 def tearDown(self):
22 self.dr.close()
23 if __name__ == '__main__':
24 unittest.main(verbosity=2)
传入字典参数
import unittest from ddt import ddt,data,unpack from time import sleep from selenium import webdriver @ddt class MyTesting(unittest.TestCase): def setUp(self): self.dr = webdriver.Chrome() self.dr.get('http://www.baidu.com') @data({'a':'python','b':'python_百度搜索'},{'a':'java','b':'java_百度搜索'}) @unpack def test_baidu(self,a,b): self.dr.find_element_by_id('kw').send_keys(a) self.dr.find_element_by_id('su').click() sleep(2) c = self.dr.title self.assertEqual(b,c) def tearDown(self): self.dr.close() if __name__ == '__main__': unittest.main()
二:传入JSON文件
import unittest from ddt import ddt,data,unpack,file_data from time import sleep from selenium import webdriver @ddt class MyTesting(unittest.TestCase): def setUp(self): self.dr = webdriver.Chrome() self.dr.get('http://www.baidu.com') @file_data('test.json') @unpack def test_baidu(self,a,b): self.dr.find_element_by_id('kw').send_keys(a) self.dr.find_element_by_id('su').click() sleep(2) c = self.dr.title self.assertEqual(b,c) def tearDown(self): self.dr.close() if __name__ == '__main__': unittest.main()
test.json文件内容如下,和上面代码同一路径
{ "positive_integer_range": { "a": "python", "b": "python_百度搜索" }, "negative_integer_range": { "a": "java", "b": "java_百度搜索" } }
读取json文件的值
import unittest from ddt import ddt,data,unpack,file_data from time import sleep from selenium import webdriver @ddt class MyTesting(unittest.TestCase): def setUp(self): self.dr = webdriver.Chrome() self.dr.get('http://www.baidu.com') @file_data('test.json') @unpack def test_baidu(self,value): self.dr.find_element_by_id('kw').send_keys(value) self.dr.find_element_by_id('su').click() # sleep(2) # c = self.dr.title # self.assertEqual(b,c) def tearDown(self): self.dr.close() if __name__ == '__main__': unittest.main()
json文件如下:
{ "unsorted_list": "python", "sorted_list": "java" }
或者json文件改成一下:
["python","java"]
本文来自博客园,作者:Harry_666,转载请注明原文链接:https://www.cnblogs.com/harry66/p/12690694.html