python – 接口自动化测试实战 – case1 – 再次优化版

 

本次优化:

  1.  各级分Package

  2.  封装【ReadExcel】类

  3.  封装【ReadConfig】类

  4.  封装【GetLog】类

  5.  引入ddt数据驱动测试,优化测试用例代码

 

工程如下:

 

 

代码分享:

 

get_logger.py

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

'''
@project: jiaxy
@author: Jimmy
@file: get_logger.py
@ide: PyCharm Community Edition
@time: 2018-12-08 16:08
@blog: https://www.cnblogs.com/gotesting/

'''

import logging
import time

class GetLog:

    def __init__(self):
        curTime = time.strftime('%Y-%m-%d')
        self.logname = 'TestReport/log/' + 'AutoTest' + '_' + curTime + '_' + '.log'

    def get_log(self,level,msg):

        # 创建日志收集器
        logger = logging.getLogger()
        logger.setLevel('DEBUG')

        # 创建handler
        fh = logging.FileHandler(self.logname,'a',encoding='gbk')
        fh.setLevel('INFO')
        ch = logging.StreamHandler()
        ch.setLevel('INFO')

        # 定义handler的输出格式
        formatter = logging.Formatter('%(asctime)s - %(filename)s - %(name)s - %(levelname)s - 日志信息: %(message)s')
        ch.setFormatter(formatter)
        fh.setFormatter(formatter)

        # 给logger添加handler
        logger.addHandler(fh)
        logger.addHandler(ch)


        if level == 'DEBUG':
            logger.debug(msg)
        elif level == 'INFO':
            logger.info(msg)
        elif level == 'WARNING':
            logger.warning(msg)
        elif level == 'ERROR':
            logger.error(msg)
        elif level == 'CRITICAL':
            logger.critical(msg)

        logger.removeHandler(fh)
        logger.removeHandler(ch)
        fh.close()

    def log_debug(self,msg):
        self.get_log('DEBUG',msg)

    def log_info(self,msg):
        self.get_log('INFO',msg)

    def log_warning(self,msg):
        self.get_log('WARNING',msg)

    def log_error(self,msg):
        self.get_log('ERROR',msg)

    def log_critical(self,msg):
        self.get_log('CRITICAL',msg)

 

http_request.py

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

'''
@project: jiaxy
@author: Jimmy
@file: http_request.py
@ide: PyCharm Community Edition
@time: 2018-12-05 10:06
@blog: https://www.cnblogs.com/gotesting/

'''

import requests

class HttpRequest:

    def http_request(self,url,param,method,cookies=None):
        if method == 'get':
            res = requests.get(url,param,cookies = cookies)
        elif method == 'post':
            res = requests.post(url,param,cookies = cookies)
        else:
            print('请求方法错误!')
        return res

 

read_config.py

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

'''
@project: jiaxy
@author: Jimmy
@file: read_config.py
@ide: PyCharm Community Edition
@time: 2018-12-08 14:45
@blog: https://www.cnblogs.com/gotesting/

'''

import configparser

class ReadConfig:

    def read_config(self,file,section,option):
        cf = configparser.ConfigParser()
        cf.read(file)
        value = cf.get(section,option)
        return value

 

read_excel.py

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

'''
@project: jiaxy
@author: Jimmy
@file: read_excel.py
@ide: PyCharm Community Edition
@time: 2018-12-05 11:57
@blog: https://www.cnblogs.com/gotesting/

'''

from openpyxl import load_workbook

class ReadExcel:

    def read_excel(self,wbname,sheetname):
        wb = load_workbook(wbname)
        sheet = wb[sheetname]

        # 双重for循环 获取excel表中测试数据
        test_data = []
        for i in range(2,sheet.max_row+1):
            sub_data = {}
            for j in range(1,sheet.max_column+1):
                sub_data[sheet.cell(1,j).value] = sheet.cell(i,j).value
            test_data.append(sub_data)

        return test_data

 

test_api.py

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

'''
@project: jiaxy
@author: Jimmy
@file: TestApi.py
@ide: PyCharm Community Edition
@time: 2018-12-05 10:09
@blog: https://www.cnblogs.com/gotesting/

'''

import unittest
from ddt import ddt,data
from TestApi.Common.http_request import HttpRequest
from TestApi.Common.read_excel import ReadExcel
from TestApi.Common.get_logger import GetLog


cookies = None
login_data = ReadExcel().read_excel('TestData/test_login.xlsx','登录及充值测试数据')

@ddt
class TestHttpApi(unittest.TestCase):

    def setUp(self):
        self.log = GetLog()

    def tearDown(self):
        pass

    # # 改写__init__方法,使用超继承
    # def __init__(self,url,param,method,expected,methodName):
    #     self.url = url
    #     self.param = param
    #     self.method = method
    #     self.expected = expected
    #     super(TestHttpApi,self).__init__(methodName)

    # 换用data来处理test_data
    @data(*login_data)
    def test_api(self,item):
        global cookies
        self.log.log_info('执行第{0}条测试用例:{1}'.format(item['case_id'],item['title']))
        res = HttpRequest().http_request(item['url'],eval(item['param']),item['method'],cookies)
        self.log.log_info('请求结果:{0}'.format(res.json()))
        if res.cookies:
            cookies = res.cookies
        try:
            self.assertEquals(item['excepted'],res.json()['msg'])
            self.log.log_info('测试结果:PASSED')
        except AssertionError as e:
            self.log.log_error('断言异常:{0}'.format(e))
            self.log.log_error('测试结果:FAILED')
            raise e

 

test_run.py

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

'''
@project: jiaxy
@author: Jimmy
@file: test_run.py
@ide: PyCharm Community Edition
@time: 2018-12-05 10:28
@blog: https://www.cnblogs.com/gotesting/

'''

import unittest
import HTMLTestRunner
import time
from TestApi.TestCses.test_api import TestHttpApi



# 加载测试集
def run_test():
    suite = unittest.TestSuite()
    loader = unittest.TestLoader()
    suite.addTest(loader.loadTestsFromTestCase(TestHttpApi))

    curTime = time.strftime('%Y-%m-%d_%H_%M_%S')
    report_name = 'TestReport/report/' + 'TestResult-' + curTime + '.html'

    # 执行测试,输出测试报告
    with open(report_name,'wb+') as file:
        runner = HTMLTestRunner.HTMLTestRunner(stream=file,
                                               verbosity=2,
                                               title='接口测试报告',
                                               description='基于python+unittest进行的数据驱动接口自动化测试',
                                               tester='Jimmy')
        runner.run(suite)


if __name__ == '__main__':
    run_test()

 

 

 

测试报告:

 

测试日志: