Created
February 19, 2019 13:19
-
-
Save dolmen/39cd8859a7126f5c5580d75af09c1b5a to your computer and use it in GitHub Desktop.
Go: checkJSONRoundtrip
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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