1. 程式人生 > >python Excel介面測試

python Excel介面測試

excel中儲存的介面資訊及格式

#!/usr/bin/env python
# -*- coding:utf-8 -*-

#Todo:介面自動化測試

import json
import random
import time
import re
import logging
import os
import sys
import requests
reload(sys)
sys.setdefaultencoding('utf-8')
import xlrd
import smtplib
from email.mime.text import MIMEText

log_file = os.path.join(os.getcwd(), './log/liveappapi.log'
) log_format = '[%(asctime)s] [%(levelname)s] %(message)s' logging.basicConfig(format=log_format, filename=log_file, filemode='w', level=logging.DEBUG) console = logging.StreamHandler() console.setLevel(logging.DEBUG) formatter = logging.Formatter(log_format) console.setFormatter(formatter) logging.getLogger(''
).addHandler(console) #獲取並執行測試用例 def runTest(testCaseFile): testCaseFile = './TestCase/TestCase.xlsx' testCaseFile = os.path.join(os.getcwd(), testCaseFile) if not os.path.exists(testCaseFile): logging.error('測試用例檔案不存在!!!') sys.exit() testCase = xlrd.open_workbook(testCaseFile) table = testCase.sheet_by_index(0
) errorCase = [] correlationDict = {} correlationDict['${session}'] = None for i in range(1, table.nrows): correlationDict['${randomEmail}'] = ''.join(random.sample('abcdefghijklmnopqrstuvwxyz', 6)) + '@automation.test' correlationDict['${randomTel}'] = '186' + str(random.randint(10000000, 99999999)) correlationDict['${timestamp}'] = int(time.time()) if table.cell(i, 10).value.replace('\n', '').replace('\r', '') != 'Yes': continue num = str(int(table.cell(i, 0).value)).replace('\n', '').replace('\r', '') api_purpose = table.cell(i, 1).value.replace('\n', '').replace('\r', '') api_host = table.cell(i, 2).value.replace('\n', '').replace('\r', '') request_url = table.cell(i, 3).value.replace('\n', '').replace('\r', '') request_method = table.cell(i, 4).value.replace('\n', '').replace('\r', '') request_data_type = table.cell(i, 5).value.replace('\n', '').replace('\r', '') request_data = table.cell(i, 6).value.replace('\n', '').replace('\r', '') encryption = table.cell(i, 7).value.replace('\n', '').replace('\r', '') check_point = table.cell(i, 8).value correlation = table.cell(i, 9).value.replace('\n', '').replace('\r', '').split(';') for key in correlationDict: if request_url.find(key) > 0: request_url = request_url.replace(key, str(correlationDict[key])) if request_data_type == 'Form': dataFile = request_data if os.path.exists(dataFile): fopen = open(dataFile, encoding='utf-8') request_data = fopen.readline() print request_data fopen.close() for keyword in correlationDict: if request_data.find(keyword) > 0: request_data = request_data.replace(keyword, str(correlationDict[keyword])) logging.error(num + ' ' + api_purpose + ' 請求的資料有誤,請檢查[Request Data]欄位是否是標準的json格式字串!') continue elif request_data_type == 'Data': dataFile = request_data if os.path.exists(dataFile): fopen = open(dataFile, encoding='utf-8') request_data = fopen.readline() fopen.close() for keyword in correlationDict: if request_data.find(keyword) > 0: request_data = request_data.replace(keyword, str(correlationDict[keyword])) request_data = request_data.encode('utf-8') status, resp = interfaceTest(num, api_purpose, api_host, request_url, request_data, check_point, request_method, request_data_type, correlationDict['${session}']) if status != 200: errorCase.append((num + ' ' + api_purpose, str(status), api_host+request_url, resp)) continue for j in range(len(correlation)): param = correlation[j].split('=') if len(param) == 2: if param[1] == '' or not re.search(r'^\[', param[1]) or not re.search(r'\]$', param[1]): logging.error(num + ' ' + api_purpose + ' 關聯引數設定有誤,請檢查[Correlation]欄位引數格式是否正確!!!') continue value = resp for key in param[1][1:-1].split(']['): try: temp = value[int(key)] except: try: temp = value[key] except: break value = temp correlationDict[param[0]] = value #print value return errorCase # 介面測試 def interfaceTest(num, api_purpose, api_host, request_url, request_data, check_point, request_method, request_data_type, session): headers = {'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest', 'Connection': 'keep-alive', #'Referer':api_host, #'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36'} 'User-Agent': 'iOS/10.000000;iPhone 5c(A1507);beast/2.4.2.5976', 'Cookie': ''} if session is not None: headers['Cookie'] = 'sessionid=' + session if request_method == 'POST': r = requests.post(api_host+request_url, data=request_data, headers=headers, verify = './ssl/speedx_com.crt') elif request_method == 'GET': r = requests.get(api_host+request_url, verify = './ssl/speedx_com.crt') else: logging.error(num + ' ' + api_purpose + ' HTTPS請求方法錯誤,請確認[Request Method]欄位是否正確!!!') return 400, request_method status = r.status_code resp = r.text #print r.headers if status == 200: resp = resp.decode('unicode_escape')#編碼 if re.search(check_point, str(resp)): logging.info(num + ' ' + api_purpose + ' 成功, ' + str(status) + ', ' + str(resp)) #返回中有空格 try: respdata = json.loads(resp.replace('\n', '')) except Exception as e: print(e) respdata = {'error': str(e)} return status, respdata else: logging.error(num + ' ' + api_purpose + ' 失敗!!!, [ ' + str(status) + ' ], ' + str(resp)) return status, resp else: logging.error(num + ' ' + api_purpose + ' 失敗!!!, [ ' + str(status) + ' ], ' + str(resp)) return status, resp.decode('raw_unicode_escape')####編碼 # 傳送通知郵件 def sendMail(text): sender = '[email protected]' receiver = ['[email protected]', '[email protected]'] mailToCc = ['[email protected]'] subject = '[AutomantionTest]介面自動化測試報告通知' smtpserver = 'smtp.office365.com' username = '[email protected]' password = '123' msg = MIMEText(text, 'html', 'utf-8') msg['Subject'] = subject msg['From'] = sender msg['To'] = ';'.join(receiver) msg['Cc'] = ';'.join(mailToCc) smtp = smtplib.SMTP() smtp.connect(smtpserver, 587) smtp.starttls() smtp.login(username, password) smtp.sendmail(sender, receiver + mailToCc, msg.as_string()) smtp.quit() def main(): errorTest = runTest('./TestCase/TestCase.xlsx') if len(errorTest) > 0: html = '<html><body>介面自動化掃描,共有 ' + str(len(errorTest)) + ' 個異常介面,列表如下:' + '</p><table><tr><th style="width:100px;">介面</th><th style="width:50px;">狀態</th><th style="width:200px;">介面地址</th><th>介面返回值</th></tr>' for test in errorTest: html = html + '<tr><td>' + test[0] + '</td><td>' + test[1] + '</td><td>' + test[2] + '</td><td>' + test[3] + '</td></tr>' html = html + '</table></body></html>' sendMail(html) if __name__ == '__main__': main()

