diff --git a/assertjson/assertjson.go b/assertjson/assertjson.go index 0954e18..f6a4da3 100644 --- a/assertjson/assertjson.go +++ b/assertjson/assertjson.go @@ -91,6 +91,7 @@ type JSONAssertFunc func(json *AssertJSON) // FileHas loads JSON from file and runs user callback for testing its nodes. func FileHas(t *testing.T, filename string, jsonAssert JSONAssertFunc) { + t.Helper() data, err := ioutil.ReadFile(filename) if err != nil { assert.Failf(t, "failed to read file '%s': %s", filename, err.Error()) @@ -100,6 +101,7 @@ func FileHas(t *testing.T, filename string, jsonAssert JSONAssertFunc) { // Has - loads JSON from byte slice and runs user callback for testing its nodes. func Has(t *testing.T, data []byte, jsonAssert JSONAssertFunc) { + t.Helper() body := &AssertJSON{t: t} err := json.Unmarshal(data, &body.data) if err != nil { diff --git a/assertjson/assertjson_test.go b/assertjson/assertjson_test.go index d6c09c8..3fcc62b 100644 --- a/assertjson/assertjson_test.go +++ b/assertjson/assertjson_test.go @@ -1,6 +1,10 @@ package assertjson -import "testing" +import ( + "testing" + + "github.com/stretchr/testify/assert" +) func TestFileHas(t *testing.T) { FileHas(t, "./../test/fixtures/object.json", func(json *AssertJSON) { @@ -15,6 +19,9 @@ func TestFileHas(t *testing.T) { // string assertions json.Node("/stringNode").IsString() json.Node("/stringNode").EqualToTheString("stringValue") + json.Node("/stringNode").AssertString(func(t *testing.T, value string) { + assert.Equal(t, "stringValue", value) + }) json.Node("/stringNode").Matches("^string.*$") json.Node("/stringNode").DoesNotMatch("^notMatch$") json.Node("/stringNode").Contains("string") diff --git a/assertjson/string.go b/assertjson/string.go index e16abfd..1682854 100644 --- a/assertjson/string.go +++ b/assertjson/string.go @@ -1,6 +1,10 @@ package assertjson -import "github.com/stretchr/testify/assert" +import ( + "testing" + + "github.com/stretchr/testify/assert" +) // IsString asserts that the JSON node has a string value. func (node *AssertNode) IsString(msgAndArgs ...interface{}) { @@ -63,3 +67,10 @@ func (node *AssertNode) IsStringWithLengthInRange(min int, max int, msgAndArgs . assert.LessOrEqual(node.t, len(node.value.(string)), max, msgAndArgs...) } } + +// AssertString assert that the JSON node has a string value and it satisfies by user function assertFunc. +func (node *AssertNode) AssertString(assertFunc func(t *testing.T, value string)) { + if node.exists() && assert.IsType(node.t, "", node.value) { + assertFunc(node.t, node.value.(string)) + } +}