Python接口自动化测试框架搭建

Python接口自动化测试框架搭建此框架是基于 python 的 unittest 单元测试框架写的 写的有点简单 有些地方可能不是很完整 后期在逐步完善 先来看下框架的目录布局 common 公共的方法目录 conf 配置文件存放目录 data 测试数据目录 library 存放一些下载第三方的模块 logs 日志文件存放的目录 reports 测试报告存放目录 testcases 测试用例类模块目录 run test py 主程序 项目的启动文件前面 Python 专栏里分开写过每个模块的使用 写的有点菜 阅读量总是那么可怜

此框架是基于python的unittest单元测试框架写的。写的有点简单,有些地方可能不是很完整,后期在逐步完善。

在这里插入图片描述
all_paths.py

这里把所有文件的目录路径都写在这里用变量接收,获取的时候直接调用变量就行。 import os dir_name1=os.path.dirname(os.path.abspath(__file__)) dir_name=os.path.dirname(dir_name1) log_path=os.path.join(os.path.join(dir_name,'logs'),'log.log')#log文件路径 casexlsx_path=os.path.join(os.path.join(dir_name,'data'),'case.xlsx')#测试用例excel文件路径 report_path=os.path.join(os.path.join(dir_name,'reports'),'report.html')#测试报告文件路径 config_path=os.path.join(os.path.join(dir_name,'conf'),'conf.yaml')#配置文件路径 case_path=os.path.join(dir_name,'testcases')#测试用例代码路径 

excel_handler.py 操作excel的方法,主要用于读取测试用例。

import openpyxl class ExcelMothed: def __init__(self,filepath,sheet): self.filepath=filepath self.sheet=sheet def open_excel(self): '''打开excel''' workbook=openpyxl.load_workbook(self.filepath) return workbook def get_sheet(self): '''获取Sheet表单''' workbook=self.open_excel() sheet=workbook[self.sheet] return sheet def get_case(self): '''获取所有用例''' cell=self.get_sheet() rows=list(cell.rows) case=[] title=[] for row in rows[0]: title.append(row.value) for values in rows[1:]: dic={ 
   } for indx,value in enumerate(values): dic[title[indx]]=value.value case.append(dic) return case def excel_write(self,row,column,data): '''excel根据单元格位置写入内容''' sheet=self.get_sheet() sheet.cell(row,column).value=data self.excel_save() self.excel_close() def excel_save(self): '''保存excel''' self.open_excel().save(self.filepath) def excel_close(self): '''关闭excel''' self.open_excel().close() 

read_yaml.py 读取yaml文件方法

import yaml def read_yaml(file): with open(file,encoding='utf-8') as f: config_info=yaml.load(f,Loader=yaml.SafeLoader) return config_info 

logger_handler.py 日志方法

#get_logger()的参数我放到了yaml文件里,所以需要从common里import read_yaml方法、配置文件的路径 import logging from api_test_v1.common.read_yaml import read_yaml from api_test_v1.common.all_paths import config_path log_info=read_yaml(config_path)['log'] def get_logger(filepath=None, fmtt=log_info['fmt'], logger_level=log_info['logger_level'], stream_level=log_info['stream_level'], handler_level=log_info['file_level']): logger = logging.getLogger() # 初始化收集器 # logger.handlers.clear()#清空收集器列表 if not logger.handlers: logger.setLevel(logger_level)#设置日志等级 stream_handler=logging.StreamHandler()#初始化处理器 stream_handler.setLevel(stream_level)#设置处理器日志等级 logger.addHandler(stream_handler) # 处理器添加到收集器 fmt = logging.Formatter(fmtt) # 设置日志输出格式 stream_handler.setFormatter(fmt)# 添加到处理器 if filepath: file_handler=logging.FileHandler(filepath,'a',encoding='utf-8')#初始化文件输出处理器 file_handler.setLevel(handler_level)#设置处理器日志等级 file_handler.setFormatter(fmt) logger.addHandler(file_handler) # 处理器添加到收集器 return logger 
log: fmt: '%(name)s--%(asctime)s--%(filename)s--%(lineno)d--%(levelname)s:%(message)s' logger_level: 'DEBUG' stream_level: 'DEBUG' file_level: 'INFO' 
#登录功能 def login(username,password): if username!=None and password!=None: if username=='admin' and password=='':#账号密码正确登录成功 return { 
   'msg':'登录成功'} else:#账号密码错误 return { 
   'msg':'账号或密码不正确'} return { 
   'msg':'账号或密码为空'}#账号或密码为空 

