1. 程式人生 > 實用技巧 >Python:介面框架:資料驅動和程式碼驅動

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()