相關推薦

python Excel介面測試

#!/usr/bin/env python # -*- coding:utf-8 -*- #Todo:介面自動化測試 import json import random import time import re import logging impor

excel+python進行介面測試

工作之餘寫了一個超級簡單的excel+python的介面測試指令碼,將多個介面的測試用例寫到表格裡後,指令碼針對單個介面測試它的全用例,然後將返回結果打印出來。之前用postman整合的時候引入excel表格,發現可以跑多個用例,但是我只能看到結果是成功(呈綠色)還是失敗(

python api介面測試---要驗證登入狀態的介面

*** 有些測試系統為了演示多方便,會將登入的校驗去掉。不登入也可以用api 實際的系統需要攜帶正確得到id才能呼叫後面的介面成功 登入的目的是後續的請求中攜帶sessionid,sessionid哪來的?是登入的時候響應訊息裡面建立的。 登入成功後,返回的結果裡有一個set_c

python api介面測試---講解

講解+體會 一般攜帶引數的地方就在,url,訊息頭,訊息體裡面。 訊息頭裡面,沒說就是沒有引數。訊息頭的格式是不用我們關心的,就是www-from-urlencode(鍵值對) 訊息體的格式,看訊息頭裡面的Content-Type import request

python requests介面測試

Python 標準庫中的 urllib2 模組提供了你所需要的大多數 HTTP 功能,但是它的 API 太渣了。它是為另一個時代、另一個網際網路所建立的。它需要巨量的工作,甚至包括各種方法覆蓋,來完成最簡單的任務。 總之,大家以後對urllib2庫敬而遠之就行了。來擁抱Requests吧

學習python介面測試

1、介面測試總結 http://www.cnblogs.com/puresoul/p/5388586.html 2、Jmeter壓測索引 http://www.cnblogs.com/puresoul/p/5092628.html 本文主要關注python做自動化測試 3、

ddt+unittest+Excel介面測試自動化

"""前塵篇:excel讀取資料,資料格式你想要什麼就處理什麼樣""" ReadExcel.py # coding=utf-8 import xlrd import sys import inspect class Excel(object): def __i

利用postman 獲取python 指令碼。使用Python 執行介面測試

開啟postman ,寫好介面後。點選右側的code .選擇Python 選擇requests ,頁面會出現python的指令碼。貼上指令碼,開啟python 貼上指令碼直接執行,此時提示我沒有安裝requests 。第一步:找到 Python的安裝目錄。我的是在C:\Pyt

使用python介面測試

#GET形式呼叫介面 import urllib2 url_save='http://10.253.5.22:8080/tamcx' try:s_save=urllib2.urlopen(url_save).read()print s_save except urllib2

Python介面測試(一)

前言 之前我們已經學會了利用JMeter工具進行介面測試,今天我們學習一下如何利用python進行介面測試。 一:傳送get請求 import requests,json url = 'http://localhost:8080/pinter/com/userList?genderType=0' req=r

Python+Requests+Unittest+Excel 介面自動化測試框架之Request模組01

1.Requests模組  a.Request模組是Python中可以實現模擬Http協議的模組  b.安裝方式很多,可以用pip install requests 2.舉例 import requests class Http_Request:     #定義一個請求函

雷子介面測試框架(基於json格式、http請求)基於Excel檔案管理測試用例(python+requests)【github+原始碼】

這個專案的github地址 基於http請求,json格式測試框架,Excel管理測試用例(北京●雷子(QQ:952943386).rar 介面測試框架(基於json格式、http請求) 注:現在基於Excel檔案管理測試用例基本實現,yaml檔案管

Python操作Excel——單元測試

函數 range init () cas .html tca pre OS 第一步:寫Excel操作方法 excel_operate.py文件 from openpyxl import load_workbook #引入模塊 class MyExcel: d

python接口測試-將運行結果寫入Excel表格

png 程序實現 我沒 bsp image php 生產力 優化 接口 公司工作是促進學習的第一生產力!! 一個get請求的接口,我想清楚的在Excel中看到所有的數據! 帶著學過H5,php覺得所有代碼都很簡單的自信,在公司開發的【鼓勵】下開始了一上午的鬥爭 一個小時

Python測試介面測試的基礎

介面測試基礎   測試對於介面測試的理解總是停留在工具使用層面,很多情況下,測試人員會花很大的代價去學習一個工具,而測試工具本身的侷限性,又導致測試人員陷入想直接用現成的測試框架卻又無法進行擴充套件的僵局,最後由於專案的特殊性等客觀因素,測試人員只能放棄工具,脫離了工具的視覺化介面友好操作,發現直接連線口是

python介面測試-認識POST請求

上午和一個大神交流了一下,給我了一點建議:多做筆記,勤覆盤;及時記錄自己,最好的提升不是來自於別人,而是來自於自身。我覺得挺有道理的,分享出來。共勉 說正事。 今天把post請求的大概內容看了一下。雖然都是post請求,但是還是分類的。看下邊。。   一、POST請求,有請求引數params

python介面測試-認識GET請求

前邊用工具也實現了介面自動化,但是後來很多的時候維護成本有點高。而且靈活上還是有所欠缺的。 於是,自己開始摸索學習敲碼。應該有很多不對的地方或者可以優化的望各位大神勿噴,同時歡迎各位大神評論區發表自己的觀點。 # GET請求有引數時的請求寫法。 import requests import js

Python自動化學習筆記(一)——介面測試基礎

1.1 介面基礎知識  1.1.1    Get&post請求 GET和POST請求:       GET提交的資料會放在URL之後,以?分割URL和傳輸資料,引數之間以&相連,如EditPosts.aspx?name

python 介面測試

GET方法: import urllib2 url_save = 'http://www.baidu.com/' try: s_save = urllib2.urlopen(url_save).read() print s_save except urllib2.HT

介面測試get請求url拼接函式(python)

get請求地址一般是 協議+域名+埠+路徑+引數,除了協議和域名其他均可為空。      http(s)://domain:port/path?key1=value1&key2=value2&... 拼接函式:協議預設http,domain必輸項,port預設空,pat