duanpu8830 2019-02-15 23:01
浏览 66
已采纳

使用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

I'm trying to write test in go using the Example method. I have created a http request with header (Content-Type: application/json), query param t=1, method type POST and URL localhost.

The output in got: and want: looks to be the same, have also checked for whitespace characters. Not able to figure out what is the difference between these two here.

Not able to figure out what am I missing here.

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

}
  • 写回答

1条回答 默认 最新

  • dongyou5098 2019-02-15 23:28
    关注

    I think what's happening is that the HTTP header has for its line break. So this is what httputil.DumpRequest returns. But you're probably editing this file on a machine that doesn't use for line breaks, so the difference comes from there.

    A brute-force way to compare successfully would be:

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

    Which removes the ""s from the string dumped by HTTP and it will compare successfully if your editor used only " " to break the expected output.

    A more elegant solution would depend on the specifics of your testing environment(s).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证