Python Api接口自動化測試框架 代碼寫用例
阿新 • • 發佈:2018-05-25
簡書 場景 分享圖片 else basic UNC ant ctc ascii
作者:赫本z
鏈接:https://www.jianshu.com/p/459e578f86e6
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請註明出處。
公司新來兩個妹子一直吐槽這個接口測試用例用excel維護起來十分費腦費事,而且比較low(內心十分贊同但是不能推翻自己),妹子說excel本來就很麻煩的工具,於是偷偷的進行了二次改版。
變更內容如下:
-
1.代碼結構
-
2.新增測試報告網頁版和版本管理
-
3.新增用例代碼化
一、封裝一個獲取用例的模塊
image.png用例的寫法可以按照yml文件的寫法,後綴的文件都可為.conf、.config、.ini。[]中的是測試用例場景,下面的參數內容對應接口用例參數。
簡單介紹下python內置模塊ConfigParser:
ConfigParser 是用來讀取配置文件的包。配置文件的格式如下:中括號“[ ]”內包含的為section。section 下面為類似於key:value 的配置內容。(key = value也可以具體方法這次不詳細展開,之後寫一遍關於ConfigParser的用法,懂原理會讓工作更輕松。)
這裏講講為什麽配置寫在最外層,如果寫到文件夾中,怎麽都無法讀取配置。python執行run命令的時候需要.ini文件跟run 文件在同個文件夾下。所以應該是路徑問題導致,之後嘗試修復這個BUG。
(通過操作絕對路徑的方法修復此BUG上圖已經修復)
這次變更代碼實現如下:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 基礎包:配置服務
import ConfigParser
config = ConfigParser.ConfigParser()
def get_config(filename):
"""
獲取文件配置
:param filename: 配置文件名
:return: None
"""
global config
try:
config.read(filename)
return True
except Exception, e:
print ("讀取配置失敗 %s" % e)
def get_data(title, key):
"""
參數配置
:param title: 配置文件的頭信息
:param key: 配置文件的key值
:return: 配置文件的value
"""
try:
value = config.get(title, key)
return value
except Exception, e:
print ("獲取參數失敗 %s" % e)
def get_title_list():
"""
獲取所有title
:return: title list
"""
try:
title = config.sections()
return str(title).decode("string_escape")
except Exception, e:
print ("獲取title信息失敗 %s", e)
二、封裝一個日誌的模塊
這次日誌進行了一次更改:會將測試用例返回結果文件內容寫入,文件通過mkdocs生成測試報告。
公司用的微服務,所以對docker有一定涉獵。官方提供了mkdocs的鏡像。拉取官網鏡像,將數據卷掛載到搭載測試報告的宿主機上,就可以訪問了。你只要維護代碼的測試用例,自動更新測試報告。
看下展示效果:
image.png代碼如下:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 基礎包:日誌服務
import logging
import constants as cs
import logging.handlers
def get_logger(name=‘report‘):
FORMAT = ‘%(message)s‘
filename = cs.REPORT_PATH + name + cs.NOW
logging.basicConfig(level=logging.WARNING, format=FORMAT,
filename=filename, filemode=‘w‘)
return logging
三、調用接口的requests
代碼如下:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 基礎包:接口測試的封裝
import requests
import json
def change_type(value):
"""
對dict類型進行中文識別
:param value: 傳的數據值
:return: 轉碼後的值
"""
result = eval(json.dumps(value, ensure_ascii=False, encoding="UTF-8"))
return result
def api(method, url, data, headers):
"""
定義一個請求接口的方法和需要的參數
:param method: 請求類型
:param url: 請求地址
:param data: 請求參數
:param headers: 請求headers
:return: code碼
"""
global results
try:
if method == ("post" or "POST"):
results = requests.post(url, data, headers=headers)
if method == ("get" or "GET"):
results = requests.get(url, data, headers=headers)
response = results.json()
code = response.get("code")
return code
except Exception, e:
print ("請求失敗 %s" % e)
四、業務包調用封裝包(common.py)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 業務包:通用函數
import lib.tezMysql as mysql
import lib.tezLog as log
import lib.tezRequest as request
import lib.tezConfig as conf
import constants as cs
import os
def prepare_data(host, user, password, db, sql):
"""
數據準備,添加測試數據
:param host: 服務地址
:param user: 用戶
:param password: 密碼
:param db: 數據庫名
:param sql: 執行的SQL
:return:
"""
mysql.connect(host, user, password, db)
res = mysql.execute(sql)
mysql.close()
print ("Run sql: the row number affected is %s" % res)
return res
def get_prepare_sql(filename, key):
"""
獲取預備執行的SQL
:param title: 配置文件頭信息
:param key: 配置文件值
:return: Value
"""
try:
conf.get_config(filename)
value = conf.get_data(title=cs.TITLE, key=key)
return value
except Exception, e:
print ("獲取用例參數值失敗 %s" % e)
def reset_report(filename):
try:
result = os.path.exists(cs.REPORT_PATH)
if result == True:
conf.get_config(filename)
reportName = eval(conf.get_data(title=cs.REPORT_NAME, key=cs.REPORT))
report_name = eval(conf.get_data(title=cs.REPORT_NAME, key=cs.R_NAME))
file = open(cs.YML_REPORT, ‘r‘)
list_con = file.readlines()
content = str(list_con).decode("string_escape")
fileContent = "- [%s, %s]"
row = "\n"
con = row + fileContent % (reportName + cs.NOW, report_name)
if fileContent % (reportName + cs.NOW, report_name) not in content:
f = open(cs.YML_REPORT, ‘a+‘)
f.write(con)
else:
print ("內容已經存在 %s" % con)
except Exception, e:
print ("文件路徑不存在 %s", e)
def run_test(filename):
conf.get_config(filename)
list = eval(conf.get_title_list())
reportName = eval(conf.get_data(cs.REPORT_NAME, key=cs.REPORT))
logging = log.get_logger(reportName)
for i in range(2, len(list)):
title = list[i]
number = eval(conf.get_data(title, key=cs.NUMBER))
name = str(conf.get_data(title, key=cs.NAME))
method = str(conf.get_data(title, key=cs.METHOD))
url = str(conf.get_data(title, key=cs.URL))
data = request.change_type(conf.get_data(title, key=cs.DATA))
headers = eval(conf.get_data(title, key=cs.HEADERS))
testUrl = cs.TEST_URL + url
actualCode = request.api(method, testUrl, data, headers)
expectCode = conf.get_data(title, key=cs.CODE)
if actualCode != expectCode:
print "FailInfo"
print number
logging.warning("- <font color=#FFB5C5 size=3>FailCase : %s", name)
logging.warning(" - <font color=#FFB5C5 size=3>Number : %s", number)
logging.warning(" - <font color=#FFB5C5 size=3>Method : %s", method)
logging.warning(" - <font color=#FFB5C5 size=3>Url : %s", testUrl)
logging.warning(" - Data : </br> ``` %s ```", data)
logging.warning(" - Headers : </br> ``` %s ```", headers)
logging.warning(" - <font color=#FFB5C5 size=3>期望值 : %s", expectCode)
logging.warning(" - <font color=#FFB5C5 size=3>實際值 : %s", str(actualCode))
logging.warning("*****************")
else:
print number
print "TrueInfo"
logging.warning("- <font color=#3cc8b4 size=3> TrueCase %s", name)
logging.warning("*****************")
五、執行包(run.py)
import util.common as common
import sys
# FILENAME = sys.argv[1]
FILENAME = "proUser.ini"
"""1.新建測試報告目錄"""
common.reset_report(filename=FILENAME)
"""2.執行測試用例"""
common.run_test(filename=FILENAME)
PS:有個全局變量包constant.py,裏面看到是參數目錄文件相關的
作者:赫本z
鏈接:https://www.jianshu.com/p/459e578f86e6
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請註明出處。
Python Api接口自動化測試框架 代碼寫用例