Skip to content

Commit

Permalink
add ResHelper.Unmarshal helper
Browse files Browse the repository at this point in the history
  • Loading branch information
ysmood committed Dec 7, 2023
1 parent 5d70e28 commit 64832b0
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
6 changes: 6 additions & 0 deletions utils_req.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,12 @@ func (res *ResHelper) JSON() (v interface{}) {
return res.ut.JSON(res.Body)
}

// Unmarshal body to v as json, it's like [json.Unmarshal].
func (res *ResHelper) Unmarshal(v interface{}) {
res.ut.Helper()
res.ut.err(json.Unmarshal(res.Bytes().Bytes(), v))
}

// Err of request protocol
func (res *ResHelper) Err() error {
return res.err
Expand Down
13 changes: 10 additions & 3 deletions utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,21 @@ func TestHelper(t *testing.T) {
ut.Has(ut.Req("", s.URL("/file")).String(), "ysmood/got")
ut.Eq(ut.Req("", s.URL("/a")).String(), "ok")
ut.Eq(ut.Req("", s.URL("/a")).String(), "ok")
res := ut.Req("", s.URL("/b"))
ut.Eq(res.JSON(), []interface{}{"ok", float64(1)})
ut.Has(res.Header.Get("Content-Type"), "application/json")

ut.Has(ut.Req("", s.URL("/c")).String(), "ysmood/got")
ut.Req(http.MethodPost, s.URL("/d"), 1)
ut.Req(http.MethodPost, s.URL("/f"), http.Header{"Test-Header": {"ok"}, "Host": {"test.com"}}, got.ReqMIME(".json"), 1)
ut.Has(ut.Req("", s.URL("/timeout"), ut.Timeout(100*time.Millisecond)).Err().Error(), "context deadline exceeded")
ut.Has(ut.Req("", string(rune(0x7f))).Err().Error(), `invalid control character in URL`)

res := ut.Req("", s.URL("/b"))
ut.Eq(res.JSON(), []interface{}{"ok", float64(1)})
ut.Has(res.Header.Get("Content-Type"), "application/json")

res = ut.Req("", s.URL("/b"))
var v []interface{}
res.Unmarshal(&v)
ut.Eq(v, []interface{}{"ok", 1.0})
}

ut.DoAfter(time.Hour, func() {})
Expand Down

0 comments on commit 64832b0

Please sign in to comment.