接口自動化一

開始正式針對任務完成接口自動化。
想法如下:

  1. 此次接口自動化是需要上傳文件的,以前想的方法是文件路徑全部存入文件中,定義成常量直接讀取,後來在設計excel表格的時候感覺很不方便,需要判斷是否有這個入參,然後再讀取常量,後來想了另外一個辦法,直接在excel裏寫入上傳的文件,其餘的入參對象以字典的形式存在
  2. 沒有使用類,直接使用函數實現,分讀取excel,調用requests,寫入excel, 生成html 4個函數實現。
  3. 先在Windows下跑通,後想移到Linux下跑通(暫時未試)

有部分借鑑代碼,所以本文章還是寫爲轉載

代碼:

import requests,xlrd,json,time,sys,os
from xlutils.copy import copy

HOST = XX
PORT = XX

def read_xls(filename): #讀用例
try:
book = xlrd.open_workbook(filename) # 打開excel,若不存在,報錯
except Exception as e:
print('Not found the file')
return e
else:
sheet = book.sheet_by_index(0) # 取第一個sheet頁
all_cases = [] # 定義空list,用於保存每一條測試用例
for row in range(1, sheet.nrows): # 不取表頭,逐行讀取
all_cases.append(sheet.row_values(row)) # 把每一條測試用例添加到list中
if all_cases:
print('獲取用例成功!')
else:
print('用例獲取失敗!')
call_requests(filename,all_cases) # 返回list

def call_requests(filename,all_cases):
response_data = [] #存響應的list
result_data = []

print('開始請求數據...')

for case in all_cases: #先遍歷excel中每一條case的值,然後根據對應的索引取到case中每個字段的值
    url = 'http://' + HOST + ':' + PORT + case[1] #請求url
    title = case[0]
    s_file = case[3]
    i_file = case[4]
    upload_data = case[5]
    expected_result = case[6]

    if s_file and _file:
        s= os.path.abspath(s_file)
        i = os.path.abspath(i_file)
        files = {'s': open(s, 'rb'), 'i: open(i, 'rb')}
        res = requests.post(url=url, data=json.loads(upload_data), files=files).text
    else:
        res = requests.post(url=url, data=json.loads(upload_data)).text

    if s_file and i_file =='':
        s = os.path.abspath(s_file)
        files = {'s': open(s, 'rb')}
        res = requests.post(url=url, data=json.loads(upload_data), files=files).text

    if s_file =='' and i_file:
        image = os.path.abspath(i_file)
        files = {'i: open(i, 'rb')}
        res = requests.post(url=url, data=json.loads(upload_data), files=files).text

    new_res = res.replace('": "', '=').replace('": ', '=')

    for i in expected_result.split('&'):
        if i in new_res:
            returnMessage = 'Succeed'
            print(title, '請求成功!')
        else:
            returnMessage = 'Failed'
            print(title,'請求失敗!')
    response_data.append(res)
    result_data.append(returnMessage) #將結果加入到測試結果list

write_xls(filename,response_data,result_data)

def write_xls(filename,response_data,result_data): #寫入excel
book1 = xlrd.open_workbook(filename) #打開原來的excel,獲取到這個對象
book2 = copy(book1) #複製一個new book
sheet = book2.get_sheet(0) #獲取這個複製的excel的第一個sheet頁
line = 1 #第一行是表頭,所以從第二行開始寫入
succeed_count = 0
fail_count = 0
for a,b in zip(response_data,result_data):
sheet.write(line,7,a)
sheet.write(line,8,b)
if b == 'Succeed':
succeed_count+=1
else:
fail_count+=1
line = line + 1 #執行幾行用例

book2.save(filename) #保存一個以前妝時間命名的測試結果

print('執行成功條數',succeed_count)
print('執行失敗條數...',fail_count)
line -=1

generate_html(succeed_count,fail_count,filename)

def generate_html(s_count, f_count, filepath):
current = time.strftime('%Y%m%d%H%M%S')
book = xlrd.open_workbook(filepath)
sheet = book.sheet_by_index(0) # 取第一個sheet頁
all_cases = [] # 定義空list,用於保存每一條測試用例
for row in range(1, sheet.nrows): # 不取表頭,逐行讀取
all_cases.append(sheet.row_values(row)) # 把每一條測試用例添加到list中

html = '<html><meta charset="utf-8"><body>測試時間:' + current + '<br><br>接口自動化掃描,列表如下<br><table border="1" bordercolor="#000000" cellspacing="0" cellpadding="2" style="border-collapse:collapse;"><tr><th style="width:100px;text-align:left">接口</th><th style="width:50px;text-align:left">響應結果</th><th style="width:200px;text-align:left">執行結果</th></tr>'
for test in all_cases:
html = html + '<tr><td style="text-align:left">' + test[0] + '</td><td style="text-align:left">' + test[
7] + '</td><td style="text-align:left">' + test[8] + '</td></tr>'

html = html + '<div>本次測試一共完成' + str(
len(all_cases)) + '個接口測試,其中成功<font color="blue">' + str(s_count) + '</font>個,失敗<font color="red">' + str(f_count) + '</font>個</div><br><br>'
report_name = current + '測試結果'
report_HTML = report_name + '.html' # 命名生成的html
with open(report_HTML, "w", encoding='utf-8') as f:
f.write(html)
print("本次測試完成,請查看測試報告:", report_HTML)
return True

file_path = 'compound.xls'
read_xls(os.path.abspath(file_path))

if name == 'main':

try:
    filename = sys.argv[1]
except IndexError as e:
    print ('Please enter a correct testcase! \n e.x: python gkk.py test_case.xls')
# else:
#     read_xls(file_path)
print('完成!')

    本次經驗總結:
    1.對json.dumps 和json.loads有了進一步的認識,之前我在excel裏寫入參的時候通常採用{'key' : 'value' , 'key':'value'}, 喜歡採用單引號,我區分字典和json就是以單引號和雙引號來區分的,這是不對的,字典支持雙引號和單引號。
    2.入參是什麼格式,要看支持什麼格式的入參,像比如我們公司入參不是json格式的,json格式在python中就一字符串,我在入參中採用雙引號格式,然後讀出來的時候是字符串,格式是這樣的''' {"key":"value","key":"value"}''', 讀出來的是json字符串,因爲入參不支持json,所以需要得用json.loads將json轉爲字符串來處理,json.dumps的功能是將字典轉爲json
    3.requests,data可支持字典和字符串格式

轉載一段文字,說得很清楚:
data參數支持字典格式也支持字符串格式,如果是字典格式,requests方法會將其按照默認表單urlencoded格式轉換爲字符串,如果是字符串則不轉化

如果data以字符串格式傳輸需要遵循以下幾點:

必須是嚴格的JSON格式字符串,裏面必須用雙引號,k-v之間必須有逗號,布爾值必須是小寫的true/false等等
不能有中文,直接傳字符串不會自動編碼

一般來說,建議將data聲明爲字典格式(方便數據添加修改),然後再用json.dumps()方法把data轉換爲合法的JSON字符串格式

寫得不對的地方請大家批評指教,與大家共勉!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章