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).

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

报告相同问题?

悬赏问题

  • ¥15 有偿求码,CNN+LSTM实现单通道脑电信号EEG的睡眠分期评估
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路