簡介
本文通過從Postman獲取基本的接口測試Code簡單的接口測試入手,一步步調(diào)整優(yōu)化接口調(diào)用,以及增加基本的結(jié)果判斷,講解Python自帶的Unittest框架調(diào)用,期望各位可以通過本文對接口自動化測試有一個大致的了解。
引言
為什么要做接口自動化測試?
在當(dāng)前互聯(lián)網(wǎng)產(chǎn)品迭代頻繁的背景下,回歸測試的時間越來越少,很難在每個迭代都對所有功能做完整回歸。但接口自動化測試因其實現(xiàn)簡單、維護(hù)成本低,容易提高覆蓋率等特點,越來越受重視。
為什么要自己寫框架呢?
使用Postman調(diào)試通過過直接可以獲取接口測試的基本代碼,結(jié)合使用requets + unittest很容易實現(xiàn)接口自動化測試的封裝,而且requests的api已經(jīng)非常人性化,非常簡單,但通過封裝以后(特別是針對公司內(nèi)特定接口),可以進(jìn)一步提高腳本編寫效率。
一個現(xiàn)有的簡單接口例子
下面使用requests + unittest測試一個查詢接口
接口信息如下
請求信息:
Method:POST
URL:api/match/image/getjson
Request:
{
"category": "image",
"offset": "0",
"limit": "30",
"sourceId": "0",
"metaTitle": "",
"metaId": "0",
"classify": "unclassify",
"startTime": "",
"endTime": "",
"createStart": "",
"createEnd": "",
"sourceType": "",
"isTracking": "true",
"metaGroup": "",
"companyId": "0",
"lastDays": "1",
"author": ""
}
Response示例:
{
"timestamp" : xxx,
"errorMsg" : "",
"data" : {
"config" : xxx
}
Postman測試方法見
測試思路
1.獲取Postman原始腳本
2.使用requests庫模擬發(fā)送HTTP請求**
3.對原始腳本進(jìn)行基礎(chǔ)改造**
4.使用python標(biāo)準(zhǔn)庫里unittest寫測試case**
原始腳本實現(xiàn)
未優(yōu)化
該代碼只是簡單的一次調(diào)用,而且返回的結(jié)果太多,很多返回信息暫時沒用,示例代碼如下
import requests
url = "http://cpright.xinhua-news.cn/api/match/image/getjson"
querystring = {"category":"image","offset":"0","limit":"30","sourceId":"0","metaTitle":"","metaId":"0","classify":"unclassify","startTime":"","endTime":"","createStart":"","createEnd":"","sourceType":"","isTracking":"true","metaGroup":"","companyId":"0","lastDays":"1","author":""}
headers = {
'cache-control': "no-cache",
'postman-token': "e97a99b0-424b-b2a5-7602-22cd50223c15"
}
response = requests.request("POST", url, headers=headers, params=querystring)
print(response.text)
優(yōu)化 第一版
調(diào)整代碼結(jié)構(gòu),輸出結(jié)果Json出來,獲取需要驗證的response.status_code,以及獲取結(jié)果校驗需要用到的results['total']
#!/usr/bin/env python
#coding: utf-8
'''
unittest merchant backgroud interface
@author: zhang_jin
@version: 1.0
@see:http://www.python-requests.org/en/master/
'''
import unittest
import json
import traceback
import requests
url = "http://cpright.xinhua-news.cn/api/match/image/getjson"
querystring = {
"category": "image",
"offset": "0",
"limit": "30",
"sourceId": "0",
"metaTitle": "",
"metaId": "0",
"classify": "unclassify",
"startTime": "",
"endTime": "",
"createStart": "",
"createEnd": "",
"sourceType": "",
"isTracking": "true",
"metaGroup": "",
"companyId": "0",
"lastDays": "1",
"author": ""
}
headers = {
'cache-control': "no-cache",
'postman-token': "e97a99b0-424b-b2a5-7602-22cd50223c15"
}
#Post接口調(diào)用
response = requests.request("POST", url, headers=headers, params=querystring)
#對返回結(jié)果進(jìn)行轉(zhuǎn)義成json串
results = json.loads(response.text)
#獲取http請求的status_code
print "Http code:",response.status_code
#獲取結(jié)果中的total的值
print results['total']
#print(response.text)
優(yōu)化 第二版
接口調(diào)用異常處理,增加try,except處理,對于返回response.status_code,返回200進(jìn)行結(jié)果比對,不是200數(shù)據(jù)異常信息。
#!/usr/bin/env python
#coding: utf-8
'''
unittest merchant backgroud interface
@author: zhang_jin
@version: 1.0
@see:http://www.python-requests.org/en/master/
'''
import json
import traceback
import requests
url = "http://cpright.xinhua-news.cn/api/match/image/getjson"
querystring = {
"category": "image",
"offset": "0",
"limit": "30",
"sourceId": "0",
"metaTitle": "",
"metaId": "0",
"classify": "unclassify",
"startTime": "",
"endTime": "",
"createStart": "",
"createEnd": "",
"sourceType": "",
"isTracking": "true",
"metaGroup": "",
"companyId": "0",
"lastDays": "1",
"author": ""
}
headers = {
'cache-control': "no-cache",
'postman-token': "e97a99b0-424b-b2a5-7602-22cd50223c15"
}
try:
#Post接口調(diào)用
response = requests.request("POST", url, headers=headers, params=querystring)
#對http返回值進(jìn)行判斷,對于200做基本校驗
if response.status_code == 200:
results = json.loads(response.text)
if results['total'] == 191:
print "Success"
else:
print "Fail"
print results['total']
else:
#對于http返回非200的code,輸出相應(yīng)的code
raise Exception("http error info:%s" %response.status_code)
except:
traceback.print_exc()
優(yōu)化 第三版
1.該版本改動較大,引入config文件,單獨封裝結(jié)果校驗?zāi)K,引入unittest模塊,實現(xiàn)接口自動調(diào)用,并增加log處理模塊;
2.對不同Post請求結(jié)果進(jìn)行封裝,不同接口分開調(diào)用;
3.測試用例的結(jié)果進(jìn)行統(tǒng)計并最終輸出
#!/usr/bin/env python
#coding: utf-8
'''
unittest interface
@author: zhang_jin
@version: 1.0
@see:http://www.python-requests.org/en/master/
'''
import unittest
import json
import traceback
import requests
import time
import result_statistics
import config as cf
from com_logger import match_Logger
class MyTestSuite(unittest.TestCase):
"""docstring for MyTestSuite"""
#@classmethod
def sedUp(self):
print "start..."
#圖片匹配統(tǒng)計
def test_image_match_001(self):
url = cf.URL1
querystring = {
"category": "image",
"offset": "0",
"limit": "30",
"sourceId": "0",
"metaTitle": "",
"metaId": "0",
"classify": "unclassify",
"startTime": "",
"endTime": "",
"createStart": "",
"createEnd": "",
"sourceType": "",
"isTracking": "true",
"metaGroup": "",
"companyId": "0",
"lastDays": "1",
"author": ""
}
headers = {
'cache-control': "no-cache",
'postman-token': "545a2e40-b120-2096-960c-54875be347be"
}
response = requests.request("POST", url, headers=headers, params=querystring)
if response.status_code == 200:
response.encoding = response.apparent_encoding
results = json.loads(response.text)
#預(yù)期結(jié)果與實際結(jié)果校驗,調(diào)用result_statistics模塊
result_statistics.test_result(results,196)
else:
print "http error info:%s" %response.status_code
#match_Logger.info("start image_query22222")
#self.assertEqual(results['total'], 888)
'''
try:
self.assertEqual(results['total'], 888)
except:
match_Logger.error(traceback.format_exc())
#print results['total']
'''
#文字匹配數(shù)據(jù)統(tǒng)計
def test_text_match_001(self):
text_url = cf.URL2
querystring = {
"category": "text",
"offset": "0",
"limit": "30",
"sourceId": "0",
"metaTitle": "",
"metaId": "0",
"startTime": "2017-04-14",
"endTime": "2017-04-15",
"createStart": "",
"createEnd": "",
"sourceType": "",
"isTracking": "true",
"metaGroup": "",
"companyId": "0",
"lastDays": "0",
"author": "",
"content": ""
}
headers = {
'cache-control': "no-cache",
'postman-token': "ef3c29d8-1c88-062a-76d9-f2fbebf2536c"
}
response = requests.request("POST", text_url, headers=headers, params=querystring)
if response.status_code == 200:
response.encoding = response.apparent_encoding
results = json.loads(response.text)
#預(yù)期結(jié)果與實際結(jié)果校驗,調(diào)用result_statistics模塊
result_statistics.test_result(results,190)
else:
print "http error info:%s" %response.status_code
#print(response.text)
def tearDown(self):
pass
if __name__ == '__main__':
#image_match_Logger = ALogger('image_match', log_level='INFO')
#構(gòu)造測試集合
suite=unittest.TestSuite()
suite.addTest(MyTestSuite("test_image_match_001"))
suite.addTest(MyTestSuite("test_text_match_001"))
#執(zhí)行測試
runner = unittest.TextTestRunner()
runner.run(suite)
print "success case:",result_statistics.num_success
print "fail case:",result_statistics.num_fail
#unittest.main()
最終輸出日志信息
Zj-Mac:unittest lazybone$ python image_test_3.py
測試結(jié)果:通過
.測試結(jié)果:不通過
錯誤信息: 期望返回值:190 實際返回值:4522
.
----------------------------------------------------------------------
Ran 2 tests in 0.889s
OK
success case: 1
fail case: 1
后續(xù)改進(jìn)建議
1.unittest輸出報告也可以推薦使用HTMLTestRunner(我目前是對結(jié)果統(tǒng)計進(jìn)行了封裝)
2.接口的繼續(xù)封裝,參數(shù)化,模塊化
3.unittest單元測試框架實現(xiàn)參數(shù)化調(diào)用第三方模塊引用(nose-parameterized)
4.持續(xù)集成運(yùn)行環(huán)境、定時任務(wù)、觸發(fā)運(yùn)行、郵件發(fā)送等一系列功能均可以在Jenkins上實現(xiàn)。文章來源:http://www.zghlxwxcb.cn/news/detail-727133.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-727133.html
到了這里,關(guān)于簡單實現(xiàn)接口自動化測試(基于python+unittest)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!