Python 接口測試實踐(Requests)-用例封裝及測試報告生成

作者:桃子

今天以天氣API接口為例,使用python語言實現(xiàn)用例編寫、封裝及報告生成功能

API信息:

天氣API:https://www.sojson.com/blog/305.html

URL:http://t.weather.sojson.com/api/weather/city/101030100

請求方式:get

參數(shù):city 城市名稱

一? 代碼實現(xiàn)查詢北京的天氣信息

步驟:

1.新建 weather_api_test.py文件

代碼實現(xiàn)

#-*-coding:GBK -*-

import requests

from pip._vendor.requests.models import Response

url='http://t.weather.sojson.com/api/weather/city/101030100'

r=requests.get(url)

response_data=r.json()

print(r.text)

返回結(jié)果:


二? 用例集成到Unittest

1.針對不同的參數(shù)場景進行測試

2.設(shè)置斷言判斷執(zhí)行結(jié)果是否符合預(yù)期

實現(xiàn)原理:

首先導(dǎo)入requests 庫、unitest 、時間庫

其次,創(chuàng)建天氣class類

然后,分別創(chuàng)建4個函數(shù),分別實現(xiàn)存放路徑、正常傳參、異常傳參、缺省參數(shù)功能

3.用例設(shè)計

代碼實現(xiàn):

新建 weather_api_unitest.py文件

#-*-coding:GBK -*-

import unittest

import requests

from time import sleep

class weathertest(unittest.TestCase):

? ? def setUp(self):

? ? ? ? self.url='http://t.weather.sojson.com/api/weather/city/101030100'

? ? ? ? self.url_error='http://t.weather.sojson.com/api/weather/city/101030101'

? ? ? ? self.url_no='http://t.weather.sojson.com/api/weather/city'

? ? #參數(shù)正常

? ? def test_weather_tianjing(self):

? ? ? ? r=requests.get(self.url)

? ? ? ? result=r.json()

? ? ? ? self.assertEqual(result['status'],200)

? ? ? ? self.assertEqual(result['message'],'success感謝又拍云(upyun.com)提供CDN贊助')

? ? ? ? sleep(3)

? ? #參數(shù)異常

? ? def test_weather_param_error(self):

? ? ? ? r=requests.get(self.url_error)

? ? ? ? result=r.json()

? ? ? ? self.assertEqual(result['status'],400)

? ? ? ? self.assertEqual(result['message'],'獲取失敗')

? ? ? ? sleep(3)

? ? #參數(shù)缺省

? ? def test_weather_no_param(self):

? ? ? ? r=requests.get(self.url_no)

? ? ? ? result=r.json()

? ? ? ? self.assertEqual(result['status'],404)

? ? ? ? self.assertEqual(result['message'],'Request resource not found.')

? ? ? ? sleep(3)? ? ?


? ? if __name__=='_main_':

? ? ? ? unittest.main()


三 測試報告生成

1.創(chuàng)建文件夾如圖,把測試用例放到test_case目錄下

2.下載BSTestRunner模塊并放置到python Lib文件夾下

如路徑 C:\Python34\Lib

3.創(chuàng)建run.py 文件

代碼:

import unittest

from BSTestRunner import BSTestRunner

import time

#指定測試用例和報告路徑

test_dir='./test_case'

report_dir='./reports'

#加載測試用例

discover=unittest.defaultTestLoader.discover(test_dir, pattern='weather_api_unittest.py')

#定義報告格式

now=time.strftime('%Y-%m-%d %H_%M_%S')

report_name=report_dir+'/'+now+'test_report.html'

#運行用例并生成測試報告

with open(report_name,'wb') as f:

? ? runner=BSTestRunner(stream=f,title="weather api test report",description="china city weather test report")

? ? runner.run(discover)


4.運行run.py,在reports文件夾下查看生成的報告



?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容