116 lines
2.3 KiB
Go
116 lines
2.3 KiB
Go
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
|
|
package resource
|
|
|
|
import (
|
|
"context"
|
|
"os"
|
|
"fmt"
|
|
"log"
|
|
"strings"
|
|
"path/filepath"
|
|
"testing"
|
|
"github.com/stretchr/testify/assert"
|
|
)
|
|
|
|
func TestNewDocumentLoader(t *testing.T) {
|
|
d := NewDocument()
|
|
assert.NotEqual(t, nil, d)
|
|
}
|
|
|
|
func TestDocumentLoader(t *testing.T) {
|
|
dir, err := os.MkdirTemp("", "testdocumentloader")
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer os.RemoveAll(dir)
|
|
|
|
file,_ := filepath.Abs(filepath.Join(dir, "foo.txt"))
|
|
|
|
document := fmt.Sprintf(`
|
|
---
|
|
resources:
|
|
- type: file
|
|
attributes:
|
|
path: "%s"
|
|
owner: "nobody"
|
|
group: "nobody"
|
|
mode: "0600"
|
|
content: |-
|
|
test line 1
|
|
test line 2
|
|
state: present
|
|
- type: user
|
|
attributes:
|
|
name: "testuser"
|
|
uid: "10022"
|
|
gid: "10022"
|
|
home: "/home/testuser"
|
|
state: present
|
|
`, file)
|
|
|
|
d := NewDocument()
|
|
assert.NotEqual(t, nil, d)
|
|
|
|
docReader := strings.NewReader(document)
|
|
|
|
e := d.Load(docReader)
|
|
assert.Equal(t, nil, e)
|
|
|
|
resources := d.Resources()
|
|
assert.Equal(t, 2, len(resources))
|
|
}
|
|
|
|
func TestDocumentGenerator(t *testing.T) {
|
|
ctx := context.Background()
|
|
|
|
fileContent := `// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
|
|
`
|
|
|
|
file,_ := filepath.Abs(filepath.Join(TempDir, "foo.txt"))
|
|
|
|
err := os.WriteFile(file, []byte(fileContent), 0644)
|
|
assert.Nil(t, err)
|
|
|
|
expected := fmt.Sprintf(`
|
|
resources:
|
|
- type: file
|
|
attributes:
|
|
path: %s
|
|
owner: "root"
|
|
group: "root"
|
|
mode: "0644"
|
|
content: |
|
|
%s
|
|
filetype: "regular"
|
|
state: present
|
|
`, file, fileContent)
|
|
|
|
var documentYaml strings.Builder
|
|
d := NewDocument()
|
|
assert.NotEqual(t, nil, d)
|
|
|
|
f,e := ResourceTypes.New("file://")
|
|
assert.Nil(t, e)
|
|
assert.NotNil(t, f)
|
|
|
|
f.(*File).Path = filepath.Join(TempDir, "foo.txt")
|
|
f.(*File).Read(ctx)
|
|
d.AddResourceDeclaration("file", f)
|
|
|
|
ey := d.Generate(&documentYaml)
|
|
assert.Equal(t, nil, ey)
|
|
|
|
assert.Greater(t, documentYaml.Len(), 0)
|
|
assert.YAMLEq(t, documentYaml.String(), expected)
|
|
}
|
|
|
|
func TestDocumentAddResource(t *testing.T) {
|
|
file,_ := filepath.Abs(filepath.Join(TempDir, "foo.txt"))
|
|
err := os.WriteFile(file, []byte(""), 0644)
|
|
assert.Nil(t, err)
|
|
|
|
d := NewDocument()
|
|
assert.NotNil(t, d)
|
|
d.AddResource(fmt.Sprintf("file://%s", file))
|
|
}
|