在测试接口时,一个接口会先写好测试用例,这个用例主要针对功能,传入参时考虑到各种场景,正常的,异常的,如:参数缺省,参数传一个六位数字写用例时考虑边界情况等。

一个接口设计用例时有可能会十几条到几十条都有可能,多个接口就有很多了,这时候我们可以考虑到自动化测试接口。

采用数据驱动方式,把数据写在excel表格中,代码做封装,用数据驱动测试,两部分相互独立。python中用ddt模块来做数据驱动,代码简单好维护,调试也方便。

自己写的框架,结构如下:

common:公共层,放读取表格数据,发送request请求,生成测试报告的.py文件

data:放excel数据

report:放测试报告

testcase:写测试用例

run_main.py:运行用例并生成测试报告

 

HTMLTestRunner.py文件是从网上下载的模板,可以直接使用。

readExcel.py读取表格数据,返回的是一个列表,里面的数据以字典格式存放,通过索引得到字典然后取字典的值

 1  #! /usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 """
 5 @version: 1.0
 6 @author: fky
 7 @site: 
 8 @software: PyCharm
 9 @file: readExcel.py
10 @time: 2018/3/24 9:37
11 """
12 import xlrd
13 
14 class ReadExcel():
15      def readExcel(fileName,SheetName="Sheet1"):
16          data = xlrd.open_workbook(fileName)
17          table = data.sheet_by_name(SheetName)
18 
19          #获取总行数、总列数
20          nrows = table.nrows
21          ncols = table.ncols
22          if nrows > 1:
23              #获取第一列的内容,列表格式
24              keys = table.row_values(0)
25              #print(keys)
26 
27              listApiData = []
28              #获取每一行的内容,列表格式
29              for col in range(1,nrows):
30                  values = table.row_values(col)
31                  # keys,values这两个列表一一对应来组合转换为字典
32                  api_dict = dict(zip(keys, values))
33                  #print(api_dict)
34                  listApiData.append(api_dict)
35 
36              return listApiData
37          else:
38              print("表格未填写数据")
39              return None
40 
41 if __name__ == '__main__':
42     s = ReadExcel.readExcel("E:\\fukun_apitest\\data\\yoyo_apiTest.xlsx","Sheet1")
43     print(s)

 

sendRequest.py中的文件,读取表格的数据作为request请求的参数:

# -*- coding:utf-8 -*-

"""
@version: 1.0
@author: fky
@site:
@software: PyCharm
@file: sendRequests.py
@time: 2018/3/24 11:40
"""
from common.readExcel import ReadExcel
import requests
import json
class SendRequests():
    def sendRequests(self,s,apiData):
        try:
            #从读取的表格中获取响应的参数作为传递
            method = apiData["method"]

            url = apiData["url"]

            if apiData["params"] == "":
                par = None
            else:
                par = eval(apiData["params"])

            if apiData["headers"] == "":
                h = None
            else:
                h = apiData["headers"]


            if apiData["body"] == "":
                body_data = None
            else:
                body_data = eval(apiData["body"])

            type = apiData["type"]

            v = False

            if type == "json":
                body = json.dumps(body_data)
            if type == "data":
                body = body_data
            else:
                body = body_data

            #发送请求
            re = s.request(method=method,url=url,headers=h,params=par,data=body,verify=v)
            return re

        except Exception as e:
            print(e)

if __name__ == '__main__':
    s = requests.session()
    testData = ReadExcel.readExcel("apiTest.xlsx", "Sheet1")
    response = SendRequests().sendRequests(s,testData[3])
    print(response.json())


 

用例部分(case_01_yoyo.py)

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

"""
@version: 1.0
@author: fky
@site:
@software: PyCharm
@file: case_01.py
@time: 2018/3/16 10:58
"""
import unittest
import requests
from ddt import ddt,data,unpack
from common.sendRequests import SendRequests
from common.readExcel import ReadExcel
import os

# path = os.path.dirname(os.getcwd())+"\\data\\yoyo_apiTest.xlsx"
# print(path)
testData = ReadExcel.readExcel("E:\\fukun_apitest\\data\\yoyo_apiTest.xlsx", "Sheet1")
@ddt
class Test1(unittest.TestCase):

    def setUp(self):
        self.s = requests.session()

    def tearDown(self):
        pass

    @data(*testData)
    def test_yoyo_api(self,data):

        re = SendRequests().sendRequests(self.s, data)
        #print(re.json())

        #切割字符串取后面的部分
        expect_result1 = data["expect_result"].split(":")[1]
        #转换为字符串
        expect_result = eval(expect_result1)
        #断言
        self.assertEqual(re.json()["origin"], expect_result, "返回错误,实际结果是%s"%re.json()["origin"])


if __name__ == '__main__':

    unittest.main()

 

run_main.py,跑用例最后生成测试报告:

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

"""
@version: 1.0
@author: fky
@site: 
@software: PyCharm
@file: run_main.py
@time: 2018/3/16 10:58
"""
import unittest
import  time
import os
from common.HTMLTestRunner_jpg import HTMLTestRunner

def run_case(dir = "testcase"):
    case_dir = os.getcwd() + "\\" + dir
    print(case_dir)
    test_case = unittest.TestSuite()
    discover = unittest.defaultTestLoader.discover(case_dir,pattern="case_01_yoyo.py",top_level_dir=None)
    return  discover
if __name__ == '__main__':

    current_time = time.strftime("%Y-%m-%d-%H_%M_%S", time.localtime(time.time()))
    report_path =os.getcwd() + "\\report\\" + current_time + '.html'  # 生成测试报告的路径
    print(report_path)
    fp = open(report_path, "wb")
    runner = HTMLTestRunner(stream=fp, title=u"自动化测试报告", description=u'yoyo接口',verbosity=2)
    runner.run(run_case())
    fp.close()

 

 

报告结果:

 

版权声明:本文为fukun原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/fukun/p/8671718.html