Skip to content

Commit

Permalink
feat: add MustHaveValue helper
Browse files Browse the repository at this point in the history
  • Loading branch information
joshiste committed Jun 18, 2024
1 parent 4c00fb5 commit 8f7666f
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
25 changes: 25 additions & 0 deletions extutil/extutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ package extutil
import (
"fmt"
"github.com/steadybit/extension-kit/extconversion"
"reflect"
"strconv"
"strings"
)
Expand Down Expand Up @@ -170,6 +171,30 @@ func ToUInt(val interface{}) uint {
}
}

type Measurable[T any, K comparable] interface {
~string | ~[]T | ~map[K]T | ~chan T
}

// MustHaveValue panics if the given key is not present in the map or the value is nil or empty.
func MustHaveValue[T any, K comparable](m map[K]T, key K) T {
val, ok := m[key]
if !ok {
panic(fmt.Sprintf("missing value for %v", key))
}

kind := reflect.TypeOf(val).Kind()
if kind == reflect.Array || kind == reflect.Chan || kind == reflect.Map || kind == reflect.Slice || kind == reflect.String {
if reflect.ValueOf(val).Len() == 0 {
panic(fmt.Sprintf("value for %v is %v ", key, val))
}
} else if kind == reflect.Ptr {
if reflect.ValueOf(val).IsNil() {
panic(fmt.Sprintf("value for %v is nil ", key))
}
}
return val
}

func ToStringArray(s interface{}) []string {
if s == nil {
return nil
Expand Down
23 changes: 23 additions & 0 deletions extutil/extutil_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package extutil

import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"testing"
)
Expand Down Expand Up @@ -237,3 +238,25 @@ func TestMaskString(t *testing.T) {
})
}
}

func TestMustHaveValue(t *testing.T) {
assert.Equal(t, 0, MustHaveValue(map[string]int{"key": 0}, "key"))
assert.Panics(t, func() {
MustHaveValue(map[string]int{"key": 0}, "missing")
})

assert.Equal(t, "value", MustHaveValue(map[string]string{"key": "value"}, "key"))
assert.Panics(t, func() {
MustHaveValue(map[string]string{"key": "value"}, "missing")
})

assert.Equal(t, Ptr("value"), MustHaveValue(map[string]*string{"key": Ptr("value")}, "key"))
assert.Panics(t, func() {
MustHaveValue(map[string]*string{"empty": nil}, "empty")
})

assert.Equal(t, []string{"value"}, MustHaveValue(map[string][]string{"key": {"value"}}, "key"))
assert.Panics(t, func() {
MustHaveValue(map[string][]string{"empty": {}}, "empty")
})
}

0 comments on commit 8f7666f

Please sign in to comment.