github.com/cloudfoundry-community/cloudfoundry-cli@v6.44.1-0.20240130060226-cda5ed8e89a5+incompatible/types/null_string_test.go (about)

     1  package types_test
     2  
     3  import (
     4  	"encoding/json"
     5  
     6  	. "code.cloudfoundry.org/cli/types"
     7  	. "github.com/onsi/ginkgo"
     8  	. "github.com/onsi/gomega"
     9  )
    10  
    11  var _ = Describe("NullString", func() {
    12  	type SamplePayload struct {
    13  		OptionalField NullString
    14  	}
    15  
    16  	Context("JSON marshaling", func() {
    17  		When("the NullString has a value", func() {
    18  			It("marshals to its value", func() {
    19  				toMarshal := SamplePayload{
    20  					OptionalField: NullString{Value: "some-string", IsSet: true},
    21  				}
    22  				bytes, err := json.Marshal(toMarshal)
    23  				Expect(err).ToNot(HaveOccurred())
    24  				Expect(string(bytes)).To(ContainSubstring(`"some-string"`))
    25  			})
    26  		})
    27  
    28  		When("the NullString has no value", func() {
    29  			It("marshals to a JSON null", func() {
    30  				toMarshal := SamplePayload{
    31  					OptionalField: NullString{IsSet: false},
    32  				}
    33  				bytes, err := json.Marshal(toMarshal)
    34  				Expect(err).ToNot(HaveOccurred())
    35  				Expect(string(bytes)).To(ContainSubstring(`null`))
    36  			})
    37  		})
    38  	})
    39  
    40  	Context("JSON unmashalling", func() {
    41  		When("the JSON has a string value", func() {
    42  			It("unmarhsalls to a NullString with the correct value", func() {
    43  				toUnmarshal := []byte(`{"optionalField":"our-value"}`)
    44  				var samplePayload SamplePayload
    45  				err := json.Unmarshal(toUnmarshal, &samplePayload)
    46  				Expect(err).ToNot(HaveOccurred())
    47  				Expect(samplePayload.OptionalField.IsSet).To(BeTrue())
    48  				Expect(samplePayload.OptionalField.Value).To(Equal("our-value"))
    49  			})
    50  		})
    51  
    52  		When("the JSON has a null value", func() {
    53  			It("unmarhsalls to a NullString with no value", func() {
    54  				toUnmarshal := []byte(`{"optionalField":null}`)
    55  				var samplePayload SamplePayload
    56  				err := json.Unmarshal(toUnmarshal, &samplePayload)
    57  				Expect(err).ToNot(HaveOccurred())
    58  				Expect(samplePayload.OptionalField.IsSet).To(BeFalse())
    59  				Expect(samplePayload.OptionalField.Value).To(Equal(""))
    60  			})
    61  		})
    62  	})
    63  
    64  })