Add a GetString helper for simple string annotations. Add tests which call Get and GetString on annotations objects (#1118)

This commit is contained in:
Richard Connon
2018-07-12 11:33:26 +01:00
committed by GitHub
parent d01fa73209
commit 5dfd9a9110
2 changed files with 54 additions and 0 deletions

View File

@@ -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()

View File

@@ -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")
}
}