1. 程式人生 > 實用技巧 >【介面自動化】Python+Requests介面自動化測試框架搭建【二】

【介面自動化】Python+Requests介面自動化測試框架搭建【二】

接續前文,在上篇部落格中我們編寫了demo.py程式碼,裡面程式碼過多冗餘,更新程式碼:

#!/usr/bin/env python
# coding=utf-8

import requests


class RunMain:
    def __init__(self):
        pass

    @staticmethod
    def send_post(url,cookies,headers,params=None):
        try:
            res = requests.post(url=url,cookies=cookies,headers=headers,data=params)
return res.status_code except Exception as msg: return msg @staticmethod def send_get(url,cookies,headers,params=None,): try: res = requests.get(url=url,cookies=cookies,headers=headers,params=params,)return res.status_code except Exception as msg:
return msg def run_main(self, url, method,cookies=None,headers=None,params=None): if method == 'GET': res = self.send_get(url,cookies,headers,params) return res elif method == 'POST': res = self.send_post(url,cookies,headers,params)
return res else: print('不支援的請求方式!')

接下來我們採用Unittest框架進行搭建,使用ddt註解進行引數化。

#!/usr/bin/env python
# -*- coding:utf-8
from ddt import ddt,data,unpack
from Demo.demo import RunMain
import unittest
from urllib import parse
@ddt
class excelddt(unittest.TestCase):
    @data(
        [1, 'http://apis.juhe.cn/mobile/get', 'GET','{"phone":"13800000000","dtype":"json","key":"密匙"}', '', '', 200, '','Yes'],
        [2, 'http://apis.juhe.cn/simpleWeather/query', 'POST','{"city": "濟南","key": "密匙"}', '', '', 200, '', 'Yes']
    )
    @unpack
    def testURL(self,id,url,method,params,headers,cookies,code,returns,run):
        t=RunMain().run_main(url=url, method=method,headers=headers, params=params)
        print(t)
        self.assertEqual(t,code)


if __name__ == '__main__':
    unittest.main()

使用ddt引數化是為了進行excel取值,我們執行一下。

出現錯誤了,POST請求返回值異常。這個問題困擾了兩天,無奈放棄,到最後也沒分析出來結果。

更換pytest,用@pytest.mark.parametrize註解試試

import pytest
from Demo.demo import RunMain
@pytest.mark.parametrize(
    "ID,URL,METHOD,PARAMS,HEADERS,COOKIES,RETURNCODE,RETURNTXT,YN",
    [(1,"http://apis.juhe.cn/mobile/get",'GET',{"phone": "13800000000","dtype": "json","key": "x"},{"Content-Type":"application/json"},'',200,'','Yes'),
     (2,"http://apis.juhe.cn/simpleWeather/query",'POST',{"city": "濟南","key": "x"},{"Content-Type":"application/json"},'',200,'','No'),
     (3,"http://apis.juhe.cn/simpleWeather/query",'POST',{"city": "濟南","key": "x"},{"Content-Type":"application/json"},'',200,'','Yes'),
     (4,"http://www.3wyuming.xyz:8080/BBSProject/userServlet.do",'GET',{"account": "x","pwd": "x"},{"Content-Type":"application/json"},'',200,'','Yes'),
     (5,"http://www.3wyuming.xyz:8080/BBSProject/textServlet.do",'GET',{"md":"read","pid":"8"},{"Content-Type":"application/json"},'',200,'','Yes')],
    ids=["case1","case2","case3","case4","case5"]
)
def test_url(ID,URL,METHOD,PARAMS,HEADERS,COOKIES,RETURNCODE,RETURNTXT,YN):
    t = RunMain().run_main(url=URL, method=METHOD, headers=HEADERS, params=PARAMS)
    assert t == RETURNCODE
if __name__ == '__main__':
    pytest.main()

執行程式碼:

執行成功。

總結一下用引數化遇到的坑:

1.Unittest,ddt引數化,一直報錯字元異常,返回值返回的為異常錯誤,導致斷言失敗。事後發現應該是中文問題。

2.Pytest,引數化中也是報錯,具體錯誤是str沒有item屬性,我在Test.py裡面傳送請求一直正常狀態,為什麼使用引數化就會異常,轉換思路,考慮到資料問題。打入斷點,Debug尋找問題,發現Test.py裡json格式資料型別都是dict,

但是引數化中屬於str型別,於是知道,將資料中的{}括號放置於引號外面,傳送請求,成功。