gpt4 book ai didi

使用 ExampleTest 进行测试 - 预期输出不匹配

转载 作者:数据小太阳 更新时间:2023-10-29 03:32:24 24 4
gpt4 key购买 nike

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 方法在 go 中编写测试。我创建了一个带有 header (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 header 有 \r\n for its line break .这就是 httputil.DumpRequest 返回的内容。但是您可能正在一台不使用 \r\n 作为换行符的机器上编辑这个文件,所以区别就在于此。

成功比较的蛮力方法是:

fmt.Println(strings.Replace(string(str), "\r", "", -1))

它从 HTTP 转储的字符串中删除“\r”,如果您的编辑器仅使用“\n”来破坏预期输出,它将成功比较。

更优雅的解决方案将取决于您的测试环境的具体情况。

关于使用 ExampleTest 进行测试 - 预期输出不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54718136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com