Python:接口框架:数据驱动和代码驱动

驱动:
1、数据驱动:用例是通过数据驱动的;比如python文件需要从yaml文件里取数据,没有yaml文件就运行不了py文件
2、代码驱动:用例是通过代码实现的,没有数据文件
例一:数据驱动:
import unittest
import ddt
import requests,nnreport
@ddt.ddt #首先需要在类上面加上这个装饰器
class Login(unittest.TestCase):
@ddt.file_data(r'/Users/houning/Downloads/接口自动化课程/课堂练习/课上练习/UTP/data/login.yaml') #把同级目录下的a.yaml文件的数据拿过来参数化
def test_interface(self,**test_data): #test_data代表每一个用例数据的字典
#**意思是入参是个字典
url=test_data.get('url')
method=test_data.get('method').upper()
detail=test_data.get('detail','没写用例描述') #get不到,就默认取'没写用例描述'值
self._testMethodDoc=detail #添加用例描述
data=test_data.get('data',{}) #请求数据,没有请求数据,就为空
headers=test_data.get('headers',{}) #请求头,没有请求头,就为空
cookies=test_data.get('cookies',{})
is_json=test_data.get('is_json',0) #标识入参是否为json
check=test_data.get('check') #断言
if method=='POST':
if is_json:
res=requests.post(url,json=data,cookies=cookies,headers=headers).text
else:
res = requests.post(url, data=data, cookies=cookies, headers=headers).text
elif method=='GET':
res=requests.get(url,params=data,cookies=cookies, headers=headers).text

for c in check:
self.assertIn(c,res,'预期结果:'+c+','+'实际结果:'+res) #判断预期结果在不在实际结果里面

例二:代码驱动(关联):
import unittest,requests
class GoldTest(unittest.TestCase):
def login(self): #不加test,unittest就不会自动运行这个函数
url = 'http://118.24.3.40/api/user/login'
data={'username':'niuhanyang','passwd':'aA123456'}
res=requests.post(url,data).json()
user_id=res.get('login_info').get('userId') #获取userId
sign=res.get('login_info').get('sign')
return user_id,sign #返回值,用来关联
def test_gold_add(self):
url='http://118.24.3.40/api/user/gold_add'
data={'stu_id':510,'gold':509}
userid,sign=self.login()
cookies={'niuhanyang':sign} cookie里的sign关联登录接口的返回值sign
res=requests.post(url,data,cookies=cookies).json()
self.assertEqual(res.get('error_code'),20)
unittest.main()

猜你喜欢

转载自www.cnblogs.com/hesperid/p/13367892.html
今日推荐