Skip to content

Instantly share code, notes, and snippets.

@icio
Last active December 8, 2017 22:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save icio/849a85cba6c9b97bed4c5233f0760675 to your computer and use it in GitHub Desktop.
Save icio/849a85cba6c9b97bed4c5233f0760675 to your computer and use it in GitHub Desktop.
Example of using sentinel values with github.com/google/go-cmp
package example_test
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/google/go-cmp/cmp"
)
type Object struct {
String string `json:"string,omitempty"`
Int int `json:"int,omitempty"`
Object *Object `json:"object,omitempty"`
}
// Handler writes a {"string": "a", "object": {"string": "b"}} in response.
func Handler(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(&Object{
String: "A",
Object: &Object{
String: "B",
Object: &Object{
String: "C",
},
},
})
}
var (
// ignore is our sentinel value for ignoring map fields.
ignore = struct{}{}
// ignoreOpt is how we tell cmp.Diff and cmp.Equal to discount ignore values.
ignoreOpt = cmp.FilterValues(
func(a, b interface{}) bool {
return a == ignore || b == ignore
},
cmp.Ignore(),
)
)
// TestHandler demonstrates comparing interface{} values which we might do if
// we're checking the contents of a JSON body.
func TestHandler(t *testing.T) {
var actual interface{}
// Get the parsed value from the handler response.
r := httptest.NewRecorder()
Handler(r, httptest.NewRequest("POST", "/", nil))
json.NewDecoder(r.Result().Body).Decode(&actual)
// Our expected template.
expected := map[string]interface{}{
"string": "A",
"object": map[string]interface{}{
"string": ignore,
"object": map[string]interface{}{
"string": "C",
},
},
}
if d := cmp.Diff(expected, actual, ignoreOpt); d != "" {
t.Errorf("Unexpected diff:\n%s", d)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment