jx/internal/resource/schema_test.go
Matthew Rich 5a49359722
Some checks failed
Lint / golangci-lint (push) Failing after 10m8s
Declarative Tests / test (push) Successful in 54s
add encoder/decoder support for json and yaml
add support for jsonschema verification
2024-04-03 09:54:50 -07:00

81 lines
1.6 KiB
Go

// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
package resource
import (
"context"
"encoding/json"
"fmt"
"github.com/stretchr/testify/assert"
_ "gopkg.in/yaml.v3"
_ "io"
_ "log"
_ "net/http"
_ "net/http/httptest"
_ "net/url"
"os"
"path/filepath"
_ "strings"
"syscall"
"testing"
"time"
)
func TestNewSchema(t *testing.T) {
s := NewSchema("document")
assert.NotEqual(t, nil, s)
}
func TestSchemaValidate(t *testing.T) {
ctx := context.Background()
s := NewSchema("file")
assert.NotEqual(t, nil, s)
file, _ := filepath.Abs(filepath.Join(TempDir, "fooread.txt"))
declarationAttributes := `
path: "%s"
owner: "nobody"
group: "nobody"
mode: "0600"
atime: 2001-12-15T01:01:01.000000001Z
ctime: %s
mtime: 2001-12-15T01:01:01.000000001Z
content: |-
test line 1
test line 2
filetype: "regular"
state: present
`
decl := fmt.Sprintf(declarationAttributes, file, "2001-12-15T01:01:01.000000001Z")
testFile := NewFile()
e := testFile.LoadDecl(decl)
assert.Equal(t, nil, e)
testFile.Apply()
jsonDoc, jsonErr := json.Marshal(testFile)
assert.Nil(t, jsonErr)
schemaErr := s.Validate(string(jsonDoc))
assert.Nil(t, schemaErr)
f := NewFile()
assert.NotEqual(t, nil, f)
f.Path = file
r, e := f.Read(ctx)
assert.Equal(t, nil, e)
assert.Equal(t, "nobody", f.Owner)
info, statErr := os.Stat(file)
assert.Nil(t, statErr)
stat, ok := info.Sys().(*syscall.Stat_t)
assert.True(t, ok)
cTime := time.Unix(int64(stat.Ctim.Sec), int64(stat.Ctim.Nsec))
expected := fmt.Sprintf(declarationAttributes, file, cTime.Format(time.RFC3339Nano))
assert.YAMLEq(t, expected, string(r))
}