测试用例代码如下:

 from Testdemo.login import login#导入login函数 from api_test_v1.common.excel_handler import ExcelMothed#导入excel方法 from api_test_v1.common.all_paths import casexlsx_path,log_path#导入excel路径,日志路径 from api_test_v1.common.logger_handler import get_logger#导入日志方法 import unittest import ddt#导入ddt,数据驱动模式 data=ExcelMothed(casexlsx_path,'Sheet1')#初始化 case=data.get_case()#获取用例 data.excel_close()#关闭excel @ddt.ddt class TestLogin(unittest.TestCase):#定义测试类继承unittest.TestCase类 @ddt.data(*case) def test_login_success(self,cases): info=eval(cases['data']) username=info['username'] password=info['password'] expected_result=eval(cases['expected'])#预期结果 actual_result=login(username,password)#调用被测函数 try: self.assertTrue(expected_result == actual_result) # 判断预期结果与实际结果是否一致 except Exception as e: get_logger(log_path).info('用例未通过:{}'.format(e))#日志记录 raise e#手动抛出异常 else: get_logger(log_path).debug('用例通过')#日志记录 

run_test.py运行主程序代码如下:

import unittest from api_test_v1.library.HTMLTestRunnerNew import HTMLTestRunner#导入第三方模块 from api_test_v1.common.all_paths import report_path,case_path#导入报告路径,测试用例的路径 loader=unittest.TestLoader()#初始化用例的加载器 test_suite=loader.discover(case_path)#自动加载测试用例 with open(report_path,'wb') as f: runner=HTMLTestRunner(f,title='自动化测试报告',description='登录与注册模块',tester='tester') runner.run(test_suite)#运行 

最后运行主程序来看下日志及测试报告:

login--2020-06-03 14:10:00,138--test_login.py--23--INFO:用例未通过:False is not true login--2020-06-03 14:10:00,139--test_login.py--26--INFO:用例通过 login--2020-06-03 14:10:00,140--test_login.py--26--INFO:用例通过 

在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/229825.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月16日 下午3:47
下一篇 2026年3月16日 下午3:48


相关推荐

  • linux awk 数组,shell数组和awk数组

    linux awk 数组,shell数组和awk数组awk终于能入门了,所以整理了该文章,内容大多来自网上。一、bash支持一维数组(不支持多维数组),没有限定数组的大小。在shell中,用括号来表示数组,数组元素用空格符号分割开。类似于C语言,数组元素的下标由0开始编号。获取数组中的元素要利用下标,下标可以是整数或算术表达式,其值应大于或等于01.定义数组数组名array,元素abc[root@localhost~]#array=(ab…

    2022年7月19日
    18
  • Chrome for Android在Chromium代码库中的提交patch「建议收藏」

    Chrome for Android在Chromium代码库中的提交patch

    2022年1月29日
    71
  • github中创建的仓库中有Readme和MIT协议push失败问题

    github中创建的仓库中有Readme和MIT协议push失败问题最近想把一个项目上传到github中去,但是遇到一系列问题,本来以为很快就解决了,但并非想象那样,反而耽误了我好长时间,于是记录下来。———————————————————————————————————————————–…

    2022年6月13日
    35
  • 不是单组分组函数

    不是单组分组函数问题:一:SELECT tablespace_name, SUM(bytes) freeFROM dba_free_space不是单组分组函数原因: 1、如果程序中使用了分组函数,则有两种情况可以使用:程序中存在group by,并指定了分组条件,这样可以将分组条件一起查询出来改为:  SELECT tablespace_name, SUM(bytes) freeFROM dba_free_spa…

    2022年6月30日
    26
  • python 报表开发工具_测评8款热门的报表开发工具 开源

    python 报表开发工具_测评8款热门的报表开发工具 开源阅读提示 文章中与 FineReport 软件使用的相关内容 基于软件的 V7 0 旧版本编写 不代表软件最新的使用方式 FineReport 最新版免费试用 https www finereport com product activeFineRe 最新版使用教程 https help fanruan com finereport 什么叫做报表开发工具开源 也就是开放源代码可以进行自主修改

    2026年3月26日
    2
  • vue定时器无法停止。

    vue定时器无法停止。vue 模板里面的定时器问题文章目录前言一 定时器是什么 二 使用步骤 1 使用过程 2 读入数据总结前言有些时候我们在使用 vue 模板时 不免会使用定时器来定时请求后台获取数据 但是在获取数据的时候 定时器就像踩不住刹车的小车 飘起来了 提示 以下是本篇文章正文内容 下面案例可供参考一 定时器是什么 定时请求后台数据的一种方式 二 使用步骤 1 使用过程你的页面组件属于 transitionna move mode out in transitionna move mode out in

    2026年3月16日
    1

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号