簡(jiǎn)單的設(shè)計(jì)思路
- 利用pytest對(duì)一個(gè)接口進(jìn)行各種場(chǎng)景測(cè)試并且斷言驗(yàn)證
- 配置文件獨(dú)立開(kāi)來(lái)(conf文件),實(shí)現(xiàn)不同環(huán)境下只需要改環(huán)境配置即可
- 測(cè)試的場(chǎng)景讀取excle的測(cè)試用例,可支持全量執(zhí)行或者自定義哪條用例執(zhí)行(用例內(nèi)帶加密變量);
- 接口入?yún)⑦€包含了加密的邏輯,所以需加一層加密處理
用例的樣例:
應(yīng)用的庫(kù)包含:
import pytest
import time, json
import base64, hmac
import hashlib, uuid, re
import requests
import pandas as pd
1. 先定義好conf配置代碼
def config_txt(file_name="config.txt"):
data_head = list()
data_tail = list()
for line in open(file_name, encoding='gb18030', errors='ignore'):
head, sep, tail = line.partition('=')
data_head.append(head.strip('\n '))
if tail.find('#') != -1:
tail, tail_b, tail_c = tail.partition('#')
data_tail.append(tail.strip('\n '))
txt_data = dict(zip(data_head, data_tail))
heada, sepa, taila = txt_data["GATEWAY_URL"].partition('/test_a')
txt_data['HTTP_URI'] = "/test_a" + taila
return txt_data
conf文件配置樣例:
GATEWAY_URL = https://127.0.0.1:8051/test_a/adk #url鏈接地址
zhu_KEY = test_key #用戶信息1
zhu_SECRET = test_secret #用戶2
zhu_ID = 18825176013 #用戶ID
zhuLY_ID = 588347220 #用戶信息3
2. 簡(jiǎn)單處理一下加密的處理,給后續(xù)持續(xù)調(diào)用
def md5(data_md5):
data_md5 = hashlib.md5(data_md5.encode(encoding='UTF-8')).hexdigest()
return data_md5
def sha256(data_sha256):
data_sha256 = hashlib.sha256(data_sha256.encode(encoding='UTF-8')).hexdigest()
return data_sha256
def hash_hmac(app_secret, msg, sha1):
hmac_code = hmac.new(app_secret.encode(), msg.encode(), sha1).digest()
return base64.b64encode(hmac_code).decode()
3. 處理用例里面的加密變量,例如:請(qǐng)求參數(shù)md5(18812345678)先進(jìn)行數(shù)據(jù)預(yù)處理
def body_encrypt(data_encrypt):
if data_encrypt.find("sha256(") != -1:
sha_ss = re.findall(r"sha256[(](.+?)[)]", data_encrypt)
for i in range(len(sha_ss)):
data_encrypt = re.compile("sha256[(]" + str(sha_ss[i]) + '[)]').sub(str(sha256(sha_ss[i])), data_encrypt)
if data_encrypt.find("md5(") != -1:
md5_ss = re.findall(r"md5[(](.+?)[)]", data_encrypt)
for i in range(len(md5_ss)):
data_encrypt = re.compile("md5[(]" + str(md5_ss[i]) + '[)]').sub(str(md5(md5_ss[i])), data_encrypt)
return data_encrypt
4. 讀取excel文檔里面的用例數(shù)據(jù)做為測(cè)試場(chǎng)景
def excel_case(file_name="case_file2.xlsx", case_id="all"): # 讀取excel賬號(hào)及路由代理信息file_name
data_excle = pd.read_excel(file_name, sheet_name=0, engine="openpyxl")
df = pd.DataFrame(data_excle)
if case_id != "all":
df_data = df[(df.case_id == case_id)].to_dict('list')
else:
df_data = df.to_dict('list')
case_id, case_name = df_data['case_id'], df_data['case_name']
case_body, case_assert = df_data['case_body'], df_data['case_assert']
case_body1 = body_encrypt(str(case_body))
txt_data = list(zip(case_id, case_name, eval(case_body1), case_assert))
return txt_data
5. 上主菜,pytest的使用
class Test_zhu(object):
#類初始化,此處在測(cè)試執(zhí)行中,全局只會(huì)執(zhí)行一次(讀取配置文件)
@classmethod
def setup_class(self):
self.text_data = config_txt()
#方法初始化,此處在測(cè)試執(zhí)行中,每條用例都會(huì)先執(zhí)行一遍
def setup_method(self):
time.sleep(0.4)
self.time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
#request接口請(qǐng)求的邏輯
def request_id(self, GATEWAY_URL, http_body):
HTTP_BODY = eval(http_body)
TIME_STAMP = str(int((time.time() + 5) * 1000))
zhuCE = uuid.uuid1().hex
msg = self.text_data['zhuLY_ID'] + "\n" + TIME_STAMP + "\n" + zhuCE + "\n" + self.text_data['zhu_KEY'] + "\n" + \
self.text_data["HTTP_URI"] + "\n" + json.dumps(HTTP_BODY)
HTTP_HEADER = {
"zhu_ID": self.text_data['zhu_ID'],
"zhuLY_ID": self.text_data['zhuLY_ID'],
"zhuCE": zhuCE,
"zhu_KEY": self.text_data['zhu_KEY'],
"TIMESTAMP": TIME_STAMP,
"SIGNATURE": hash_hmac(self.text_data['zhu_SECRET'], msg, hashlib.sha1)}
print('**請(qǐng)求參數(shù):{}.'.format(HTTP_BODY))
response_one = requests.post(GATEWAY_URL, json=HTTP_BODY, headers=HTTP_HEADER, verify=True)
print('**響應(yīng)結(jié)果:{}.'.format(response_one.text))
return eval(response_one.text)
#parametrize為數(shù)據(jù)驅(qū)動(dòng),此處獲取了excle用例里的數(shù)據(jù);apitest定個(gè)標(biāo)簽,后續(xù)冒煙啥的可以選擇性的跑(暫時(shí)無(wú)用);
#excel_case(case_id="all")說(shuō)明,all為全部用例執(zhí)行或者指定用例執(zhí)行case_0001
@pytest.mark.parametrize('case_id,case_name, case_body, case_assert', excel_case(case_id="all"))
@pytest.mark.apitest
def test_zhu_case(self, case_id, case_name, case_body, case_assert):
print("**\n執(zhí)行編號(hào):" + case_id + "\n**用例名稱:" + case_name)
case_assert_a = json.loads(case_assert)
alertText = self.request_id(self.text_data['GATEWAY_URL'], case_body)
retcode = case_assert_a.get('code') if case_assert_a.get('retcode') == None else case_assert_a.get('retcode')
alertText_a = alertText.get('code') if alertText.get('retcode') == None else alertText.get('retcode')
#此處為斷言,判斷用例通過(guò)還是不通過(guò)
assert alertText_a == retcode
if __name__ == '__main__':
pytest.main(["-sv", 'zhu_testA.py'])
6. 利用pytest-html庫(kù)可以生成html報(bào)告
命令:pytest zhu_testA.py --html=report.html --self-contained-html
到此這篇關(guān)于python使用pytest接口自動(dòng)化測(cè)試的使用的文章就介紹到這了,更多相關(guān)python 接口自動(dòng)化測(cè)試內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- Python接口自動(dòng)化淺析數(shù)據(jù)驅(qū)動(dòng)原理
- Python接口自動(dòng)化淺析登錄接口測(cè)試實(shí)戰(zhàn)
- Python接口自動(dòng)化淺析unittest單元測(cè)試原理
- python+requests+pytest接口自動(dòng)化的實(shí)現(xiàn)示例
- python接口自動(dòng)化測(cè)試數(shù)據(jù)和代碼分離解析