当前位置: 首页 > news >正文

Pytest+request+Allure

零基础1小时快速入门pytest自动化测试教程,全套项目框架实战

前言:

接口自动化是指模拟程序接口层面的自动化,由于接口不易变更,维护成本更小,所以深受各大公司的喜爱。
接口自动化包含2个部分,功能性的接口自动化测试和并发接口自动化测试。
本次文章着重介绍第一种,功能性的接口自动化框架。


一、简单介绍

环境:Mac、Python 3,Pytest,Allure,Request
流程:读取Yaml测试数据-生成测试用例-执行测试用例-生成Allure报告
模块类的设计说明:

Request.py 封装request方法,可以支持多协议扩展(get\post\put)
Config.py读取配置文件,包括:不同环境的配置,email相关配置
Log.py 封装记录log方法,分为:debug、info、warning、error、critical
Email.py 封装smtplib方法,运行结果发送邮件通知
Assert.py 封装assert方法
run.py 核心代码。定义并执行用例集,生成报告

Yaml测试数据格式如下:

---
Basic:dec: "基础设置"parameters:-url: /settings/basic.jsondata: slug=da1677475c27header: {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko)\Chrome/67.0.3396.99 Safari/537.36","Content-Type": "keep-alive"}

二、代码结构与框架流程

1、代码结构见下图:

代码结构.png

2、框架流程见下图:

框架流程.jpg


三、详细功能和使用说明

1、定义配置文件config.ini

该文件中区分测试环境[private_debug]和正式环境[online_release]分别定义相关配置项,[mail]部分为邮件相关配置项

# http接口测试框架配置信息[private_debug]
# debug测试服务
tester = your name
environment = debug
versionCode = your version
host = www.jianshu.com
loginHost = /Login
loginInfo = email=wang@user.com&password=123456[online_release]
# release正式服务
tester = your name
environment = release
versionCode = v1.0
host = www.jianshu.com
loginHost = /Login
loginInfo = email=wang@user.com&password=123456[mail]
#发送邮件信息
smtpserver = smtp.163.com
sender = test1@163.com
receiver = wang@user.com
username = wang@user.com
password = 123456
2、读取yaml测试数据后封装

yaml测试数据例子见第一节,一条接口可定义多条case数据,get_parameter为已封装好的读取yaml数据方法,循环读取后将多条case数据存在list中。

class Basic:params = get_parameter('Basic')url = []data = []header = []for i in range(0, len(params)):url.append(params[i]['url'])data.append(params[i]['data'])header.append(params[i]['header'])
3、编写用例
class TestBasic:@pytest.allure.feature('Home')@allure.severity('blocker')@allure.story('Basic')def test_basic_01(self, action):"""用例描述:未登陆状态下查看基础设置"""conf = Config()data = Basic()test = Assert.Assertions()request = Request.Request(action)host = conf.host_debugreq_url = 'http://' + hosturls = data.urlparams = data.dataheaders = data.headerapi_url = req_url + urls[0]response = request.get_request(api_url, params[0], headers[0])assert test.assert_code(response['code'], 401)assert test.assert_body(response['body'], 'error', u'继续操作前请注册或者登录.')assert test.assert_time(response['time_consuming'], 400)Consts.RESULT_LIST.append('True')
4、运行整个框架run.py
if __name__ == '__main__':# 定义测试集allure_list = '--allure_features=Home,Personal'args = ['-s', '-q', '--alluredir', xml_report_path, allure_list]log.info('执行用例集为:%s' % allure_list)self_args = sys.argv[1:]pytest.main(args)cmd = 'allure generate %s -o %s' % (xml_report_path, html_report_path)try:shell.invoke(cmd)except:log.error('执行用例失败,请检查环境配置')raisetry:mail = Email.SendMail()mail.sendMail()except:log.error('发送邮件失败,请检查邮件配置')raise
5、err.log实例
[ERROR 2018-08-24 09:55:37]Response body != expected_msg, expected_msg is {"error":"继续操作前请注册或者登录9."}, body is {"error":"继续操作前请注册或者登录."}
[ERROR 2018-08-24 10:00:11]Response time > expected_time, expected_time is 400, time is 482.745
[ERROR 2018-08-25 21:49:41]statusCode error, expected_code is 208, statusCode is 200 
6、Assert部分代码
    def assert_body(self, body, body_msg, expected_msg):"""验证response body中任意属性的值:param body::param body_msg::param expected_msg::return:"""try:msg = body[body_msg]assert msg == expected_msgreturn Trueexcept:self.log.error("Response body msg != expected_msg, expected_msg is %s, body_msg is %s" % (expected_msg, body_msg))Consts.RESULT_LIST.append('fail')raisedef assert_in_text(self, body, expected_msg):"""验证response body中是否包含预期字符串:param body::param expected_msg::return:"""try:text = json.dumps(body, ensure_ascii=False)# print(text)assert expected_msg in textreturn Trueexcept:self.log.error("Response body Does not contain expected_msg, expected_msg is %s" % expected_msg)Consts.RESULT_LIST.append('fail')raise
