common: fix method signature for UnmarshalJSON

There was a bug in the previous implementation which used to pass the
argument as a value but that does not work because we need to change the
value of it. The new implementation uses pass by reference.

Create a test to cover this scenario.
This commit is contained in:
Martin Sehnoutka 2020-02-13 15:13:07 +01:00 committed by Tom Gundersen
parent 251d63c06a
commit 6b957f01a0
2 changed files with 25 additions and 9 deletions

View file

@ -124,12 +124,12 @@ func ArchitectureExists(testedArch string) bool {
// UnmarshalJSON is a custom unmarshaling function to limit the set of allowed values
// in case the input is JSON.
func (arch Architecture) UnmarshalJSON(data []byte) error {
func (arch *Architecture) UnmarshalJSON(data []byte) error {
value, err := unmarshalHelper(data, " is not a valid JSON value", " is not a valid architecture", getArchMapping())
if err != nil {
return err
}
arch = Architecture(value)
*arch = Architecture(value)
return nil
}
@ -199,12 +199,12 @@ func getCompatImageTypeMapping() map[int]string {
return mapping
}
func (imgType ImageType) UnmarshalJSON(data []byte) error {
func (imgType *ImageType) UnmarshalJSON(data []byte) error {
value, err := unmarshalHelper(data, " is not a valid JSON value", " is not a valid image type", getImageTypeMapping())
if err != nil {
return err
}
imgType = ImageType(value)
*imgType = ImageType(value)
return nil
}
@ -260,12 +260,12 @@ func DistributionExists(testedDistro string) bool {
return existsHelper(getDistributionMapping(), testedDistro)
}
func (distro Distribution) UnmarshalJSON(data []byte) error {
func (distro *Distribution) UnmarshalJSON(data []byte) error {
value, err := unmarshalHelper(data, " is not a valid JSON value", " is not a valid distribution", getDistributionMapping())
if err != nil {
return err
}
distro = Distribution(value)
*distro = Distribution(value)
return nil
}
@ -300,12 +300,12 @@ func getUploadTargetMapping() map[string]int {
return mapping
}
func (ut UploadTarget) UnmarshalJSON(data []byte) error {
func (ut *UploadTarget) UnmarshalJSON(data []byte) error {
value, err := unmarshalHelper(data, " is not a valid JSON value", " is not a valid upload target", getUploadTargetMapping())
if err != nil {
return err
}
ut = UploadTarget(value)
*ut = UploadTarget(value)
return nil
}

View file

@ -129,5 +129,21 @@ func TestJSONConversionsComposeRequest(t *testing.T) {
t.Error("Marshaled compose request is not the one expected")
}
}
}
func TestImageType_UnmarshalJSON(t *testing.T) {
dict := struct {
ImageTypes []ImageType `json:"image_types"`
}{}
input := `{"image_types":["qcow2", "Alibaba"]}`
err := json.Unmarshal([]byte(input), &dict)
if err != nil {
t.Fatal(err)
}
if dict.ImageTypes[0] != Qcow2Generic {
t.Fatal("failed to umarshal image type qcow2; got tag:", dict.ImageTypes[0])
}
if dict.ImageTypes[1] != Alibaba {
t.Fatal("failed to umarshal image type Alibaba; got tag:", dict.ImageTypes[0])
}
}