Skip to content

Commit b181f4e

Browse files
requirejson: add ParseFromFile function
Add `ParseFromFile` function, to make it more convienet when reading from files.
1 parent 2a04d1a commit b181f4e

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

Diff for: requirejson/json.go

+11
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ package requirejson
99
import (
1010
"encoding/json"
1111
"fmt"
12+
"os"
1213
"testing"
1314

1415
"github.com/itchyny/gojq"
@@ -35,6 +36,16 @@ func Parse(t *testing.T, jsonData []byte, msgAndArgs ...interface{}) *JQObject {
3536
return &JQObject{t: t, data: data}
3637
}
3738

39+
// ParseFromFile creates a new JQObect from the given file path.
40+
// If the file is not a valid json the test fails.
41+
func ParseFromFile(t *testing.T, filePath string, msgAndArgs ...interface{}) *JQObject {
42+
var data interface{}
43+
jsonData, err := os.ReadFile(filePath)
44+
require.NoError(t, err, msgAndArgs...)
45+
require.NoError(t, json.Unmarshal(jsonData, &data), msgAndArgs...)
46+
return &JQObject{t: t, data: data}
47+
}
48+
3849
// Query performs a query on the given JQObject and returns the first result. If the query
3950
// produces no result the test will fail.
4051
func (obj *JQObject) Query(jqQuery string) *JQObject {

Diff for: requirejson/json_test.go

+25
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@
77
package requirejson_test
88

99
import (
10+
"os"
1011
"testing"
1112

13+
"github.com/stretchr/testify/require"
1214
"go.bug.st/testifyjson/requirejson"
1315
)
1416

@@ -68,3 +70,26 @@ func TestJSONAssertions(t *testing.T) {
6870

6971
requirejson.Parse(t, in).Query(".list").ArrayMustContain("20")
7072
}
73+
74+
func TestParseFromFile(t *testing.T) {
75+
in := []byte(`
76+
{
77+
"id" : 1,
78+
"list" : [
79+
10, 20, 30
80+
]
81+
}
82+
`)
83+
84+
tmpDir := t.TempDir()
85+
testFile, err := os.CreateTemp(tmpDir, "test.json")
86+
require.NoError(t, err)
87+
_, err = testFile.Write(in)
88+
require.NoError(t, err)
89+
require.NoError(t, testFile.Close())
90+
91+
obj := requirejson.ParseFromFile(t, testFile.Name())
92+
obj.Query(".id").MustEqual("1")
93+
obj.Query(".list").ArrayMustContain("20")
94+
obj.Query(".list | length").MustEqual("3")
95+
}

0 commit comments

Comments
 (0)