Python Api接口自動化測試框架 代碼寫用例

公司新來兩個妹子一直吐槽這個接口測試用例用excel維護起來十分費腦費事,並且比較low(心裏十分贊同可是不能推翻本身),妹子說excel原本就很麻煩的工具,因而偷偷的進行了二次改版。

變動內容以下:python

  • 1.代碼結構
 
image.png
  • 2.新增測試報告網頁版和版本管理
  • 3.新增用例代碼化
1、封裝一個獲取用例的模塊
 
image.png
用例的寫法能夠按照yml文件的寫法,後綴的文件均可爲.conf、.config、.ini。[]中的是測試用例場景,下面的參數內容對應接口用例參數。
簡單介紹下python內置模塊ConfigParser:
  • ConfigParser 是用來讀取配置文件的包。配置文件的格式以下:中括號「[ ]」內包含的爲section。section 下面爲相似於key:value 的配置內容。(key = value也能夠具體方法此次不詳細展開,以後寫一遍關於ConfigParser的用法,懂原理會讓工做更輕鬆。)mysql

  • 這裏講講爲何配置寫在最外層,若是寫到文件夾中,怎麼都沒法讀取配置。python執行run命令的時候須要.ini文件跟run 文件在同個文件夾下。因此應該是路徑問題致使,以後嘗試修復這個BUG。sql

(經過操做絕對路徑的方法修復此BUG上圖已經修復)docker

此次變動代碼實現以下:
#!/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) 

2、封裝一個日誌的模塊

此次日誌進行了一次更改:會將測試用例返回結果文件內容寫入,文件經過mkdocs生成測試報告。
公司用的微服務,因此對docker有必定涉獵。官方提供了mkdocs的鏡像。拉取官網鏡像,將數據卷掛載到搭載測試報告的宿主機上,就能夠訪問了。你只要維護代碼的測試用例,自動更新測試報告。

看下展現效果:數據庫

 
image.png

代碼以下:json

#!/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 

3、調用接口的requests

代碼以下:api

#!/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) 

4、業務包調用封裝包(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("*****************") 

5、執行包(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 來源:簡書 著做權歸做者全部。商業轉載請聯繫做者得到受權,非商業轉載請註明出處。
相關文章
相關標籤/搜索