Skip to content

Commit

Permalink
Fix parser test
Browse files Browse the repository at this point in the history
  • Loading branch information
saffage committed Aug 11, 2024
1 parent 3fcd112 commit d121f92
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions parser/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package parser
import (
"encoding/json"
"os"
"reflect"
"testing"

"github.com/saffage/jet/ast"
Expand All @@ -18,6 +19,7 @@ func TestMatchSequence(t *testing.T) {
{Kind: token.Ident},
{Kind: token.At},
{Kind: token.Ident},
{Kind: token.EOF},
}
p := New(tokens, DefaultFlags)
kinds := []token.Kind{token.At, token.Ident}
Expand Down Expand Up @@ -108,31 +110,35 @@ func TestExprs(t *testing.T) {
} else {
stmts, err = Parse(tokens, c.parserFlags)
}

if !checkError(t, err, c.error) {
return
}

if c.expectedJSON != "" {
filename := "./testdata/" + c.expectedJSON
expect, err := os.ReadFile(filename)

if err != nil {
t.Errorf("unexpected error while reading file '%s': %s", filename, err)
return
}

actual, err := json.MarshalIndent(stmts, "", "\t")

if err != nil {
t.Error("unexpected JSON marshal error:", err)
return
}

if string(actual) != string(expect) {
if equal, err := JSONBytesEqual(actual, expect); err != nil {
t.Error(err)
} else if !equal {
t.Errorf(
"invalid AST was parsed\nexpect %s\nactual %s",
string(expect),
string(actual),
)
return
}
} else {
encoded, err := json.MarshalIndent(stmts, "", " ")
Expand Down Expand Up @@ -173,3 +179,17 @@ func checkError(t *testing.T, got, want error) bool {

return true
}

func JSONBytesEqual(a, b []byte) (bool, error) {
var jsonA, jsonB any

if err := json.Unmarshal(a, &jsonA); err != nil {
return false, err
}

if err := json.Unmarshal(b, &jsonB); err != nil {
return false, err
}

return reflect.DeepEqual(jsonB, jsonA), nil
}

0 comments on commit d121f92

Please sign in to comment.