2021-07-21 01:56:28 +00:00
|
|
|
package exec
|
|
|
|
|
|
|
|
import (
|
2022-10-17 18:29:12 +00:00
|
|
|
"io"
|
2021-07-21 01:56:28 +00:00
|
|
|
"os"
|
|
|
|
"path"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
portainer "github.com/portainer/portainer/api"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
)
|
|
|
|
|
|
|
|
func Test_createEnvFile(t *testing.T) {
|
|
|
|
dir := t.TempDir()
|
|
|
|
|
|
|
|
tests := []struct {
|
|
|
|
name string
|
|
|
|
stack *portainer.Stack
|
|
|
|
expected string
|
|
|
|
expectedFile bool
|
|
|
|
}{
|
|
|
|
{
|
|
|
|
name: "should not add env file option if stack doesn't have env variables",
|
|
|
|
stack: &portainer.Stack{
|
|
|
|
ProjectPath: dir,
|
|
|
|
},
|
|
|
|
expected: "",
|
|
|
|
},
|
|
|
|
{
|
|
|
|
name: "should not add env file option if stack's env variables are empty",
|
|
|
|
stack: &portainer.Stack{
|
|
|
|
ProjectPath: dir,
|
|
|
|
Env: []portainer.Pair{},
|
|
|
|
},
|
|
|
|
expected: "",
|
|
|
|
},
|
|
|
|
{
|
|
|
|
name: "should add env file option if stack has env variables",
|
|
|
|
stack: &portainer.Stack{
|
|
|
|
ProjectPath: dir,
|
|
|
|
Env: []portainer.Pair{
|
|
|
|
{Name: "var1", Value: "value1"},
|
|
|
|
{Name: "var2", Value: "value2"},
|
|
|
|
},
|
|
|
|
},
|
|
|
|
expected: "var1=value1\nvar2=value2\n",
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, tt := range tests {
|
|
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
|
|
result, _ := createEnvFile(tt.stack)
|
|
|
|
|
|
|
|
if tt.expected != "" {
|
2021-08-17 01:12:07 +00:00
|
|
|
assert.Equal(t, "stack.env", result)
|
2021-07-21 01:56:28 +00:00
|
|
|
|
|
|
|
f, _ := os.Open(path.Join(dir, "stack.env"))
|
2022-10-17 18:29:12 +00:00
|
|
|
content, _ := io.ReadAll(f)
|
2021-07-21 01:56:28 +00:00
|
|
|
|
|
|
|
assert.Equal(t, tt.expected, string(content))
|
|
|
|
} else {
|
|
|
|
assert.Equal(t, "", result)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
2021-12-09 15:09:34 +00:00
|
|
|
|
2022-07-04 01:16:04 +00:00
|
|
|
func Test_createEnvFile_mergesDefultAndInplaceEnvVars(t *testing.T) {
|
2021-12-09 15:09:34 +00:00
|
|
|
dir := t.TempDir()
|
2022-07-04 01:16:04 +00:00
|
|
|
os.WriteFile(path.Join(dir, ".env"), []byte("VAR1=VAL1\nVAR2=VAL2\n"), 0600)
|
|
|
|
stack := &portainer.Stack{
|
2021-12-09 15:09:34 +00:00
|
|
|
ProjectPath: dir,
|
|
|
|
Env: []portainer.Pair{
|
2022-07-04 01:16:04 +00:00
|
|
|
{Name: "VAR1", Value: "NEW_VAL1"},
|
|
|
|
{Name: "VAR3", Value: "VAL3"},
|
2021-12-09 15:09:34 +00:00
|
|
|
},
|
|
|
|
}
|
2022-07-04 01:16:04 +00:00
|
|
|
result, err := createEnvFile(stack)
|
|
|
|
assert.Equal(t, "stack.env", result)
|
|
|
|
assert.NoError(t, err)
|
|
|
|
assert.FileExists(t, path.Join(dir, "stack.env"))
|
|
|
|
f, _ := os.Open(path.Join(dir, "stack.env"))
|
2022-10-17 18:29:12 +00:00
|
|
|
content, _ := io.ReadAll(f)
|
2022-07-04 01:16:04 +00:00
|
|
|
|
|
|
|
assert.Equal(t, []byte("VAR1=VAL1\nVAR2=VAL2\n\nVAR1=NEW_VAL1\nVAR3=VAL3\n"), content)
|
2021-12-09 15:09:34 +00:00
|
|
|
}
|