python接口自动化:requests+ddt+htmltestrunner数据驱动框架

一、xc_datas:存放数据,xc_report:存放生成的报告,xc_tools:存放一些工具,get_api.py为执行程序

  

 二、执行程序的实现代码如下:

#无token情况下,只支持get、post请求
import unittest
from HTMLTestRunner import HTMLTestRunner
from ddt import ddt,data
from xctest_api.xc_tools.get_CutString import *
from xctest_api.xc_tools.get_ReadExcel import *
import requests
import time

@ddt
class get_apitest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        print('测试开始')
        cls.s=requests.session()
    @classmethod
    def tearDownClass(cls):
        print('测试结束')
    def test_login(self):
        lo=ReadExcel().read_excel('./xc_datas/login_data.xlsx')
        if lo[3] == 'post':
            result = self.s.post(lo[2], get_string().cut_string(lo[5]))
            self.assert_login(lo[8],result.text)
        elif lo[3]=='get':
            result = self.s.get(lo[2])
            self.assert_login(lo[8], result.text)
        else:
            print('暂无此请求类型方法')
    @data(*ReadExcel().read_excel('./xc_datas/api_data.xlsx'))
    def test_start(self, li):
        if li[3] == 'post':
            self.post_requests(li[4],li)
        elif li[3] == 'get':
            result = self.s.get(li[2])
            self.assertIn(li[8], result.text)
        else:
            print('暂无此请求类型方法')
    def assert_login(self,a,b):
        if a in b.text:
            print('登录成功')
        else:
            print('登录失败')

    def post_requests(self,c,li):
        if c == 'application/x-www-form-urlencode':
            result = self.s.post(li[2], get_string().cut_string(li[5]))
            self.assertIn(li[8], result.text)
        elif c == 'application/json':
            result = self.s.post(li[2], json=get_string().cut_string(li[5]))
            self.assertIn(li[8], result.text)
        elif c == 'text/xml':
            result = self.s.post(li[2], get_string().cut_string(li[5]).encode('utf-8'))
            self.assertIn(li[8], result.text)
        elif c == 'multipart/form-data':
            if li[6]=='':
                result = self.s.post(li[2],get_string().cut_string(li[5]))
                self.assertIn(li[8], result.text)
            else:
                result = self.s.post(li[2], get_string().cut_string(li[5]),files=li[6])
                self.assertIn(li[8], result.text)
        else:
            print('暂无此数据类型方法')

if __name__ == '__main__':
    suite = unittest.TestSuite()
    suite.addTests(unittest.TestLoader().loadTestsFromTestCase(get_apitest))
    name=time.strftime('%Y%m%d%H%M%S')
    f = open('./xc_report/%d.html'%name, 'wb')
    r = HTMLTestRunner(stream=f, title=u'EMS1.5', description=u'测试报告')
    r.run(suite)
    f.close()
原文地址:https://www.cnblogs.com/badbadboyyx/p/12013358.html