Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix some missing log informations and add VerifyJSON assert method #15

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ before_install:
- go get -u -v github.com/axw/gocov/gocov
- go get -u -v github.com/mattn/goveralls
- go get -u -v github.com/golang/lint/golint
- go get -u -v github.com/mitchellh/mapstructure
- mkdir -p $GOPATH/src/gopkg.in/h2non
- ln -s $(pwd) $GOPATH/src/gopkg.in/h2non/baloo.v2

Expand Down
28 changes: 28 additions & 0 deletions _examples/assert_json/json_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
package assert_json

import (
"fmt"
"strings"
"testing"

"github.com/mitchellh/mapstructure"
baloo "gopkg.in/h2non/baloo.v2"
)

type UserAgent struct {
Value string `mapstructure:"user-agent"`
}

// test stores the HTTP testing client preconfigured
var test = baloo.New("http://httpbin.org")

Expand All @@ -18,3 +25,24 @@ func TestBalooJSONAssertion(t *testing.T) {
JSON(`{"user-agent":"baloo/` + baloo.Version + `"}`).
Done()
}

func TestBalooJSONCustomAssertion(t *testing.T) {
test.Get("/user-agent").
SetHeader("Foo", "Bar").
Expect(t).
Status(200).
Type("json").
JSON(`{"user-agent":"baloo/` + baloo.Version + `"}`).
VerifyJSON(func(data map[string]interface{}) error {
var result UserAgent
err := mapstructure.Decode(data, &result)
if err != nil {
return err
}
if !strings.Contains(result.Value, "baloo") {
return fmt.Errorf("bad user-agent: %s, %s", result.Value, data)
}
return nil
}).
Done()
}
5 changes: 3 additions & 2 deletions assert/body.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@ func BodyMatchString(pattern string) Func {
if err != nil {
return err
}
if match, _ := regexp.MatchString(pattern, string(body)); !match {
return fmt.Errorf("body mismatch: pattern not found '%s'", pattern)
sbody := string(body)
if match, _ := regexp.MatchString(pattern, sbody); !match {
return fmt.Errorf("body mismatch: pattern not found '%s' in '%s'", pattern, sbody)
}
return nil
}
Expand Down
18 changes: 18 additions & 0 deletions assert/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import (
"reflect"
)

// FnJSONVerify callable function that take a JSON map, test this data and can return an error.
type FnJSONVerify func(map[string]interface{}) error

func unmarshal(buf []byte) (map[string]interface{}, error) {
data := make(map[string]interface{})
if err := json.Unmarshal(buf, &data); err != nil {
Expand All @@ -23,6 +26,7 @@ func unmarshalBody(res *http.Response) (map[string]interface{}, error) {
if err != nil {
return nil, err
}
res.Body = ioutil.NopCloser(bytes.NewBuffer(body))
if len(body) == 0 {
return nil, nil
}
Expand Down Expand Up @@ -109,3 +113,17 @@ func JSON(data interface{}) Func {
return compare(body, data)
}
}

// VerifyJSON extract JSON in body and call fn with result
// write your own test on data
func VerifyJSON(fn FnJSONVerify) Func {
return func(res *http.Response, req *http.Request) error {
// Read and unmarshal response body as JSON
body, err := unmarshalBody(res)
if err != nil {
return err
}

return fn(body)
}
}
11 changes: 10 additions & 1 deletion expect.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,13 @@ func (e *Expect) JSON(data interface{}) *Expect {
return e
}

// VerifyJSON asserts the response body with the given function
// write your own test on data
func (e *Expect) VerifyJSON(fn assert.FnJSONVerify) *Expect {
e.AssertFunc(assert.VerifyJSON(fn))
return e
}

// JSONSchema asserts the response body with the given
// JSON schema definition.
func (e *Expect) JSONSchema(schema string) *Expect {
Expand Down Expand Up @@ -196,7 +203,9 @@ func (e *Expect) Done() error {
// Run assertions
err = e.run(res.RawResponse, res.RawRequest)
if err != nil {
e.test.Error(err)
logerrorf(e.test, err.Error())
Dump(e.test, res.RawResponse)

}

return err
Expand Down
121 changes: 121 additions & 0 deletions log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
package baloo

/// Come from https://github.com/emicklei/forest/
// LICENSE MIT https://github.com/emicklei/forest/blob/master/LICENSE.txt

import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"runtime"
"strings"
"testing"
)

var scanStackForFile = true
var logfFunc = logf

const noStackOffset = 0

// Logf adds the actual file:line information to the log message
func Logf(t *testing.T, format string, args ...interface{}) {
logfFunc(t, noStackOffset, "\n"+format, args...)
}

func logfatal(t *testing.T, format string, args ...interface{}) {
logfFunc(t, noStackOffset, format, args...)
t.FailNow()
}

// Error is equivalent to Log followed by Fail.
func logerror(t *testing.T, args ...interface{}) {
logerrorf(t, "\terror: "+tabify("%s")+"\n", args)
}

func logerrorf(t *testing.T, format string, args ...interface{}) {
logfFunc(t, noStackOffset, format, args...)
t.Fail()
}

func logf(t *testing.T, stackOffset int, format string, args ...interface{}) {
var file string
var line int
var ok bool
if scanStackForFile {
offset := 0
outside := false
for !outside {
_, file, line, ok = runtime.Caller(2 + offset)
outside = !strings.Contains(file, "/baloo/")
offset++
}
} else {
_, file, line, ok = runtime.Caller(2)
}
if ok {
// Truncate file name at last file name separator.
if index := strings.LastIndex(file, "/"); index >= 0 {
file = file[index+1:]
} else if index = strings.LastIndex(file, "\\"); index >= 0 {
file = file[index+1:]
}
} else {
file = "???"
line = 1
}
t.Logf("<-- %s:%d "+format, append([]interface{}{file, line}, args...)...)
}

// Dump is a convenient method to log the full contents of a request and its response.
func Dump(t *testing.T, resp *http.Response) {
// dump request
var buffer bytes.Buffer
buffer.WriteString("\n")
buffer.WriteString(fmt.Sprintf("%v %v\n", resp.Request.Method, resp.Request.URL))
for k, v := range resp.Request.Header {
if len(k) > 0 {
buffer.WriteString(fmt.Sprintf("%s : %v\n", k, strings.Join(v, ",")))
}
}
if resp == nil {
buffer.WriteString("-- no response --")
Logf(t, buffer.String())
return
}
// dump response
buffer.WriteString(fmt.Sprintf("\n%s\n", resp.Status))
for k, v := range resp.Header {
if len(k) > 0 {
buffer.WriteString(fmt.Sprintf("%s : %v\n", k, strings.Join(v, ",")))
}
}
if resp.Body != nil {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
if resp.StatusCode/100 == 3 {
// redirect closes body ; nothing to read
buffer.WriteString("\n")
} else {
buffer.WriteString(fmt.Sprintf("unable to read body:%v", err))
}
} else {
if len(body) > 0 {
buffer.WriteString("\n")
}
buffer.WriteString(string(body))
}
resp.Body.Close()
// put the body back for re-reads
resp.Body = ioutil.NopCloser(bytes.NewReader(body))
}
buffer.WriteString("\n")
Logf(t, buffer.String())
}

func tabify(format string) string {
if strings.HasPrefix(format, "\n") {
return strings.Replace(format, "\n", "\n\t\t", 1)
}
return format
}