Skip to content

Instantly share code, notes, and snippets.

@dolmen
Created February 19, 2019 13:19
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 dolmen/39cd8859a7126f5c5580d75af09c1b5a to your computer and use it in GitHub Desktop.
Save dolmen/39cd8859a7126f5c5580d75af09c1b5a to your computer and use it in GitHub Desktop.
Go: checkJSONRoundtrip
package main_test
import (
"encoding/json"
"reflect"
)
func checkJSONRoundtrip(t *testing.T, value interface{}, expectedJSON json.RawMessage) bool {
b, err := json.Marshal(value)
if err != nil {
t.Errorf("%v marshal JSON: %v", value, err)
return false
}
if !bytes.Equal(b, []byte(expectedJSON)) {
var i1, i2 interface{}
e1 := json.Unmarshal(b, &i1)
e2 := json.Unmarshal(expectedJSON, &i2)
if e1 != nil {
t.Fatal(e1)
}
if e2 != nil {
t.Fatal(e2)
}
if !reflect.DeepEqual(i1, i2) {
t.Errorf("%v marshal JSON: mismatch (got %s, expecting %s)", value, b, []byte(expectedJSON))
return false
}
}
target := reflect.New(reflect.TypeOf(value))
err = json.Unmarshal(b, target.Interface())
if !reflect.DeepEqual(target.Elem().Interface(), value) {
t.Errorf("%v unmarshal JSON: got %v", value, target.Elem().Interface())
return false
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment