github.com/pyroscope-io/pyroscope@v0.37.3-0.20230725203016-5f6947968bd0/pkg/model/role_test.go (about)

     1  package model_test
     2  
     3  import (
     4  	"encoding/json"
     5  
     6  	. "github.com/onsi/ginkgo/v2"
     7  	. "github.com/onsi/gomega"
     8  
     9  	"github.com/pyroscope-io/pyroscope/pkg/model"
    10  )
    11  
    12  var _ = Describe("Role validation", func() {
    13  	type testCase struct {
    14  		role  model.Role
    15  		valid bool
    16  	}
    17  
    18  	validateRole := func(c testCase) {
    19  		Expect(c.role.IsValid()).To(Equal(c.valid))
    20  		parsed, err := model.ParseRole(c.role.String())
    21  		Expect(parsed).To(Equal(c.role))
    22  		if c.valid {
    23  			Expect(err).ToNot(HaveOccurred())
    24  		} else {
    25  			Expect(err).To(MatchError(model.ErrRoleUnknown))
    26  		}
    27  	}
    28  
    29  	DescribeTable("Role cases",
    30  		validateRole,
    31  		Entry("Invalid", testCase{model.InvalidRole, false}),
    32  		Entry("Admin", testCase{model.AdminRole, true}),
    33  		Entry("Agent", testCase{model.AgentRole, true}),
    34  		Entry("ReadOnly", testCase{model.ReadOnlyRole, true}),
    35  	)
    36  })
    37  
    38  var _ = Describe("Role JSON", func() {
    39  	type testCase struct {
    40  		json string
    41  		role model.Role
    42  	}
    43  
    44  	type role struct {
    45  		Role model.Role
    46  	}
    47  
    48  	Context("when a role is marshaled with JSON encoder", func() {
    49  		expectEncoded := func(c testCase) {
    50  			b, err := json.Marshal(role{c.role})
    51  			Expect(err).ToNot(HaveOccurred())
    52  			Expect(b).To(MatchJSON(c.json))
    53  		}
    54  
    55  		DescribeTable("JSON marshal cases",
    56  			expectEncoded,
    57  			Entry("Valid", testCase{`{"Role":"Admin"}`, model.AdminRole}),
    58  			Entry("Invalid", testCase{`{"Role":""}`, model.InvalidRole}),
    59  		)
    60  	})
    61  
    62  	Context("when a JSON encoded role is unmarshalled", func() {
    63  		expectDecoded := func(c testCase) {
    64  			var x role
    65  			err := json.Unmarshal([]byte(c.json), &x)
    66  			Expect(err).ToNot(HaveOccurred())
    67  			Expect(x.Role).To(Equal(c.role))
    68  		}
    69  
    70  		DescribeTable("JSON unmarshal cases",
    71  			expectDecoded,
    72  			Entry("Valid", testCase{`{"Role":"Admin"}`, model.AdminRole}),
    73  			Entry("Invalid", testCase{`{"Role":"NotAValidRole"}`, model.InvalidRole}),
    74  		)
    75  	})
    76  })