unittest项目实战阶段总结
2019-12-16 本文已影响0人
我是孟小鱼呀
测试阶段目标
1、引入单元测试、HTML测试报告、断言结果
2、引入超继承
3、引入ddt
4、添加一个字段存入测试结果。执行错误怎么写回结果?
5、引入try...except...finally
6、完成用例的可配置:想跑哪条跑哪条,就在配置文件里写好,难点:如何考虑多模块的情况?
7、实现路径的可配置
项目配置框架图
# -*-coding: utf8 -*-
import requests
class HttpRequest(object):
def http_request(self, url, data, method, expected=None, cookie=None):
if method.lower() == 'get':
res = requests.get(url, data=None, cookies=cookie, verify=False)
else:
res = requests.post(url, data, cookies=cookie, verify=False)
return res
project_path.py
实现路径的可配置,避免相对路径的使用。方便他人使用。
# -*-coding: utf8 -*-
import os
# path = os.path.realpath(__file__)
# print(path)
#路径切割获取先最大的目录
project_path = os.path.split(os.path.split(os.path.realpath(__file__))[0])[0]
#测试数据路径
test_case_path = os.path.join(project_path, 'data_http.xlsx')
#测试报告路径
test_report_path = os.path.join(project_path, 'test_http_report.html')
#配置文件路径
case_config_path = os.path.join(project_path, 'http_case.config')
test_http_request.py
引入unittest模块,引入断言,判断测试数据结构。
# -*-coding: utf8 -*-
import unittest
from practise.utils.http_request import HttpRequest
from practise.utils.get_data import GetData
from ddt import ddt, data
from practise.do_excel_http import DoExcel
from practise.utils.project_path import *
test_data = DoExcel.get_data(test_case_path)
@ddt
class TestHttpRequest(unittest.TestCase):
def setUp(self):
pass
@data(*test_data)
def test_api(self, item):
res = HttpRequest().http_request(item['url'], eval(item['data']), item['method'], item['expected'], getattr(GetData, 'Cookie'))
if res.cookies:
setattr(GetData, 'Cookie', res.cookies) #利用反射存储cookie值
try:
self.assertEqual(item['expected'], res.json()['info'])
TestResult = 'PASS'
except AssertionError as e:
TestResult = 'Falied'
print('执行用例出错:{0}'.format(e))
raise e
finally:#不管对还是错,它里面的代码是肯定会执行的
DoExcel.write_back(test_case_path, item['sheet_name'], item['case_id']+1, str(res.json()), TestResult)
print('获取的结果是{0}'.format(res.json()))
def tearDown(self):
pass
run.py
引入HTML测试报告,直观展示测试结果
# -*-coding: utf8 -*-
import unittest
from HTMLTestRunner import HTMLTestRunner
# from HtmlTestRunner import HTMLTestRunner
from practise.test_http_request import TestHttpRequest
suite = unittest.TestSuite()
loader = unittest.TestLoader()
suite.addTest(loader.loadTestsFromTestCase(TestHttpRequest))
with open('test_http_report.html', 'wb') as file:
runner = HTMLTestRunner(
stream=file,
verbosity=2,
title='test_api的测试',
description='test_api的测试')
runner.run(suite)
do_excel_http.py
读取excel表内数据,通过配置文件实现用例可配置
# -*-coding: utf8 -*-
from openpyxl import load_workbook
from practise.utils.project_path import *
from practise.read_http_config import ReadConfig
class DoExcel(object):
@staticmethod
def get_data(file_name):
wb = load_workbook(file_name)
mode = eval(ReadConfig.get_config(case_config_path, 'MODE', 'mode'))
test_data = []
for key in mode:
sheet = wb[key]
if mode[key] == 'all':
for row in range(2, sheet.max_row + 1):
sub_data = {}
sub_data['case_id'] = sheet.cell(row, 1).value
sub_data['url'] = sheet.cell(row, 2).value
sub_data['data'] = sheet.cell(row, 3).value
sub_data['expected'] = sheet.cell(row, 4).value
sub_data['method'] = sheet.cell(row, 5).value
sub_data['sheet_name'] = key
test_data.append(sub_data)
else:
for case_id in mode[key]:
sub_data = {}
sub_data['case_id'] = sheet.cell(case_id+1, 1).value
sub_data['url'] = sheet.cell(case_id+1, 2).value
sub_data['data'] = sheet.cell(case_id+1, 3).value
sub_data['expected'] = sheet.cell(case_id+1, 4).value
sub_data['method'] = sheet.cell(case_id+1, 5).value
sub_data['sheet_name'] = key
test_data.append(sub_data)
return test_data
@staticmethod
def write_back(file_name, sheet_name, row, result, TestResult):#把结果写回表内
wb = load_workbook(file_name)
sheet_name = wb[sheet_name]
sheet_name.cell(row, 6).value = result
sheet_name.cell(row, 7).value = TestResult
wb.save(file_name)
if __name__ == '__main__':
test_data = DoExcel.get_data(test_case_path)
print(len(test_data))
http_case.config
[MODE]
mode = {
'login_data': 'all',#执行所有的用例
'recharge_data': [1, 3]#执行第1和第3条用例
}
data_http.xlsx表格内数据包含两个表单'login_data'和'recharge_data',各有4条用例
image.png image.png
read_http_config.py 读取配置文件
# -*-coding: utf8 -*-
import configparser
class ReadConfig:
@staticmethod
def get_config(file_path, section, option):
cf = configparser.ConfigParser()
cf.read(file_path)
return cf[section][option]
if __name__ == '__main__':
from practise.utils import project_path
print(ReadConfig.get_config(project_path.case_config_path, 'MODE', 'mode'))
执行run.py
image.png
查看html测试报告
image.png
【注】接口地址和表内数据可参考上篇文章