基于GO开发的开源的API测试工具,支持HTTP/WebSocket/RPC等协议

《开源精选》是我们分享Github、Gitee等开源社区中优质项目的栏目,包括技术、学习、实用与各种有趣的内容。本期推荐的是一个开源的 API 测试工具——HttpRunner。

基于GO开发的开源的API测试工具,支持HTTP/WebSocket/RPC等协议

HttpRunner 是一个开源的 API 测试工具,支持 HTTP(S) / HTTP2 / WebSocket / RPC 等网络协议,涵盖接口测试、性能测试、数字体验监测等测试类型。简单易用,功能强大,具有丰富的插件化机制和高度的可扩展能力。

基于GO开发的开源的API测试工具,支持HTTP/WebSocket/RPC等协议


功能特性

  • 网络协议:完整支持 HTTP(S)/HTTP2/WebSocket,可扩展支持 TCP/UDP/RPC 等更多协议
  • 多格式可选:测试用例支持 YAML/JSON/go test/pytest 格式,并且支持格式互相转换
  • 双执行引擎:同时支持 golang/python 两个执行引擎,兼具 go 的高性能和 pytest 的丰富生态
  • 录制 & 生成:可使用 HAR/Postman/Swagger/curl 等生成测试用例;基于链式调用的方法提示也可快速编写测试用例
  • 复杂场景:基于 variables/extract/validate/hooks 机制可以方便地创建任意复杂的测试场景
  • 插件化机制:内置丰富的函数库,同时可以基于主流编程语言(go/python/java)编写自定义函数轻松实现更多能力
  • 性能测试:无需额外工作即可实现压力测试;单机可轻松支撑 1w+ VUM,结合分布式负载能力可实现海量发压
  • 网络性能采集:在场景化接口测试的基础上,可额外采集网络链路性能指标(DNS 解析、TCP 连接、SSL 握手、网络传输等)
  • 一键部署:采用二进制命令行工具分发,无需环境依赖,一条命令即可在 macOS/Linux/Windows 快速完成安装部署


安装部署

HttpRunner 采用 Golang 开发,已针对主流操作系统预编译了二进制文件,只需在系统终端中执行一条命令即可完成安装部署。

$ bash -c "$(curl -ksSL https://httprunner.com/script/install.sh)"

成功后,你将获得一个 hrp 命令行工具,执行 hrp -h 即可查看到参数帮助说明。

$ hrp -h

██╗  ██╗████████╗████████╗██████╗ ██████╗ ██╗   ██╗███╗   ██╗███╗   ██╗███████╗██████╗
██║  ██║╚══██╔══╝╚══██╔══╝██╔══██╗██╔══██╗██║   ██║████╗  ██║████╗  ██║██╔════╝██╔══██╗
███████║   ██║      ██║   ██████╔╝██████╔╝██║   ██║██╔██╗ ██║██╔██╗ ██║█████╗  ██████╔╝
██╔══██║   ██║      ██║   ██╔═══╝ ██╔══██╗██║   ██║██║╚██╗██║██║╚██╗██║██╔══╝  ██╔══██╗
██║  ██║   ██║      ██║   ██║     ██║  ██║╚██████╔╝██║ ╚████║██║ ╚████║███████╗██║  ██║
╚═╝  ╚═╝   ╚═╝      ╚═╝   ╚═╝     ╚═╝  ╚═╝ ╚═════╝ ╚═╝  ╚═══╝╚═╝  ╚═══╝╚══════╝╚═╝  ╚═╝

HttpRunner is an open source API testing tool that supports HTTP(S)/HTTP2/WebSocket/RPC
network protocols, covering API testing, performance testing and digital experience
monitoring (DEM) test types. Enjoy! ✨  ✨

License: Apache-2.0
Website: https://httprunner.com
Github: https://github.com/httprunner/httprunner
Copyright 2017 debugtalk

Usage:
  hrp [command]

Available Commands:
  boom         run load test with boomer
  completion   generate the autocompletion script for the specified shell
  convert      convert JSON/YAML testcases to pytest/gotest scripts
  har2case     convert HAR to json/yaml testcase files
  help         Help about any command
  pytest       run API test with pytest
  run          run API test with go engine
  startproject create a scaffold project

Flags:
  -h, --help               help for hrp
      --log-json           set log to json format
  -l, --log-level string   set log level (default "INFO")
  -v, --version            version for hrp

Use "hrp [command] --help" for more information about a command.


脚手架创建项目

HttpRunner 支持使用脚手架创建示例项目。

执行 hrp startproject 命令,即可初始化指定名称的项目工程。

$ hrp startproject demo
10:13PM INF Set log to color console other than JSON format.
10:13PM ??? Set log level
10:13PM INF create new scaffold project force=false pluginType=py projectName=demo
10:13PM INF create folder path=demo
10:13PM INF create folder path=demo/har
10:13PM INF create file path=demo/har/.keep
10:13PM INF create folder path=demo/testcases
10:13PM INF create folder path=demo/reports
10:13PM INF create file path=demo/reports/.keep
10:13PM INF create file path=demo/.gitignore
10:13PM INF create file path=demo/.env
10:13PM INF create file path=demo/testcases/demo_with_funplugin.json
10:13PM INF create file path=demo/testcases/demo_requests.yml
10:13PM INF create file path=demo/testcases/demo_ref_testcase.yml
10:13PM INF start to create hashicorp python plugin
10:13PM INF create file path=demo/debugtalk.py
10:13PM INF ensure python3 venv packages=["funppy==v0.4.3"] python=/Users/debugtalk/.hrp/venv/bin/python
10:13PM INF python package is ready name=funppy version=0.4.3
10:13PM INF create scaffold success projectName=demo

