Skip to content

Commit

Permalink
improve json tests
Browse files Browse the repository at this point in the history
  • Loading branch information
MarkRosemaker committed Jan 2, 2025
1 parent 795e733 commit bf24c13
Showing 1 changed file with 26 additions and 19 deletions.
45 changes: 26 additions & 19 deletions ref_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,13 @@ import (

_json "github.com/MarkRosemaker/openapi/internal/json"
"github.com/go-json-experiment/json"
"github.com/go-json-experiment/json/jsontext"
)

var typeRefEmptyStruct = reflect.TypeFor[refEmptyStruct]()
var (
typeRefEmptyStruct = reflect.TypeFor[refEmptyStruct]()
typeEmptyStruct = reflect.TypeFor[emptyStruct]()
)

type (
refEmptyStruct = refOrValue[emptyStruct, *emptyStruct]
Expand All @@ -18,19 +22,20 @@ type (

func (emptyStruct) Validate() error { return nil }

func isJSONSemanticError(t *testing.T, err error, goType reflect.Type) error {
func errAs[T any, E interface {
*T
error
}](t *testing.T, err error,
) E {
t.Helper()

jsonErr := &json.SemanticError{}
if !errors.As(err, &jsonErr) {
t.Fatalf("expected json.SemanticError, got: %v", err)
}

if goType != jsonErr.GoType {
t.Fatalf("json.SemanticError is not of type %s but of %s", goType, jsonErr.GoType)
var zero T
target := E(&zero)
if !errors.As(err, &target) {
t.Fatalf("want: %T, got: %T", target, err)
}

return jsonErr.Err
return target
}

func TestRef_UnmarshalJSONV2(t *testing.T) {
Expand All @@ -39,21 +44,23 @@ func TestRef_UnmarshalJSONV2(t *testing.T) {
t.Run("reference", func(t *testing.T) {
err := json.Unmarshal([]byte(`{"$ref":"#/components/schemas/Pet"`),
&refEmptyStruct{}, _json.Options)
err = isJSONSemanticError(t, err, typeRefEmptyStruct)

if want := "unexpected EOF"; err.Error() != want {
t.Fatalf("want: %s, got: %s", want, err)
synErr := errAs[jsontext.SyntacticError](t, err)
if synErr.JSONPointer != "" || synErr.ByteOffset != 34 ||
synErr.Err.Error() != "unexpected EOF" {
t.Fatalf("got: %#v", synErr.Err)
}
})

t.Run("object", func(t *testing.T) {
err := json.Unmarshal([]byte([]byte(`{"foo":"bar"}`)),
&refEmptyStruct{}, _json.Options)
err = isJSONSemanticError(t, err, typeRefEmptyStruct)
err = isJSONSemanticError(t, err, reflect.TypeFor[emptyStruct]())

if want := `unknown name "foo"`; err.Error() != want {
t.Fatalf("want: %s, got: %s", want, err)
semErr := errAs[json.SemanticError](t, err)
if semErr.GoType != typeRefEmptyStruct {
t.Fatalf("want: %s, got: %s", typeRefEmptyStruct, semErr.GoType)
} else if semErr = errAs[json.SemanticError](t, semErr.Err); semErr.GoType != typeEmptyStruct {
t.Fatalf("want: %s, got: %s", typeEmptyStruct, semErr.GoType)
} else if want := "unknown object member name"; semErr.Err.Error() != want {
t.Fatalf("want: %s, got: %q", want, semErr.Err)
}
})
}

0 comments on commit bf24c13

Please sign in to comment.