一、框架介绍
1、HttpRunner
是一款面向 HTTP(S) 协议的通用测试框架,只需编写维护一份YAML/JSON脚本,即可实现自动化测试、性能测试、线上监控、持续集成等多种测试需求。
2、Locust
Locust是一款易于使用的分布式用户负载测试工具。它用于对网站(或其他系统)进行负载测试,并确定系统可以处理多少并发用户。HttpRunner 通过复用Locust ,可以在无需对 YAML/JSON 进行任何修改的情况下,直接运行性能测试。
3 httprunner使用手册
附httprunner中文使用文档地址:https://cn.httprunner.org/
二、环境安装
1 安装httprunner: pip install httprunner==2.2.5
2 安装har2case: pip install har2case
3 检查安装是否成功:hrun -h/-v;har2case -h/-v
4 安装locust: pip install locustio
三、在 HttpRunner 安装成功后,系统中会新增如下 5 个命令:
1 httprunner: 核心命令
2 hrun: httprunner 的缩写,功能与 httprunner 完全相同
3 locusts: 基于 Locust 实现性能测试
4 har2case: 辅助工具,可将标准通用的 HAR 格式(HTTP Archive)转换为YAML/JSON格式的测试用例
四、用例生成
(1)利用fiddler/charles对接口数据进行抓包,将结果导出为XX.har文件


(2)将导出的XX.har文件转化为json文件/yaml文件
转化为json文件:har2case xx.har
转化为yaml文件:har2case xx.har -2y/--to-yml
(3) 转化成功后的yaml文件如下:

status_code:请求的状态码
headers.Content-Type:将响应头的内容格式做验证
content.msg:响应内容的关键字作为验证
----------------------------------------------------------------------
config:作为整个测试用例集的全局配置项,包括变量(variables,name)
test:对应单个测试用例
name 这个test的名字(用例的名称)
request 这个test具体发送http请求的各种信息, 如下:
url 请求的路径 (若config中有定义base_url, 则完整路径是用 base_url + url )
method 请求方法 POST, GET等等
headers:请求头
请求体:json格式的数据
validate(断言): 完成请求后, 所要进行的验证内容. 所有验证内容均通过该test才算通过,否则失败.
参数化:
testcases:
-
name: call demo_testcase with data 1
testcase: testcases/test_login.yml
parameters:
# username: ["admin1","admin"]
-username:
- ["admin1"]
- ["admin"]
测试用例(testcase)嵌套testcases

变量取值:

响应头和响应体的提取:


提取HTML的内容(正则表达式)

上传文件场景

四、生成项目文档:
(1)进入D盘
(2)输入命令:hrun --startproject 项目名称
testcases:存放用例
testsuites:存放套件
reports:自动生成报告并放到该目录

3、 进入到目录,查看对应的文件和目录
可以看到生成的3个目录和一个py文件,api debugtalk.py testcases suite
4、将转化好的XX.har文件放置在项目文件夹testcases目录中
5 、运行用例
(1)运行单个用例:指定具体的xx.yml或xx.json文件
hrun 文件路径/hrun 文件路径 --log-level info

(2)运行多个用例:hrun 文件的testcases目录

(3) 运行testsuites目录:运行testsuites目录中所有的yml用例

参数化:多个参数三种类型参数化

六、查看报告
在项目文件夹report中,生成了html格式的测试报告,包括log日志记录(包含request and response data)



注意事项:

hrun xx.yaml --log-level debug

(3) 将运行过程中的中间数据作为日志保存:hrun xx.yaml --log-file xx.log


七、接口的性能测试---locusts
1 执行性能测试用例:locusts -f 文件路径(相对路径) --processes
(在 Locust 中需使用多核处理器的能力,--processes 参数,可以一次性启动 1 个 master 和多个 salve。若在 --processes 参数后没有指定具体的数值,则启动的 slave 个数与机器的 CPU 核数相同。)

2 用例运行完成后,在浏览器中输入地址 http://localhost:8089/,可查看到locust页面
Number of total users to simulate:并发用户数
Hatch rate (users spawned/second):多少秒启动这些并发
Host:接口的主机地址


locustos在执行请求动作

3 查看性能测试报告:

(2) 每秒完成的请求数(RPS:Requests Per Second)

(3)响应时间(Response Times),单位ms

(4)不同时间的虚拟用户数:稳定值(一定时间后)

(5)查看cpu并发压力:类似负载均衡--CPU usage(cpu的使用率)

6、参数说明
host:http://10.0.10.27:10080
请求路径(name):/api/login

7 脚本执行结果
从测试结果可以看出,实际上每秒并没有触发10个请求(RPS值不到10),因为在locustfile.py文件里面有个等待机制
min_wait = 1000 最小等待时间1秒
max_wait = 5000 最大等待时间5秒
把max_wait改成1000就可以达到 10 RPS了
locustfile.py
当启动locusts的时候,会在当前目录自动生成一个locustfile.py文件。这个才是locust的脚本文件

使用locust执行locustfile.py脚本文件
locust -f locustfile.py
测试结果 RPS=9.9 接近10
网友评论