jx/internal/codec/encoder_test.go

59 lines
1.1 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 TestFile struct {
Path string `json:"path" yaml:"path"`
}
func TestNewYAMLEncoder(t *testing.T) {
var yamlDoc strings.Builder
e := NewYAMLEncoder(&yamlDoc)
assert.NotNil(t, e)
}
func TestNewEncoderEncodeJSON(t *testing.T) {
schema:=`
{
"$id": "file",
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "file",
"type": "object",
"required": [ "path" ],
"properties": {
"path": {
"type": "string",
"description": "file path",
"minLength": 1
}
}
}
`
var jsonDoc strings.Builder
file := &TestFile{}
file.Path = "foo"
e := NewJSONEncoder(&jsonDoc)
assert.NotNil(t, e)
docErr := e.Encode(file)
assert.Nil(t, docErr)
schemaLoader := gojsonschema.NewStringLoader(schema)
loader := gojsonschema.NewStringLoader(jsonDoc.String())
result, err := gojsonschema.Validate(schemaLoader, loader)
assert.Nil(t, err)
assert.True(t, result.Valid())
}