整体框架:
cases.xlsx用例:
common.read_xl的代码
from openpyxl import load_workbook from settings import config def read_excel(file, sheet_name): # 通过文件得到一个工作簿,参数是文件名,如果有路径,要填绝对路径 wb = load_workbook(file) # 获取sheet表格 sheet = wb[sheet_name] # 得到所有的数据 data = list(sheet.values) # 获取所有的标题 titles = data[0] # 转为字典 rows = [dict(zip(titles, row)) for row in data[1:]] return rows result = read_excel(file=config.case_file, sheet_name='register')
common.read_yaml的代码
import yaml from settings import config def read_yml(yaml_path): # 读取yaml文件 with open(yaml_path, encoding='utf-8') as f: # 安全加载 data = yaml.safe_load(f) return data
common.logger的代码
from loguru import logger from settings import config def get_logger(file): logger.add(sink=file, encoding='utf-8', level='INFO') return logger log = get_logger(config.log_path)
settings.config的代码
# -*- coding: utf-8 -*- # @Time : 2021/10/20 10:49 # @Author : wyatt # @File : config.py """配置选项""" import os # 获取config.py当前文件的路径 current_path = os.path.abspath(__file__) # 配置文件目录的路径 config_dir = os.path.dirname(current_path) # 项目的根目录 root_dir = os.path.dirname(config_dir) # 测试数据的路径 data/ data_dir = os.path.join(root_dir, 'data') # 测试用例的文件路径 case_file = os.path.join(data_dir, 'cases.xlsx') # 测试用户信息的路径 user_path = os.path.join(data_dir, 'user.yaml') # 测试域名 host = 'http://api.xxx.com:8766' # 日志路径 log_path = os.path.join(root_dir, 'log/test.log')
tests.test_register_ddt的代码
import unittest import requests import json from common.read_xl import read_excel from settings import config from ddt import ddt, data # 得到测试数据 cases = read_excel(file=config.case_file, sheet_name='register') @ddt class TestRegister(unittest.TestCase): @data(*cases) def test_register_1(self, info): """ 注册 :return: """ # 1.准备测试数据 url = config.host + info['url'] method = info['method'] # 将json格式的字符串转化成字典,因为requests.request 需要字典格式 headers = json.loads(info['headers']) json_data = json.loads(info['json']) expected = json.loads(info['expected']) # 2.发送接口请求,得到实际结果 resp = requests.request(url=url, method=method, headers=headers, json=json_data) actual = resp.json() # 3.预期结果和实际结果的断言。 self.assertEqual(expected, actual)
run.py的代码
import unittest import unittestreport import datetime from BeautifulReport import BeautifulReport """发现文件夹的地址,收集用例,discover 是需要收集的用例模块属于哪个包""" suite = unittest.defaultTestLoader.discover('tests') # runner = unittestreport.TestRunner(suite) # runner.run() time1 = datetime.datetime.strftime(datetime.datetime.now(), '%Y_%m_%d_%H_%M') br = BeautifulReport(suite) br.report(description='测试报告', report_dir='./report', filename=f'report_{time1}')