github.com/interconnectedcloud/qdr-operator@v0.0.0-20210826174505-576d2b33dac7/test/crd_validation_test.go (about)

     1  package test
     2  
     3  import (
     4  	"github.com/RHsyseng/operator-utils/pkg/validation"
     5  	"github.com/ghodss/yaml"
     6  	interconnectv1alpha1 "github.com/interconnectedcloud/qdr-operator/pkg/apis/interconnectedcloud/v1alpha1"
     7  	"github.com/stretchr/testify/assert"
     8  	"io/ioutil"
     9  	"strings"
    10  	"testing"
    11  )
    12  
    13  var crdTypeMap = map[string]interface{}{
    14  	"interconnectedcloud_v1alpha1_interconnect_crd.yaml": &interconnectv1alpha1.Interconnect{},
    15  }
    16  
    17  func TestCRDSchemas(t *testing.T) {
    18  	for crdFileName, amqType := range crdTypeMap {
    19  		schema := getSchema(t, crdFileName)
    20  		missingEntries := schema.GetMissingEntries(amqType)
    21  		for _, missing := range missingEntries {
    22  			if strings.HasPrefix(missing.Path, "/status/conditions/transitionTime/") {
    23  				//skill detailed properties of transition Time.
    24  			} else {
    25  				assert.Fail(t, "Discrepancy between CRD and Struct",
    26  					"Missing or incorrect schema validation at %v, expected type %v  in CRD file %v", missing.Path, missing.Type, crdFileName)
    27  			}
    28  		}
    29  	}
    30  }
    31  
    32  func TestSampleCustomResources(t *testing.T) {
    33  
    34  	var crFileName, crdFileName string = "interconnectedcloud_v1alpha1_interconnect_cr.yaml", "interconnectedcloud_v1alpha1_interconnect_crd.yaml"
    35  	assert.NotEmpty(t, crdFileName, "No matching CRD file found for CR suffixed: %s", crFileName)
    36  
    37  	schema := getSchema(t, crdFileName)
    38  	yamlString, err := ioutil.ReadFile("../deploy/crds/" + crFileName)
    39  	assert.NoError(t, err, "Error reading %v CR yaml", crFileName)
    40  	var input map[string]interface{}
    41  	assert.NoError(t, yaml.Unmarshal([]byte(yamlString), &input))
    42  	assert.NoError(t, schema.Validate(input), "File %v does not validate against the CRD schema", crFileName)
    43  }
    44  
    45  func getSchema(t *testing.T, crdFile string) validation.Schema {
    46  
    47  	yamlString, err := ioutil.ReadFile("../deploy/crds/" + crdFile)
    48  	assert.NoError(t, err, "Error reading CRD yaml %v", yamlString)
    49  
    50  	schema, err := validation.New([]byte(yamlString))
    51  	assert.NoError(t, err)
    52  
    53  	return schema
    54  }