Add helmfile state validate policy (#592)

This commit is contained in:
yxxhero
2022-12-21 10:49:31 +08:00
committed by GitHub
parent 8ec51c2826
commit d8d0bf830a
9 changed files with 148 additions and 8 deletions
+37
View File
@@ -0,0 +1,37 @@
// Package policy provides a policy checker for the helmfile state.
package policy
import (
"errors"
)
var (
EnvironmentsAndReleasesWithinSameYamlPartErr = errors.New("environments and releases cannot be defined within the same YAML part. Use --- to extract the environments into a dedicated part")
)
// checkerFunc is a function that checks the helmState.
type checkerFunc func(map[string]interface{}) (bool, error)
func forbidEnvironmentsWithReleases(releaseState map[string]interface{}) (bool, error) {
// forbid environments and releases to be defined at the same yaml part
_, hasEnvironments := releaseState["environments"]
_, hasReleases := releaseState["releases"]
if hasEnvironments && hasReleases {
return false, EnvironmentsAndReleasesWithinSameYamlPartErr
}
return false, nil
}
var checkerFuncs = []checkerFunc{
forbidEnvironmentsWithReleases,
}
// Checker is a policy checker for the helmfile state.
func Checker(helmState map[string]interface{}) (bool, error) {
for _, fn := range checkerFuncs {
if isStrict, err := fn(helmState); err != nil {
return isStrict, err
}
}
return false, nil
}
+54
View File
@@ -0,0 +1,54 @@
package policy
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestForbidEnvironmentsWithReleases(t *testing.T) {
testCases := []struct {
name string
helmState map[string]interface{}
expectedErr bool
isStrict bool
}{
{
name: "no error when only releases",
helmState: map[string]interface{}{
"releases": interface{}(nil),
},
expectedErr: false,
isStrict: false,
},
{
name: "no error when only environments",
helmState: map[string]interface{}{
"environments": map[string]interface{}{},
},
expectedErr: false,
isStrict: false,
},
{
name: "error when both releases and environments",
helmState: map[string]interface{}{
"environments": interface{}(nil),
"releases": interface{}(nil),
},
expectedErr: true,
isStrict: false,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
isStrict, err := forbidEnvironmentsWithReleases(tc.helmState)
require.Equal(t, tc.isStrict, isStrict, "expected isStrict=%v, got=%v", tc.isStrict, isStrict)
if tc.expectedErr {
require.ErrorIsf(t, err, EnvironmentsAndReleasesWithinSameYamlPartErr, "expected error=%v, got=%v", EnvironmentsAndReleasesWithinSameYamlPartErr, err)
} else {
require.NoError(t, err, "expected no error but got error: %v", err)
}
})
}
}