github.com/argoproj/argo-cd@v1.8.7/resource_customizations/health_test.go (about)

     1  package resource_customizations
     2  
     3  import (
     4  	"io/ioutil"
     5  	"os"
     6  	"path/filepath"
     7  	"strings"
     8  	"testing"
     9  
    10  	"github.com/argoproj/gitops-engine/pkg/health"
    11  	"github.com/ghodss/yaml"
    12  	"github.com/stretchr/testify/assert"
    13  	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
    14  
    15  	"github.com/argoproj/argo-cd/util/errors"
    16  	"github.com/argoproj/argo-cd/util/lua"
    17  )
    18  
    19  type TestStructure struct {
    20  	Tests []IndividualTest `yaml:"tests"`
    21  }
    22  
    23  type IndividualTest struct {
    24  	InputPath    string              `yaml:"inputPath"`
    25  	HealthStatus health.HealthStatus `yaml:"healthStatus"`
    26  }
    27  
    28  func getObj(path string) *unstructured.Unstructured {
    29  	yamlBytes, err := ioutil.ReadFile(path)
    30  	errors.CheckError(err)
    31  	obj := make(map[string]interface{})
    32  	err = yaml.Unmarshal(yamlBytes, &obj)
    33  	errors.CheckError(err)
    34  	return &unstructured.Unstructured{Object: obj}
    35  }
    36  
    37  func TestLuaHealthScript(t *testing.T) {
    38  	err := filepath.Walk(".", func(path string, f os.FileInfo, err error) error {
    39  		if !strings.Contains(path, "health.lua") {
    40  			return nil
    41  		}
    42  		errors.CheckError(err)
    43  		dir := filepath.Dir(path)
    44  		yamlBytes, err := ioutil.ReadFile(dir + "/health_test.yaml")
    45  		errors.CheckError(err)
    46  		var resourceTest TestStructure
    47  		err = yaml.Unmarshal(yamlBytes, &resourceTest)
    48  		errors.CheckError(err)
    49  		for i := range resourceTest.Tests {
    50  			test := resourceTest.Tests[i]
    51  			t.Run(test.InputPath, func(t *testing.T) {
    52  				vm := lua.VM{
    53  					UseOpenLibs: true,
    54  				}
    55  				obj := getObj(filepath.Join(dir, test.InputPath))
    56  				script, err := vm.GetHealthScript(obj)
    57  				errors.CheckError(err)
    58  				result, err := vm.ExecuteHealthLua(obj, script)
    59  				errors.CheckError(err)
    60  				assert.Equal(t, &test.HealthStatus, result)
    61  			})
    62  		}
    63  		return nil
    64  	})
    65  	assert.Nil(t, err)
    66  }