-1
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

}
Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
Ankit Deshpande
  • 3,476
  • 1
  • 29
  • 42
  • Can you please post a minimal but complete [https://stackoverflow.com/help/mcve] code snippet? Otherwise it's really hard to help you here – Eli Bendersky Feb 15 '19 at 23:12
  • 1
    @EliBendersky Have added test that I'm trying to execute. The output seems to be the same. Not sure what is the difference here in both the strings – Ankit Deshpande Feb 15 '19 at 23:15
  • Thanks, adding the full example was very helpful - I could reproduce your problem and find what causes it - see answer below – Eli Bendersky Feb 15 '19 at 23:54

1 Answers1

2

I think what's happening is that the HTTP header has \r\n 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 \r\n for line breaks, so the difference comes from there.

A brute-force way to compare successfully would be:

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

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

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

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412