7、Request部分代码
    def post_request(self, url, data, header):"""Post请求:param url::param data::param header::return:"""if not url.startswith('http://'):url = '%s%s' % ('http://', url)print(url)try:if data is None:response = self.get_session.post(url=url, headers=header)else:response = self.get_session.post(url=url, params=data, headers=header)except requests.RequestException as e:print('%s%s' % ('RequestException url: ', url))print(e)return ()except Exception as e:print('%s%s' % ('Exception url: ', url))print(e)return ()# time_consuming为响应时间,单位为毫秒time_consuming = response.elapsed.microseconds/1000# time_total为响应时间,单位为秒time_total = response.elapsed.total_seconds()Common.Consts.STRESS_LIST.append(time_consuming)response_dicts = dict()response_dicts['code'] = response.status_codetry:response_dicts['body'] = response.json()except Exception as e:print(e)response_dicts['body'] = ''response_dicts['text'] = response.textresponse_dicts['time_consuming'] = time_consumingresponse_dicts['time_total'] = time_totalreturn response_dicts

四、Allure报告及Email

1、Allure报告总览,见下图:

Allure报告.png

2、Email见下图:

Email.png


五、后续优化

1、集成Jenkins,使用Jenkins插件生成Allure报告
2、多线程并发接口自动化测试
3、接口加密,参数加密


文章转载自:

http://ADxvzZJw.xjqrn.cn
http://Vwin2PKh.xjqrn.cn
http://WHsuW03y.xjqrn.cn
http://HYeozgvv.xjqrn.cn
http://c5LCkMpf.xjqrn.cn
http://5SqC4uQ0.xjqrn.cn
http://UUmNPuS4.xjqrn.cn
http://1lL6pRKs.xjqrn.cn
http://J02ecLmL.xjqrn.cn
http://zn7HobUq.xjqrn.cn
http://czlPTYge.xjqrn.cn
http://LJFWMvKk.xjqrn.cn
http://MDbPDU1b.xjqrn.cn
http://3kryJWRq.xjqrn.cn
http://uaUjQ1R1.xjqrn.cn
http://ffrIcQu0.xjqrn.cn
http://ghOGNnKd.xjqrn.cn
http://yCDuQyfB.xjqrn.cn
http://gQgS3t8C.xjqrn.cn
http://xVrFdeCr.xjqrn.cn
http://vi9ArtRE.xjqrn.cn
http://3uzYinuB.xjqrn.cn
http://2hoFsU1H.xjqrn.cn
http://xPxPVLhJ.xjqrn.cn
http://5xxmvIQh.xjqrn.cn
http://rYpAjnHr.xjqrn.cn
http://L77oxS1o.xjqrn.cn
http://J2PNmvQS.xjqrn.cn
http://kxU9g6pY.xjqrn.cn
http://TyyHpS4a.xjqrn.cn
http://www.dtcms.com/a/386369.html

相关文章:

  • Android 反调试攻防实战:多重检测手段解析与内核级绕过方案
  • [vue.js] 树形结点多选框选择
  • websocket python 实现
  • 使用代理访问网络各项命令总结
  • 信创电脑入门指南:定义、发展历程与重点行业部署详解
  • PostgreSQL——元命令
  • PHP 连接池详解:概念、实现与最佳实践
  • nginx + php-fpm改用socket方式代理可能遇到的问题
  • 一篇文章说清【布隆过滤器】
  • 「数据获取」《中国教育经费统计年鉴》(1997-2024)
  • 产品开发周期缩写意思
  • Keil5安装教程保姆级(同时兼容支持C51与ARM双平台开发)(附安装包)
  • [deepseek]Python文件打包成exe指南
  • 2025最新超详细FreeRTOS入门教程:第二十章 FreeRTOS源码阅读与内核解析
  • 一种基于最新YOLO系列优化策略的缺陷检测方法及系统
  • 「英」精益设计第二版 — AxureMost落葵网
  • esp32_rust_oled
  • 贪心算法应用:前向特征选择问题详解
  • 微信小程序禁止下拉
  • 概率思维:数据驱动时代的核心技术引擎与方法论修炼
  • Docker在欧拉系统上内核参数优化实践
  • 【Linux系列】查询磁盘类型
  • 机械革命笔记本电脑重装Windows系统详细教程
  • RustFS vs MinIO:深入对比分布式存储的性能、功能与选型指南
  • GLSL 版本与应用场景详解
  • QNX与Linux的详细对比分析
  • PHP 并发处理与进程间通信深度解析
  • 洛谷 下楼梯 动态规划
  • 仓颉编程语言青少年基础教程:class(类)(上)
  • MySQL数据库(五)—— Mysql 备份与还原+慢查询日志分析