Skip to content

Commit

Permalink
assert string method added
Browse files Browse the repository at this point in the history
  • Loading branch information
strider2038 committed Apr 8, 2021
1 parent 40a8bd5 commit 355de3f
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
2 changes: 2 additions & 0 deletions assertjson/assertjson.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand All @@ -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 {
Expand Down
9 changes: 8 additions & 1 deletion assertjson/assertjson_test.go
Original file line number Diff line number Diff line change
@@ -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) {
Expand All @@ -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")
Expand Down
13 changes: 12 additions & 1 deletion assertjson/string.go
Original file line number Diff line number Diff line change
@@ -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{}) {
Expand Down Expand Up @@ -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))
}
}

0 comments on commit 355de3f

Please sign in to comment.