代码驱动:你的用例都是代码写的,如果不继续往下写代码,下面就没有用例了
数据驱动:有一条数据执行一条测试用例,没有数据不执行
关键字驱动:ui自动化的时候能用到
代码驱动实例:
import unittest import requests class StuInfoTest(unittest.TestCase): url = 'http://api.nnzhp.cn/api/user/stu_info' def test_single(self): data = {'name':'xidada'} r = requests.get(self.url,data) print(r.json()) def test_more(self): data = {'name':'xiaohei'} r = requests.get(self.url,data) print(r.json()) unittest.main()
下面是手动一条一条添加测试数据(数据驱动):
import unittest import requests import parameterized class StuInfoTest(unittest.TestCase): url = 'http://api.nnzhp.cn/api/user/stu_info' @parameterized.parameterized.expand( [ ['小黑',18],#这种是数据驱动 ['小白',17], ['小黄',16], ['小绿',15] ] ) #expand里面要传一个二维数组,因为有时候函数有多个入参,需要一一对应 def test_single(self,name,age): print(name) data = {'stu_name':name,'age':age} r = requests.get(self.url,data) print(r.json()) unittest.main()
一条一条添加测试数据的话,某一天测试数据如果改变了,也需要手动查找代码改数据,所以数据,代码要分离,在当前文件下面定义一个
'stu_info.txt'(如果文件不在当前文件下,则需要写绝对路径),里面存储好要测试的数据,需要改数据的时候直接在这里面改
import unittest import requests import parameterized import os class GetData: @staticmethod def read_data_to_file(filename): data = [] if os.path.exists(filename): with open(filename,'r',encoding='utf-8') as fr: for line in fr: d1 = line.strip().split(',') data.append(d1) else: raise Exception('文件不存在') # raise FileNotFoundError('参数化文件找不到') return data @staticmethod def read_data_to_excel(filename): pass @staticmethod def read_data_to_redis(key): pass @staticmethod def read_data_to_mysql(sql): pass class StuInfoTest(unittest.TestCase): url = 'http://api.nnzhp.cn/api/user/stu_info' @parameterized.parameterized.expand(GetData.read_data_to_file('stu_info.txt')) #类可以直接调用静态方法 def test_single(self,name,age): print(name) data = {'stu_name':name,'age':age} r = requests.get(self.url,data) print(r.json()) unittest.main()