go - 使用 ExampleTest 进行测试 - 预期的输出不匹配
问题描述
Running tool: /usr/local/go/bin/go test -timeout 30s -run ^(ExampleBuild)$
--- FAIL: ExampleBuild (0.00s)
got:
POST localhost/status?t=1 HTTP/1.1
Content-Type: application/json
want:
POST localhost/status?t=1 HTTP/1.1
Content-Type: application/json
FAIL
exit status 1
我正在尝试使用 Example 方法编写测试。我创建了一个带有标头(Content-Type:application/json)、查询参数 t=1、方法类型 POST 和 URL localhost 的 http 请求。
got: 和 want: 中的输出看起来是一样的,还检查了空格字符。无法弄清楚这两者之间有什么区别。
无法弄清楚我在这里错过了什么。
import (
"fmt"
"net/http"
"net/http/httputil"
)
func ExampleBuild() {
req, err := http.NewRequest(http.MethodPost, "localhost/status?t=1", nil)
req.Header.Add("content-type", "application/json")
if err != nil {
panic(err)
}
str, err := httputil.DumpRequest(req, false)
if err != nil {
panic(err)
}
fmt.Printf("%s", string(str))
// Output:
// POST localhost/status?t=1 HTTP/1.1
// Content-Type: application/json
}
解决方案
我认为发生的事情是 HTTP 标头\r\n
的 line break。所以这就是httputil.DumpRequest
返回。但是您可能在不\r\n
用于换行符的机器上编辑此文件,因此差异来自那里。
成功比较的蛮力方法是:
fmt.Println(strings.Replace(string(str), "\r", "", -1))
这会从 HTTP 转储的字符串中删除“\r”,如果您的编辑器仅使用“\n”来破坏预期的输出,它将成功比较。
更优雅的解决方案将取决于您的测试环境的具体情况。
推荐阅读
- android - Firebase 技术来寻找最近的用户
- java - 链接列表在尝试访问其数据时出现空点错误
- vue.js - 挂载钩子中的错误:“RangeError:超出最大调用堆栈大小”VUEJS
- angular - 如何返回使用可观察对象发出的数据构造的数组?
- c++ - 为什么 VS 2019 中缺少“项目默认值”设置?
- javascript - How to be sure if a callback function has called
- psycopg2 - 将 psycopg2 转换为 asyncpg 格式。““%”处或附近的语法错误”
- objective-c - 在 Swift 中转换 Objective C 块
- ios - 应用程序关闭时从推送通知中打开特定的 ViewController
- azure-devops - 服务网络挂钩 - 获取成功构建的工件?