133 lines
2.4 KiB
Go
133 lines
2.4 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"
|
|
"testing"
|
|
)
|
|
|
|
func TestNewFileResource(t *testing.T) {
|
|
f := NewFile()
|
|
assert.NotEqual(t, nil, f)
|
|
}
|
|
|
|
func TestApplyResourceTransformation(t *testing.T) {
|
|
f := NewFile()
|
|
assert.NotEqual(t, nil, f)
|
|
|
|
//e := f.Apply()
|
|
//assert.Equal(t, nil, e)
|
|
}
|
|
|
|
func TestReadFile(t *testing.T) {
|
|
ctx := context.Background()
|
|
file, _ := filepath.Abs(filepath.Join(TempDir, "fooread.txt"))
|
|
|
|
decl := fmt.Sprintf(`
|
|
path: "%s"
|
|
owner: "nobody"
|
|
group: "nobody"
|
|
mode: "0600"
|
|
content: |-
|
|
test line 1
|
|
test line 2
|
|
filetype: "regular"
|
|
state: present
|
|
`, file)
|
|
|
|
testFile := NewFile()
|
|
e := testFile.LoadDecl(decl)
|
|
assert.Equal(t, nil, e)
|
|
testFile.Apply()
|
|
|
|
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)
|
|
assert.YAMLEq(t, decl, string(r))
|
|
}
|
|
|
|
func TestCreateFile(t *testing.T) {
|
|
file, _ := filepath.Abs(filepath.Join(TempDir, "foo.txt"))
|
|
|
|
decl := fmt.Sprintf(`
|
|
path: "%s"
|
|
owner: "nobody"
|
|
group: "nobody"
|
|
mode: "0600"
|
|
content: |-
|
|
test line 1
|
|
test line 2
|
|
state: present
|
|
`, file)
|
|
|
|
f := NewFile()
|
|
e := f.LoadDecl(decl)
|
|
assert.Equal(t, nil, e)
|
|
assert.Equal(t, "nobody", f.Owner)
|
|
|
|
applyErr := f.Apply()
|
|
assert.Equal(t, nil, applyErr)
|
|
assert.FileExists(t, file, nil)
|
|
s, e := os.Stat(file)
|
|
assert.Equal(t, nil, e)
|
|
|
|
assert.Greater(t, s.Size(), int64(0))
|
|
|
|
f.State = "absent"
|
|
assert.Equal(t, nil, f.Apply())
|
|
assert.NoFileExists(t, file, nil)
|
|
}
|
|
|
|
func TestFileType(t *testing.T) {
|
|
fileType := []byte(`
|
|
filetype: "directory"
|
|
`)
|
|
var testFile File
|
|
err := yaml.Unmarshal(fileType, &testFile)
|
|
assert.Nil(t, err)
|
|
|
|
}
|
|
|
|
func TestFileDirectory(t *testing.T) {
|
|
file, _ := filepath.Abs(filepath.Join(TempDir, "testdir"))
|
|
|
|
decl := fmt.Sprintf(`
|
|
path: "%s"
|
|
owner: "nobody"
|
|
group: "nobody"
|
|
mode: "0700"
|
|
filetype: "directory"
|
|
state: present
|
|
`, file)
|
|
|
|
f := NewFile()
|
|
e := f.LoadDecl(decl)
|
|
assert.Equal(t, nil, e)
|
|
assert.Equal(t, "nobody", f.Owner)
|
|
|
|
applyErr := f.Apply()
|
|
assert.Equal(t, nil, applyErr)
|
|
assert.DirExists(t, file)
|
|
|
|
f.State = "absent"
|
|
deleteErr := f.Apply()
|
|
assert.Nil(t, deleteErr)
|
|
assert.NoDirExists(t, file)
|
|
}
|