forked from adammck/terraform-inventory
-
Notifications
You must be signed in to change notification settings - Fork 2
/
input_test.go
91 lines (74 loc) · 2 KB
/
input_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"io"
"os"
"path/filepath"
"testing"
"github.com/adammck/venv"
"github.com/blang/vfs"
"github.com/blang/vfs/memfs"
"github.com/stretchr/testify/assert"
)
func TestGetInputPath(t *testing.T) {
assert.Equal(t, ".", GetInputPath(memfs.Create(), venv.Mock()))
assert.Equal(t, "aaa", GetInputPath(memfs.Create(), envWith(map[string]string{"TF_STATE": "aaa"})))
assert.Equal(t, "bbb", GetInputPath(memfs.Create(), envWith(map[string]string{"TI_TFSTATE": "bbb"})))
assert.Equal(t, "terraform.tfstate", GetInputPath(fsWithFiles([]string{"terraform.tfstate"}), venv.Mock()))
assert.Equal(t, ".", GetInputPath(fsWithFiles([]string{".terraform/terraform.tfstate"}), venv.Mock()))
assert.Equal(t, "terraform", GetInputPath(fsWithDirs([]string{"terraform"}), envWith(map[string]string{"TF_STATE": "terraform"})))
}
func envWith(env map[string]string) venv.Env {
e := venv.Mock()
for k, v := range env {
e.Setenv(k, v)
}
return e
}
func fsWithFiles(filenames []string) vfs.Filesystem {
fs := memfs.Create()
var err error
for _, fn := range filenames {
path := filepath.Dir(fn)
if path != "" {
err = vfs.MkdirAll(fs, path, 0700)
if err != nil {
panic(err)
}
}
err = touchFile(fs, fn)
if err != nil {
panic(err)
}
}
return fs
}
func fsWithDirs(dirs []string) vfs.Filesystem {
fs := memfs.Create()
var err error
for _, fp := range dirs {
err = vfs.MkdirAll(fs, fp, 0700)
if err != nil {
panic(err)
}
}
return fs
}
// TODO: Upgrade this later with file contents.
func touchFile(fs vfs.Filesystem, filename string) error {
return writeFile(fs, filename, []byte{}, 0600)
}
// port of ioutil.Writefile for vfs
func writeFile(fs vfs.Filesystem, filename string, data []byte, perm os.FileMode) error {
f, err := fs.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
if err != nil {
return err
}
n, err := f.Write(data)
if err == nil && n < len(data) {
err = io.ErrShortWrite
}
if err1 := f.Close(); err == nil {
err = err1
}
return err
}