httprunner项目实战
该项目来自于httprunner作者在霍格沃兹学院公开课的实战项目整理,主要用于httprunner的学习记录和交流
1.httprunner安装
1.1 pip安装httprunner,使用指令
pip install -U HttpRunner
1.2 安装完成后,输入“hrun -V”校验是否安装成功
出现版本号就是安装成功了
2.httprunner项目创建
2.1 通过框架的脚手架命令生成项目目录结构
httprunner startproject httprunner_project
2.2 使用charles抓包工具抓取录制下来的请求转为".har"文件放到项目的har目录下
文件类型选择har
2.3 使用指令“har2case har/demo.har”生成pytest测试用例
har2case使用具体可以查看“har2case -h”
2.4 执行刚刚生成的测试用例,执行成功
3.httprunner项目编写
3.1 参数化
因为直接复制出来的请求代码id是固定的,每次请求使用的id又是不一定的,所以需要参数化,这里使用jmespath提取参数
.extract()
.with_jmespath("body.data.id","docID")
jmespath替换的参数用"${docID}"
设置全局变量并用 " $参数名" 替换
#设置全局变量
.variables(**{"memberId":"111111111"})
设置局部变量并用 " $参数名" 替换
#设置局部变量
.with_variables(**{"remeber":True})
3.2 断言
使用断言,来判断接口请求返回参数是否正常
#判断next返回是否为/next
.assert_equal("body.data.next","/next")
#判断文件夹folderList数量是否大于等于5
.assert_length_greater_than("$folderList",5)
3.3 teardown赋值变量
teardown赋值变量作为session变量被后续接口所使用
实例:
#实现加载文档列表后,获取folders数目
在用例下,加入
#调用get_folders_num并传入folder_num
.teardown_hook("${get_folders_num($response)}","folder_num")
在“debugtalk.py”中定义一个方法get_folders_num()
def get_folders_num(response:ResponseObject):
print("response===",response.resp_obj.json())
resp_json = response.resp_obj.json()
folders = resp_json["data"]["folders"]
return len(folders)
使用指定httprunner发起的user-agent
"user-agent": "HttpRunner/${get_httprunner_version()}"
获取token
局部变量里需要传一个时间戳
.with_variables(**{
"remember":"true",
"timestamp":"${get_timestamp()}"
})
token的引用
"token": "${get_token($phone,$password,timestamp)}"
token的调用方法
def get_token(phone,password,timestamp):
s = "".join([phone,password,str(timestamp)])
token = hashlib.md5(s.encode("utf-8")).hexdigest()
print(f"token: {token}")
return token
3.4 用例间的调用
实例:
#实现登录用例的调用
可以使用指令获取模板直接套用
hmake testcases/demo_testcase_ref.yml
生成的文件的头部引用可以改成自己的并加在需要调用的类上
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))
from httprunner import HttpRunner, Config, Step, RunRequest, RunTestCase
from testcases.login_test import (
TestCaseLogin as CaseLogin,
)
类里需要在teststeps里加上调用,用来执行调用的用例
teststeps = [
Step(
RunTestCase("login").call(CaseLogin)
),
用例调用时,若有变量引用,需要用".export()"将变量导出,方便后续的引用
多个数据的调用,可以使用csv文件的来存放参数,比如新建个csv文件输入存放的参数
然后再使用pytest调用
@pytest.mark.parametrize("param", Parameters({
"phone-password":"${parametrize(data/accounts.csv)}"
}))
4.测试报告
4.1 测试报告生成
使用指令执行并生成测试报告
hrun testcase--alluredir=allurereports/
使用指令查看报告
allure serve allurereports
4.2 生成性能测试报告
需要先安装插件,使用指令
pip install "httprunner[locust]"
或者
pip install locust
装好后输入指令运行
locusts -f testcases/demo.py