nurse/validation/jsonpath_test.go

89 lines
2.1 KiB
Go
Raw Permalink Normal View History

package validation_test
import (
"testing"
2022-09-22 09:46:36 +00:00
"code.icb4dc0.de/prskr/nurse/validation"
)
2022-09-27 20:19:27 +00:00
type jsonPathValidatorEqualsTestCase[V validation.Value] struct {
testName string
expected V
jsonPath string
json string
2022-06-09 20:12:45 +00:00
wantErr bool
}
2022-09-27 20:19:27 +00:00
func (tt jsonPathValidatorEqualsTestCase[V]) name() string {
return tt.testName
}
2022-06-09 20:12:45 +00:00
//nolint:thelper // is not a helper
2022-09-27 20:19:27 +00:00
func (tt jsonPathValidatorEqualsTestCase[V]) run(t *testing.T) {
t.Parallel()
t.Helper()
validator, err := validation.JSONPathValidatorFor(tt.jsonPath, tt.expected)
if err != nil {
t.Fatalf("JSONPathValidatorFor() err = %v", err)
}
2022-06-09 20:12:45 +00:00
if err := validator.Equals(tt.json); err != nil {
if !tt.wantErr {
t.Errorf("Failed to equal value in %s to %v: %v", tt.json, tt.expected, err)
}
}
}
func TestJSONPathValidator_Equals(t *testing.T) {
t.Parallel()
tests := []testCase{
2022-09-27 20:19:27 +00:00
jsonPathValidatorEqualsTestCase[string]{
testName: "Simple object navigation",
expected: "hello",
jsonPath: "$.greeting",
json: `{"greeting": "hello"}`,
2022-06-09 20:12:45 +00:00
wantErr: false,
},
2022-09-27 20:19:27 +00:00
jsonPathValidatorEqualsTestCase[string]{
testName: "Simple object navigation - number as string",
expected: "42",
jsonPath: "$.number",
json: `{"number": 42}`,
2022-06-09 20:12:45 +00:00
wantErr: false,
},
2022-09-27 20:19:27 +00:00
jsonPathValidatorEqualsTestCase[string]{
testName: "Simple array navigation",
expected: "world",
jsonPath: "$[1]",
json: `["hello", "world"]`,
2022-06-09 20:12:45 +00:00
wantErr: false,
},
2022-09-27 20:19:27 +00:00
jsonPathValidatorEqualsTestCase[int]{
testName: "Simple array navigation - string to int",
expected: 37,
jsonPath: "$[1]",
json: `["13", "37"]`,
2022-06-09 20:12:45 +00:00
wantErr: false,
},
2022-09-27 20:19:27 +00:00
jsonPathValidatorEqualsTestCase[int]{
testName: "Simple array navigation - string to int - wrong value",
expected: 42,
jsonPath: "$[1]",
json: `["13", "37"]`,
2022-06-09 20:12:45 +00:00
wantErr: true,
},
2022-09-27 20:19:27 +00:00
jsonPathValidatorEqualsTestCase[string]{
testName: "Simple array navigation - int to string",
expected: "37",
jsonPath: "$[1]",
json: `[13, 37]`,
2022-06-09 20:12:45 +00:00
wantErr: false,
},
}
//nolint:paralleltest
for _, tt := range tests {
tt := tt
t.Run(tt.name(), tt.run)
}
}