diff --git a/api/models/annotations.go b/api/models/annotations.go index c1307e46e..e902a81be 100644 --- a/api/models/annotations.go +++ b/api/models/annotations.go @@ -160,6 +160,18 @@ func (m Annotations) Get(key string) ([]byte, bool) { return nil, false } +// GetString returns a string value if the annotation value is a string, otherwise an error +func (m Annotations) GetString(key string) (string, error) { + if v, ok := m[key]; ok { + var s string + if err := json.Unmarshal([]byte(*v), &s); err != nil { + return "", err + } + return s, nil + } + return "", errors.New("Annotation not found") +} + // Without returns a new annotations object with a value excluded func (m Annotations) Without(key string) Annotations { nuVal := m.clone() diff --git a/api/models/annotations_test.go b/api/models/annotations_test.go index 7605ab36a..c02b33b1d 100644 --- a/api/models/annotations_test.go +++ b/api/models/annotations_test.go @@ -259,3 +259,45 @@ func TestMergeAnnotations(t *testing.T) { } } + +func TestGetAnnotations(t *testing.T) { + annotations := EmptyAnnotations() + annotations, err := annotations.With("string-annotation", "string-value") + if err != nil { + t.Fatal("Cannot add string annotation") + } + annotations, err = annotations.With("array-annotation", []string{"string-1", "string-2"}) + if err != nil { + t.Fatal("Cannot add array annotation") + } + strAnnotation, ok := annotations.Get("string-annotation") + if !ok { + t.Error("Cannot get string annotation") + } + expected := "\"string-value\"" + if string(strAnnotation) != expected { + t.Errorf("Got unexpected value for string annotation. Got: %s Expected %s", strAnnotation, expected) + } + arrAnnotation, ok := annotations.Get("array-annotation") + if !ok { + t.Error("Cannot get array annotation") + } + expected = "[\"string-1\",\"string-2\"]" + if string(arrAnnotation) != expected { + t.Errorf("Got unexpected value for array annotation. Got: %s Expected %s", strAnnotation, expected) + } + + stringAnnotation, err := annotations.GetString("string-annotation") + if err != nil { + t.Fatalf("Error decoding string annotation: %v", err) + } + expected = "string-value" + if stringAnnotation != expected { + t.Errorf("Got unexpected decoded value for string annotation. Got: %s Expected %s", strAnnotation, expected) + } + + _, err = annotations.GetString("array-annotation") + if err == nil { + t.Error("Expected error trying to retrieve a string value for array annotation") + } +}