ddt
python 专门用来实现数据驱动的第三方包
-
安装对应的ddt文件
pip install ddt
-
包含内容/模块
- data - 存放数据格式:字典元祖列表
- unpack - 用来做数据解包,把对应的数据自动的分别进行分割
- fila_data - 存放数据格式:json yaml(读取出来会以字典的格式进行展示)
-
使用
- 进行导包
from ddt import ddt, data,file_data,unpack
- 装饰对应的类
@ddt class TestLogin(unittest.TestCase): def...
-
准备测试数据进行用例执行
模拟用户登录,仅需要用户名和密码,此处仅展示部分代码段~
@ddt class TestLogin(unittest.TestCase): # 方法一 @data({ "username":"yyy","password":"111111"}) @unpack def test_login_success(self,**paras): self.driver.find_element(By.ID,"username").send_keys(paras["username"]) self.driver.find_element(By.ID,"password").send_keys(paras["password"]) # 方法二 (适用于多个字典数据 单个用例操作) datas = [{ "username":"yyy","password":"111111"},{ "username":"hhh","password":"123456"}] @data(*datas) @unpack def test_login_success(self,**paras): self.driver.find_element(By.ID,"username").send_keys(paras["username"]) self.driver.find_element(By.ID,"password").send_keys(paras["password"]) # 方法三 (data数据为字典类型,参数要和key一样) @data({ "username":"yyy","password":"111111"}) @unpack def test_login_success(self,username,password): self.driver.find_element(By.ID,"username").send_keys(username) self.driver.find_element(By.ID,"password").send_keys(password) # 方法四 (适用于多个数据单个用例操作,这里数据类型为列表或者元祖) @data(["yyy","111111"],["hhh","111111"]) @unpack def test_login_success(self,username,password): self.driver.find_element(By.ID,"username").send_keys(username) self.driver.find_element(By.ID,"password").send_keys(password) ...
以上为 ddt 中的 data 模块实现,下面我们来使用 file_data操作:
- caseName: test_login_success username: yyy password: 111111
@ddt class TestLogin(unittest.TestCase): @file_data("yaml文件的路径/login.yaml") @unpack def test_login_success(self,**paras): self.driver.find_element(By.ID,"username").send_keys(paras["username"]) self.driver.find_element(By.ID,"password").send_keys(paras["password"])
总结
file_data 可以获取 json 文件和 yaml 文件的数据;需要把数据放入到独立的 json 文件中,另外 json/yaml 文件中的内容需要和 def 函数中的参数个数对应;
data 数据相对就比较直观,直接写在py文件里面;