如下是项目工程的目录结构。其中,testcases 文件夹中包含了多个示例测试用例。

$ tree demo -a
demo
├── .env
├── .gitignore
├── debugtalk.py
├── har
│   └── .keep
├── reports
│   └── .keep
└── testcases
    ├── demo_ref_testcase.yml
    ├── demo_requests.yml
    └── demo_with_funplugin.json

3 directories, 8 files


测试用例

接下来我们以 demo_requests.yml 为例,初步预览下 HttpRunner 的测试用例结构。

config:
    name: "request methods testcase with functions"
    variables:
        foo1: config_bar1
        foo2: config_bar2
        expect_foo1: config_bar1
        expect_foo2: config_bar2
    base_url: "https://postman-echo.com"
    verify: False
    export: ["foo3"]

teststeps:
-
    name: get with params
    variables:
        foo1: bar11
        foo2: bar21
        sum_v: "${sum_two(1, 2)}"
    request:
        method: GET
        url: /get
        params:
            foo1: $foo1
            foo2: $foo2
            sum_v: $sum_v
        headers:
            User-Agent: HttpRunner/${get_httprunner_version()}
    extract:
        foo3: "body.args.foo2"
    validate:
        - eq: ["status_code", 200]
        - eq: ["body.args.foo1", "bar11"]
        - eq: ["body.args.sum_v", "3"]
        - eq: ["body.args.foo2", "bar21"]
-
    name: post raw text
    variables:
        foo1: "bar12"
        foo3: "bar32"
    request:
        method: POST
        url: /post
        headers:
            User-Agent: HttpRunner/${get_httprunner_version()}
            Content-Type: "text/plain"
        data: "This is expected to be sent back as part of response body: $foo1-$foo2-$foo3."
    validate:
        - eq: ["status_code", 200]
        - eq: ["body.data", "This is expected to be sent back as part of response body: bar12-$expect_foo2-bar32."]
-
    name: post form data
    variables:
        foo2: bar23
    request:
        method: POST
        url: /post
        headers:
            User-Agent: HttpRunner/${get_httprunner_version()}
            Content-Type: "application/x-www-form-urlencoded"
        data: "foo1=$foo1&foo2=$foo2&foo3=$foo3"
    validate:
        - eq: ["status_code", 200]
        - eq: ["body.form.foo1", "$expect_foo1"]
        - eq: ["body.form.foo2", "bar23"]
        - eq: ["body.form.foo3", "bar21"]

HttpRunner 测试用例包括且仅有两部分:

  • config:测试用例的公共配置部分,包括用例名称、base_url、参数化数据源、是否开启 SSL 校验等
  • teststeps:有序步骤的集合;采用了 go interface 的设计理念,支持进行任意协议和测试类型的拓展(甚至包括 UI 自动化)

在上面的案例中,每个 step 都是一个 HTTP 请求;可以看到,描述信息仅包含了 HTTP 请求和结果校验的核心要素,没有任何累赘的内容。

同时,需要重点关注的是,虽然上面的用例是 YAML 文本,但同样支持引用变量和调用函数。

  • 变量引用:约定通过 ${} 或 $ 的形式来引用变量,例如 $foo1 或 ${foo1}
  • 函数调用:约定通过 ${} 的形式来调用插件函数,例如 ${sum_two(1, 2)}

变量的申明定义在 step 或 config 的 variables 中,并且遵循优先级的要求。

函数的申明定义在项目根目录的 debugtalk.py 中,基于「约定大于配置」的设计理念,我们无需在测试用例中进行配置。

import funppy


def get_httprunner_version():
    return "v4.0.0-alpha"


def sum_two_int(a: int, b: int) -> int:
    return a + b


if __name__ == '__main__':
    funppy.register("get_httprunner_version", get_httprunner_version)
    funppy.register("sum_two", sum_two_int)
    funppy.serve()

debugtalk.py 中,我们可以编写实现任意自定义逻辑的函数,只需通过 funppy 进行 registerserve() 即可。


运行接口测试

测试用例就绪后,通过 hrp run 命令即可执行指定的测试用例;如需生成 HTML 测试报告,可附带 --gen-html-report 参数。

$ hrp run demo/testcases/demo_requests.yml demo/testcases/demo_ref_testcase.yml --gen-html-report

测试生成的 HTML 报告如下所示:

基于GO开发的开源的API测试工具,支持HTTP/WebSocket/RPC等协议


运行性能测试

针对已有的接口测试用例,HttpRunner 无需任何额外的工作,即可通过 hrp boom 命令运行性能测试;通过 --spawn-count 参数可指定并发用户数,通过 --spawn-rate 可指定起始发压斜率。

$ hrp boom testcases/demo_requests.yml --spawn-count 100 --spawn-rate 10

在压测运行过程中,每隔 3 秒打印一次性能汇总数据;通过 CTRL + C 终止测试后,会打印整个压测过程的汇总数据(Statistics Summary)。


—END—

开源协议:Apache2.0

开源地址:https://github.com/httprunner/httprunner

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章