github.com/regadas/controller-tools@v0.5.1-0.20210408091555-18885b17ff7b/pkg/rbac/parser_integration_test.go (about) 1 package rbac_test 2 3 import ( 4 "bytes" 5 "fmt" 6 "io/ioutil" 7 "os" 8 9 "github.com/google/go-cmp/cmp" 10 . "github.com/onsi/ginkgo" 11 . "github.com/onsi/gomega" 12 13 rbacv1 "k8s.io/api/rbac/v1" 14 15 "github.com/regadas/controller-tools/pkg/genall" 16 "github.com/regadas/controller-tools/pkg/loader" 17 "github.com/regadas/controller-tools/pkg/markers" 18 "github.com/regadas/controller-tools/pkg/rbac" 19 "sigs.k8s.io/yaml" 20 ) 21 22 var _ = Describe("ClusterRole generated by the RBAC Generator", func() { 23 // run this test multiple times to make sure the Rule order is stable. 24 const stableTestCount = 5 25 for i := 0; i < stableTestCount; i++ { 26 It("should match the expected result", func() { 27 By("switching into testdata to appease go modules") 28 cwd, err := os.Getwd() 29 Expect(err).NotTo(HaveOccurred()) 30 Expect(os.Chdir("./testdata")).To(Succeed()) // go modules are directory-sensitive 31 defer func() { Expect(os.Chdir(cwd)).To(Succeed()) }() 32 33 By("loading the roots") 34 pkgs, err := loader.LoadRoots(".") 35 Expect(err).NotTo(HaveOccurred()) 36 37 By("registering RBAC rule marker") 38 reg := &markers.Registry{} 39 Expect(reg.Register(rbac.RuleDefinition)).To(Succeed()) 40 41 By("creating GenerationContext") 42 ctx := &genall.GenerationContext{ 43 Collector: &markers.Collector{Registry: reg}, 44 Roots: pkgs, 45 } 46 47 By("generating a ClusterRole") 48 objs, err := rbac.GenerateRoles(ctx, "manager-role") 49 Expect(err).NotTo(HaveOccurred()) 50 51 By("loading the desired YAML") 52 expectedFile, err := ioutil.ReadFile("role.yaml") 53 Expect(err).NotTo(HaveOccurred()) 54 55 By("parsing the desired YAML") 56 for i, expectedRoleBytes := range bytes.Split(expectedFile, []byte("\n---\n"))[1:] { 57 By(fmt.Sprintf("comparing the generated Role and expected Role (Pair %d)", i)) 58 obj := objs[i] 59 switch obj := obj.(type) { 60 case rbacv1.ClusterRole: 61 var expectedClusterRole rbacv1.ClusterRole 62 Expect(yaml.Unmarshal(expectedRoleBytes, &expectedClusterRole)).To(Succeed()) 63 Expect(obj).To(Equal(expectedClusterRole), "type not as expected, check pkg/rbac/testdata/README.md for more details.\n\nDiff:\n\n%s", cmp.Diff(obj, expectedClusterRole)) 64 default: 65 var expectedRole rbacv1.Role 66 Expect(yaml.Unmarshal(expectedRoleBytes, &expectedRole)).To(Succeed()) 67 Expect(obj).To(Equal(expectedRole), "type not as expected, check pkg/rbac/testdata/README.md for more details.\n\nDiff:\n\n%s", cmp.Diff(obj, expectedRole)) 68 } 69 } 70 71 }) 72 } 73 })