jx/internal/codec/decoder_test.go

81 lines
1.6 KiB
Go
Raw Normal View History

2024-05-14 16:53:47 +00:00
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package codec
import (
_ "fmt"
"github.com/stretchr/testify/assert"
_ "log"
"strings"
"testing"
"github.com/xeipuuv/gojsonschema"
)
type TestUser struct {
Name string `json:"name" yaml:"name"`
Uid string `json:"uid" yaml:"uid"`
Group string `json:"group" yaml:"group"`
Home string `json:"home" yaml:"home"`
State string `json:"state" yaml:"state"`
}
func TestNewYAMLDecoder(t *testing.T) {
e := NewYAMLDecoder(strings.NewReader(""))
assert.NotNil(t, e)
}
func TestNewDecoderDecodeJSON(t *testing.T) {
schema:=`
{
"$id": "user",
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "user",
"type": "object",
"required": [ "name" ],
"properties": {
"path": {
"type": "string",
"description": "user name",
"minLength": 1
}
}
}
`
decl := `{
"name": "testuser",
"uid": "12001",
"group": "12001",
"home": "/home/testuser",
"state": "present"
}`
jsonReader := strings.NewReader(decl)
user := &TestUser{}
e := NewJSONDecoder(jsonReader)
assert.NotNil(t, e)
docErr := e.Decode(user)
assert.Nil(t, docErr)
schemaLoader := gojsonschema.NewStringLoader(schema)
loader := gojsonschema.NewStringLoader(decl)
result, validateErr := gojsonschema.Validate(schemaLoader, loader)
assert.True(t, result.Valid())
assert.Nil(t, validateErr)
}
func TestNewJSONStringDecoder(t *testing.T) {
decl := `{
"name": "testuser",
"uid": "12001",
"group": "12001",
"home": "/home/testuser",
"state": "present"
}`
e := NewJSONStringDecoder(decl)
assert.NotNil(t, e)
docErr := e.Decode(&TestUser{})
assert.Nil(t, docErr)
}