標籤:val 變數 自動化測試 擷取 應該 測試 return decode 定義
公司新來兩個妹子一直吐槽這個介面測試案例用excel維護起來十分費腦費事,而且比較low(內心十分贊同但是不能推翻自己),妹子說excel本來就很麻煩的工具,於是偷偷的進行了二次改版。
變更內容如下:
image.png
- 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 ConfigParserconfig = 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 -*-# 基礎包:Log Serviceimport loggingimport constants as csimport logging.handlersdef 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 requestsimport jsondef change_type(value): """ 對dict類型進行中文識別 :param value: 傳的資料值 :return: 轉碼後的值 """ result = eval(json.dumps(value, ensure_ascii=False, encoding="UTF-8")) return resultdef 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 mysqlimport lib.tezLog as logimport lib.tezRequest as requestimport lib.tezConfig as confimport constants as csimport osdef 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 resdef 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 commonimport 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介面自動化測試架構 代碼寫用例