工具包介绍

Excel:用于存储测试用例;
requests:接口测试框架,发送请求;
unittest:单元测试框架,用于包装接口测试用例;
ddt:Data-Driven Tests;
yagmail:发送测试报告邮件的库;
xlrd:读取 Excel 文件;
HTMLTestReportCN:生成测试报告模板

1,按行读取 Excel 文件中的测试用例

class ExceHandle():

  def __init__(self,word_path,sheet_name):
      '''

      :param word_path: Excel文件路径
      :param sheet_name: sheet名称
      '''
      self.workBook = xlrd.open_workbook(word_path)
      self.table = self.workBook.sheet_by_name(sheet_name)
      self.col_nums = self.table.ncols
      self.row_nums = self.table.nrows
      self.row_value = self.table.row_values(0)

  def testcase_date(self):
      result = []
      swift_dict = {}
      for i in range(self.row_nums-1):
          row_data = self.table.row_values(i+1)
          for j in range(self.col_nums):
              swift_dict[self.row_value[j]] = row_data[j]
          if swift_dict:
              result.append(swift_dict)
              swift_dict = {}
      return result

2,根据返回的数据获取对应接口的测试用例

class DataSet():

    @classmethod
    def get_test_date(self,work_path,sheet_name,testcaseName):
        '''

        :param work_path: 测试用例路径
        :param sheet_name: Excelsheet名称
        :param testcaseName: 测试用例名称
        :return:
        '''
        result = ExceHandle(work_path,sheet_name)
        testDate = result.testcase_date()
        testDateSet = []
        for i in range(len(testDate)):
            if testDate[i]['TestCaseName'] == testcaseName and testDate[i]['Execute']:
                testDateSet.append(testDate[i])
        return testDateSet

3,编辑统一接口方法

import requests
import json

class TestRequests():

    @classmethod
    def test_requests(self,url,method='',header='',data=''):
        if data:
            data = json.loads(data)
        self.response = requests.request(url=url,method=method,headers=header,data=data)
        return self.response

4,编辑前置接口类

import requests
import json

class FrontInterface():

    @classmethod
    def getLoginUserInfo(self,url_getInfo,method_getInfo='',data_getInfo=''):
        if data_getInfo:
            data_getInfo = json.loads(data_getInfo)
        self.head = {}
        getLoginUrl = url_getInfo + 'getLoginUserInfo'
        response =  requests.request(url=getLoginUrl,method=method_getInfo,data=data_getInfo)
        one = response.headers['Set-Cookie'].split(";")
        result = one[1].split(",")
        self.head['Cookie'] = result[2].strip()
        return self.head

    @classmethod
    def dict_interface_count(self):
        dict_interface = {}
        dict_interface['getLoginUserInfo'] = self.getLoginUserInfo
        return dict_interface

5,测试用例【登录接口为例】

import unittest
import ddt
import json

from TestTool.get_test_date import DataSet
from TestInterface.front_interface import FrontInterface
from TestInterface.test_requests import TestRequests

#读取测试用例数据
test_data = DataSet.get_test_date("TestInterface\TestDate\TestDataSet.xlsx",'TestDataSet','login')

@ddt.ddt
class LoginCase(unittest.TestCase):

    def setUp(self):
        data = json.loads(test_data[0]['RequestFrontInterface'])
        dict_interface = FrontInterface.dict_interface_count()
        for key,value in dict_interface.items():
            if key == data[key]:
                url_front = test_data[0]['RequestUrl']
                self.head = dict_interface[key](url_front,test_data[0]['RequestWays'],test_data[0]['RequestFrontData'])
                return self.head

    @ddt.data(*test_data)
    def test_login(self,data):
        url_login = data['RequestUrl']+data['RequestInterface']
        print(self.head)
        responses = SwiftpassRequests.test_requests(url_login,data['RequestWays'],self.head,data['RequestData'])
        value = responses.json()['success']
        self.assertEqual(value,data['ExceptResult'])

6,编写运行器

import yagmail
import unittest
import HTMLTestReportCN
import time
import os

discover = unittest.defaultTestLoader.discover('TestCase',pattern='test_*.py')
suite = unittest.TestSuite()
suite.addTest(discover)
now_time = time.strftime("%Y_%M_%d_%H_%M_%S")
now = time.strftime("%Y%m%d")
dir = os.getcwd() + '/' + now
if not os.path.exists(dir):
    os.mkdir(dir)

file_dir = dir + '/' + now_time + '_report.html'
report_html = open(file_dir,'wb')
runner = HTMLTestReportCN.HTMLTestRunner(report_html)
runner.run(suite)
report_html.close()

#结合yagmail包,实现发送邮件功能
#注意,网易个人邮箱,password应填入授权码值
yag = yagmail.SMTP(user='emailuser',password='password',host='smtp.exmail.qq.com')
yag.send(to='emailuser',subject="接口自动化测试报告",contents=[file_dir])

写在最后:希望大家不吝赐教,多多指出我的问题和不足,感谢!


↙↙↙阅读原文可查看相关链接,并与作者交流