From 865c0c18b6842adda142ca5748974550869d5c31 Mon Sep 17 00:00:00 2001 From: gedi Date: Wed, 3 May 2017 14:46:10 +0300 Subject: [PATCH] updates api example json matcher --- examples/api/api_test.go | 33 ++++++++++++++++++++++++--------- 1 file changed, 24 insertions(+), 9 deletions(-) diff --git a/examples/api/api_test.go b/examples/api/api_test.go index d406c9c..964ef5a 100644 --- a/examples/api/api_test.go +++ b/examples/api/api_test.go @@ -1,7 +1,6 @@ package main import ( - "bytes" "encoding/json" "fmt" "net/http" @@ -53,23 +52,39 @@ func (a *apiFeature) theResponseCodeShouldBe(code int) error { func (a *apiFeature) theResponseShouldMatchJSON(body *gherkin.DocString) (err error) { var expected, actual []byte - var data interface{} - if err = json.Unmarshal([]byte(body.Content), &data); err != nil { + var exp, act interface{} + + // re-encode expected response + if err = json.Unmarshal([]byte(body.Content), &exp); err != nil { return } - if expected, err = json.Marshal(data); err != nil { + if expected, err = json.MarshalIndent(exp, "", " "); err != nil { return } - actual = bytes.TrimSpace(a.resp.Body.Bytes()) + + // re-encode actual response too + if err = json.Unmarshal(a.resp.Body.Bytes(), &act); err != nil { + return + } + if actual, err = json.MarshalIndent(act, "", " "); err != nil { + return + } + + // the matching may be adapted per different requirements. if len(actual) != len(expected) { - return fmt.Errorf("expected json length: %d does not match actual: %d", len(expected), len(actual)) + return fmt.Errorf( + "expected json length: %d does not match actual: %d:\n%s", + len(expected), + len(actual), + string(actual), + ) } + for i, b := range actual { if b != expected[i] { return fmt.Errorf( - "expected json does not match actual at character: %s^%s", - string(actual[:i]), - string(actual[i:i+1]), + "expected JSON does not match actual, showing up to last matched character:\n%s", + string(actual[:i+1]), ) } }