Skip to content

Commit

Permalink
add Len function
Browse files Browse the repository at this point in the history
  • Loading branch information
Stein Fletcher committed Apr 18, 2019
1 parent 2f7e50c commit d150e81
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
15 changes: 15 additions & 0 deletions jsonpath.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,21 @@ func Equal(expression string, expected interface{}) apitest.Assert {
}
}

func Len(expression string, expectedLength int) apitest.Assert {
return func(res *http.Response, req *http.Request) error {
value, err := jsonPath(res.Body, expression)
if err != nil {
return err
}

v := reflect.ValueOf(value)
if v.Len() != expectedLength {
return errors.New(fmt.Sprintf("\"%d\" not equal to \"%d\"", v.Len(), expectedLength))
}
return nil
}
}

func jsonPath(reader io.Reader, expression string) (interface{}, error) {
v := interface{}(nil)
b, err := ioutil.ReadAll(reader)
Expand Down
20 changes: 20 additions & 0 deletions jsonpath_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,26 @@ func Test_IncludesElement(t *testing.T) {
assertFalse(t, found)
}

func TestApiTest_Len(t *testing.T) {
handler := http.NewServeMux()
handler.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
_, err := w.Write([]byte(`{"a": [1, 2, 3], "b": "c"}`))
if err != nil {
panic(err)
}
})

apitest.New().
Handler(handler).
Get("/hello").
Expect(t).
Assert(Len(`$.a`, 3)).
Assert(Len(`$.b`, 1)).
End()
}

func assertTrue(t *testing.T, v bool) {
if !v {
t.Error("\nexpected to be true but was false")
Expand Down

0 comments on commit d150e81

Please sign in to comment.