#testing-http #toml-config #http-response #testing #config-file #http-file #rest

bin+lib hat

hat 通过 toml 配置文件运行 HTTP 测试。配置的测试可以使用二进制操作(如 ==、>、<、!= 等)检查响应状态、头和体。如果一个或多个测试失败,hat 将返回失败退出码。使用 --help 获取更多使用细节。项目主页:https://github.com/isaacadams/hat

5 个不稳定版本

0.3.0 2023年7月20日
0.2.0 2023年7月16日
0.1.7 2023年7月10日
0.1.1 2023年6月26日

#2670 in 命令行工具

42 每月下载量

MIT/Apache

54KB
1.5K SLoC

用法

查看 hat 的使用示例

$ hat --help
hat runs HTTP tests based on a toml configuration file.

The configured tests can check response status, headers, and body
using binary operations such as ==, >, <, !=, etc.

If one or more tests fail, hat will return a failed exit code.

Use --help for more USAGE details.

Project homepage: https://github.com/isaacadams/hat


Usage: hat[EXE] [OPTIONS] <PATH>

Arguments:
  <PATH>  path to .toml configuration file

Options:
  -v, --verbose <VERBOSE>  verbose level: DEBUG, INFO, ERROR [default: DEBUG]
  -h, --help               Print help
  -V, --version            Print version

.toml 配置

一个配置了 HTTP 请求和断言的 .toml 文件可以通过 hat CLI 加载,然后执行 HTTP 请求并运行断言对 HTTP 响应。

# see other examples of a hat .toml config file in the example folder
# e.g. example/local/config.toml
# e.g. example/pastebin/pastebin.toml
[environment]
# any variable can be defined here that needs to be used throughout testing
# all environment variables and .env file(s) will be loaded automatically
# <name> = <value>
base = "https://your-api-domain.com/api/v1"

[[tests]]
# http = "<METHOD> <URL>" OR "path/to/file.http"
http = "GET {{base}}/users"
# optional description
description = "get the users"
# each line in assertions is evaluated
# three variables are generated from the HTTP response: status, headers, and body
# status: number
# headers: json
# body: whatever the endpoint returns (e.g. json, xml, plaintext, etc.)
assertions = """
{{ status }} == 200
{{ headers | content-type }} == "application/json"
{{ body | users.0.username }} == "isaacadams"
{{ body | users.#(username=="isaacadams").username }} == "isaacadams"
"""
# using response variables, add new variables to the [environment]
[tests.outputs]
userId = "{{ body | users.#(username==\"isaacadams\").id }}"

# write a follow-up test
[[tests]]
# uses {{userId}} defined from previous steps' output
http = """
GET {{base}}/users/{{userId}}
Accept application/json
"""
assertions = """
{{ status }} == 200
{{ headers | content-type }} == "application/json"
{{ body | username }} == "isaacadams"
"""

.http 文件

example/local/config.toml 使用了一个 create-post.http 文件。

这是 CLI 工具特有的文件类型。以下是如何使用 .http 文件的示例。由于某些请求很复杂,请求体可能非常大,这可能会分散配置文件的注意力。能够在自己的文件中定义请求也打开了重用请求的可能性。

POST {{base}}/posts
Content-Type: application/json

[
    "I made a new post today"
]

依赖

~13–25MB
~331K SLoC