github.com/DaAlbrecht/cf-cli@v0.0.0-20231128151943-1fe19bb400b9/types/optional_object_test.go (about)

     1  package types_test
     2  
     3  import (
     4  	"code.cloudfoundry.org/cli/types"
     5  	"code.cloudfoundry.org/jsonry"
     6  	. "github.com/onsi/ginkgo"
     7  	. "github.com/onsi/gomega"
     8  )
     9  
    10  var _ = Describe("optional object", func() {
    11  	It("has an unset zero value", func() {
    12  		var s types.OptionalObject
    13  		Expect(s.IsSet).To(BeFalse())
    14  		Expect(s.Value).To(SatisfyAll(BeEmpty(), BeNil()))
    15  	})
    16  
    17  	It("has a set empty value", func() {
    18  		s := types.NewOptionalObject(map[string]interface{}{})
    19  		Expect(s.IsSet).To(BeTrue())
    20  		Expect(s.Value).To(BeEmpty())
    21  		Expect(s.Value).NotTo(BeNil())
    22  
    23  		t := types.NewOptionalObject(nil)
    24  		Expect(t.IsSet).To(BeTrue())
    25  		Expect(t.Value).To(BeEmpty())
    26  		Expect(t.Value).NotTo(BeNil())
    27  
    28  		Expect(s).To(Equal(t))
    29  	})
    30  
    31  	When("marshaling", func() {
    32  		It("can marshal to an object", func() {
    33  			s := struct {
    34  				S types.OptionalObject
    35  			}{
    36  				S: types.NewOptionalObject(map[string]interface{}{"foo": "bar"}),
    37  			}
    38  			Expect(jsonry.Marshal(s)).To(MatchJSON(`{"S":{"foo":"bar"}}`))
    39  		})
    40  
    41  		It("can marshal to an empty object", func() {
    42  			s := struct {
    43  				S types.OptionalObject
    44  			}{
    45  				S: types.NewOptionalObject(map[string]interface{}{}),
    46  			}
    47  			Expect(jsonry.Marshal(s)).To(MatchJSON(`{"S":{}}`))
    48  		})
    49  
    50  		It("can be omitted during marshaling", func() {
    51  			var s struct {
    52  				S types.OptionalObject
    53  			}
    54  			Expect(jsonry.Marshal(s)).To(MatchJSON(`{}`))
    55  		})
    56  	})
    57  
    58  	When("unmarshaling", func() {
    59  		It("can be unmarshaled from an empty object", func() {
    60  			var s struct {
    61  				S types.OptionalObject
    62  			}
    63  			Expect(jsonry.Unmarshal([]byte(`{"S":{}}`), &s)).NotTo(HaveOccurred())
    64  			Expect(s.S.IsSet).To(BeTrue())
    65  			Expect(s.S.Value).To(BeEmpty())
    66  			Expect(s.S.Value).NotTo(BeNil())
    67  		})
    68  
    69  		It("can be unmarshaled from null", func() {
    70  			var s struct {
    71  				S types.OptionalObject
    72  			}
    73  			Expect(jsonry.Unmarshal([]byte(`{"S":null}`), &s)).NotTo(HaveOccurred())
    74  			Expect(s.S.IsSet).To(BeTrue())
    75  			Expect(s.S.Value).To(BeEmpty())
    76  			Expect(s.S.Value).NotTo(BeNil())
    77  		})
    78  	})
    79  })