DDT:Data-Drivern Tests是针对unittest的扩展库。允许使用不同的测试数据来运行一个测试用例,并将其展示为多个测试用例
1.在线下载
在Dos下输入:
python -m pip install ddt
安装成功结果为:
2.利用DDT5种不同的参数化方式实现百度搜索
test_baidu_ddt.py
import unittest from ddt import ddt, data, file_data, unpack from time import sleep from selenium import webdriver @ddt class TestBaidu(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = webdriver.Chrome() cls.base_url = "https://www.baidu.com" def baidu_search(self, search_key): self.driver.get(self.base_url) self.driver.find_element_by_id("kw").send_keys(search_key) self.driver.find_element_by_id("su").click() sleep(3) # 参数化方式1:列表 @data(["case1", "selenium"], ["case2", "unittest"], ["case3", "python"]) @unpack def test_search1(self, case, search_key): print("第一组测试用例:", case) self.baidu_search(search_key) self.assertEqual(self.driver.title, search_key + "_百度搜索") # 参数化方式2:元组 @data(("case1", "selenium"), ("case2", "unittest"), ("case3", "python")) @unpack def test_search2(self, case, search_key): print("第二组测试用例:", case) self.baidu_search(search_key) self.assertEqual(self.driver.title, search_key + "_百度搜索") # 参数化方式3:字典 @data({"search_key": "selenium"}, {"search_key": "unittest"}, {"search_key": "python"}) @unpack def test_search3(self, search_key): print("第三组测试用例:", search_key) self.baidu_search(search_key) self.assertEqual(self.driver.title, search_key + "_百度搜索") # 参数化方式4:文件参数化 @file_data("D:/Test1/test_csv_pa_ddt/ddt_data_file.json") def test_search4(self, search_key): print("第四组测试用例:", search_key) self.baidu_search(search_key) self.assertEqual(self.driver.title, search_key + "_百度搜索") # 参数化方式5:yaml文件 @file_data("D:/Test1/test_csv_pa_ddt/ddt_data_file.yaml") def test_search5(self, case): search_key = case[0]["search_key"] print("第五组测试用例:", search_key) self.baidu_search(search_key) self.assertEqual(self.driver.title, search_key + "_百度搜索") @classmethod def tearDownClass(cls): cls.driver.quit() if '__name__' == '__main__': unittest.main(verbosity=2)
参数化4的json:(ddt_data_file.json)
{ "case1":{"search_key": "selenium"}, "case2":{"search_key": "unittest"}, "case3":{"search_key": "python"} }
参数化5的yaml:(ddt_data_file.yaml)
case1: - search_key: "python" case2: - search_key: "unittest" case3: - search_key: "ddt"
注意:如果没安装yaml,参数化5无法执行
Dos在线安装命令为:
python -m pip install pyyaml
安装成功如下图:
最后,运行结果为: