登录
首页 >  Golang >  Go问答

测试 ExampleTest 中的预期输出是否不匹配

来源:stackoverflow

时间:2024-03-18 14:15:36 228浏览 收藏

在测试 Go 代码时,您可能会遇到预期输出与实际输出不匹配的情况。这可能是由于 HTTP 标头中的换行符 (\r\n) 差异造成的。您的编辑器可能使用 \n 进行换行,而 httputil.DumpRequest 返回的内容包含 \r\n。为了解决此问题,可以使用字符串替换函数将 \r 从转储的字符串中删除。通过这样做,您可以确保比较的准确性,即使两个字符串在换行符方面存在差异。

问题内容

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

我正在尝试使用示例方法在 go 中编写测试。我创建了一个带有标头(内容类型: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 for its line break。所以这就是 httputil.dumprequest 返回的内容。但您可能在不使用 \r\n 进行换行的计算机上编辑此文件,因此差异就来自于此。

成功比较的强力方法是:

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

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

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

本篇关于《测试 ExampleTest 中的预期输出是否不匹配》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>