ddt模块封装测试数据,生成HTML测试报告

小白一枚,初次学习Python,写的不好,???

为了见证学习中的成长还是记录一些笔记为好,过程中有学习的乐趣,当然也有太多的坑去填....不多说废话

ddf安装:

pip install ddt

首先,为了做自动化测试创建一个类,写了一个request的函数

import requests


class keepInterface:

    def keep_interface(self,url,data,http_method):

        if http_method.upper() == 'POST':
            try:
                res = requests.post(url,json=data,verify=False)
            except Exception as e:
                print('post请求出现了异常:{}'.format(e))
        else:
            try:
                res = requests.get(url,json=data,verity=False)
            except Exception as e:
                print('get请求出现了异常:{}'.format(e))

        # print("请求的结果是:{}".format(res.json()))
        return res.json()

使用ddt模块封装测试数据

这里使用了openpyxl读写Excel数据

import unittest
from sport_auto_test.common.do_excel import doExcel
from sport_auto_test.common.api import keepInterface
from ddt import ddt,data

'''测试类'''

test_data = doExcel('/.../.../***.xlsx','sheet_data').do_excel()

@ddt
class testApi(unittest.TestCase):

    def setUp(self):
        print('开始测试了!!!')
        # 创建一个Excel操作实例
        self.writeBack = doExcel('/.../.../***.xlsx','sheet_data')

    @data(*test_data)
    def test_apiTest(self,item):
        print('正在运行第{}条用例:{}'.format(item['id'],item['title']))
        print('测试数据是:{}'.format(item['param']))
        # res = requests.post(item['URL'],eval(item['param']),verify=False)
        
        res = keepInterface().keep_interface(item['URL'],eval(item['param']),item['HttpRequest'])
        # print(res)
        # 加断言
        try:
            self.assertEqual(str(item['expectResult']),str(res['status']))
            testResult = 'PASS'
        except Exception as e:# 断言异常
            testResult = 'failed'
            raise e
        finally:# 最终都要写回Excel里面
            self.writeBack.write_back(item['id']+1,res['status'],testResult)

    def tearDown(self):
        print('测试结束了')

最后,最后生成HTML报告

import unittest,HTMLTestRunner
from sport_auto_test.common.apiTest import testApi

# 加载测试套件
suite = unittest.TestSuite()
# 加载测试类
loder = unittest.TestLoader()
# 把测试用例放到测试套件里
suite.addTest(loder.loadTestsFromTestCase(testApi))
# 创建testReport.html存放测试报告
with open('/.../testReport.html','wb') as testReport:
    runner = HTMLTestRunner.HTMLTestRunner(stream=testReport, verbosity=2,title='requestTest',description='测试用套件执行',tester='Cody')
    # 运行测试套件
    runner.run(suite)

 

你可能感兴趣的:(python自动化,HTMLTestRunner,requests,Python,requests,HTMLTestRunner,openpyxl,Python自动化)