Skip to content

Commit

Permalink
Merge pull request #1 from alessio-perugini/add-parse-from-file-path
Browse files Browse the repository at this point in the history
requirejson: add ParseFromFile function
  • Loading branch information
cmaglie authored Jan 9, 2025
2 parents 2a04d1a + b181f4e commit f598506
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
11 changes: 11 additions & 0 deletions requirejson/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ package requirejson
import (
"encoding/json"
"fmt"
"os"
"testing"

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

// ParseFromFile creates a new JQObect from the given file path.
// If the file is not a valid json the test fails.
func ParseFromFile(t *testing.T, filePath string, msgAndArgs ...interface{}) *JQObject {
var data interface{}
jsonData, err := os.ReadFile(filePath)
require.NoError(t, err, msgAndArgs...)
require.NoError(t, json.Unmarshal(jsonData, &data), msgAndArgs...)
return &JQObject{t: t, data: data}
}

// Query performs a query on the given JQObject and returns the first result. If the query
// produces no result the test will fail.
func (obj *JQObject) Query(jqQuery string) *JQObject {
Expand Down
25 changes: 25 additions & 0 deletions requirejson/json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
package requirejson_test

import (
"os"
"testing"

"github.com/stretchr/testify/require"
"go.bug.st/testifyjson/requirejson"
)

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

requirejson.Parse(t, in).Query(".list").ArrayMustContain("20")
}

func TestParseFromFile(t *testing.T) {
in := []byte(`
{
"id" : 1,
"list" : [
10, 20, 30
]
}
`)

tmpDir := t.TempDir()
testFile, err := os.CreateTemp(tmpDir, "test.json")
require.NoError(t, err)
_, err = testFile.Write(in)
require.NoError(t, err)
require.NoError(t, testFile.Close())

obj := requirejson.ParseFromFile(t, testFile.Name())
obj.Query(".id").MustEqual("1")
obj.Query(".list").ArrayMustContain("20")
obj.Query(".list | length").MustEqual("3")
}

0 comments on commit f598506

Please sign in to comment.