...

Source file src/edge-infra.dev/test/fixtures/fixtures.go

Documentation: edge-infra.dev/test/fixtures

     1  // Package fixtures provides functions for loading embedded test fixtures used
     2  // by various tests.
     3  package fixtures
     4  
     5  import (
     6  	"embed"
     7  	//	"fmt"
     8  	"path/filepath"
     9  
    10  	v1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
    11  	"k8s.io/apimachinery/pkg/util/yaml"
    12  )
    13  
    14  //go:embed crds/**/*.yaml
    15  var crdFixtures embed.FS
    16  
    17  //go:embed warehouse/src/**
    18  var PalletFixtures embed.FS
    19  
    20  type options struct {
    21  	only string
    22  }
    23  
    24  type Option func(*options)
    25  
    26  // Only makes LoadCRDs only return CRDs from directories with the provided name.
    27  // e.g., to only read the Edge CRDs, pass "edge"
    28  func Only(dir string) func(*options) {
    29  	return func(o *options) {
    30  		o.only = dir
    31  	}
    32  }
    33  
    34  // LoadCRDs loads the embedded CRD test fixtures and marshals them
    35  // into client.Object structs that are ready to be applied to any K8s server
    36  func LoadCRDs(opts ...Option) ([]*v1.CustomResourceDefinition, error) {
    37  	o := &options{}
    38  	for _, opt := range opts {
    39  		opt(o)
    40  	}
    41  
    42  	crdDir := "crds"
    43  	var manifests []*v1.CustomResourceDefinition
    44  	crdDirs, err := crdFixtures.ReadDir(crdDir)
    45  	if err != nil {
    46  		return nil, err
    47  	}
    48  
    49  	// loop over directories containing CRDs
    50  	for _, crdDirEntry := range crdDirs {
    51  		if !crdDirEntry.Type().IsDir() {
    52  			continue
    53  		}
    54  		dirname := crdDirEntry.Name()
    55  		// skip dirnames that dont match if o.only is set
    56  		if o.only != "" && dirname != o.only {
    57  			continue
    58  		}
    59  		crdEntries, err := crdFixtures.ReadDir(filepath.Join(crdDir, dirname))
    60  		if err != nil {
    61  			return nil, err
    62  		}
    63  
    64  		// loop over CRDs in the CRD directory
    65  		for _, crdEntry := range crdEntries {
    66  			crdname := crdEntry.Name()
    67  			//fmt.Println(crdname)
    68  			data, err := crdFixtures.ReadFile(filepath.Join(crdDir, dirname, crdname))
    69  			if err != nil {
    70  				return nil, err
    71  			}
    72  
    73  			crd := &v1.CustomResourceDefinition{}
    74  			if err := yaml.Unmarshal(data, crd); err != nil {
    75  				return nil, err
    76  			}
    77  
    78  			manifests = append(manifests, crd)
    79  		}
    80  	}
    81  
    82  	return manifests, nil
    83  }
    84  

View as plain text