diff --git a/app/types/app.go b/app/types/app.go index 69423cce04..3ec149f0f0 100644 --- a/app/types/app.go +++ b/app/types/app.go @@ -1,6 +1,7 @@ package types import ( + "errors" "fmt" "reflect" @@ -38,6 +39,10 @@ var ( upgrades = map[string]UpgradeInitFn{} ) +var ( + ErrEmptyFieldName = errors.New("empty field name") +) + type IUpgrade interface { StoreLoader() *storetypes.StoreUpgrades UpgradeHandler() upgradetypes.UpgradeHandler @@ -101,6 +106,9 @@ func GetUpgradesList() map[string]UpgradeInitFn { // and has the defined member field, if error is nil, the given // fieldName exists and is accessible with reflect. func FindStructField[C any](obj interface{}, fieldName string) (C, error) { + if fieldName == "" { + return *new(C), ErrEmptyFieldName + } rValue := reflect.ValueOf(obj) if rValue.Type().Kind() != reflect.Ptr { diff --git a/app/types/app_test.go b/app/types/app_test.go new file mode 100644 index 0000000000..ac559d2242 --- /dev/null +++ b/app/types/app_test.go @@ -0,0 +1,65 @@ +package types + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestFindStructFieldEmptyField(t *testing.T) { + type testType struct { + Val string + } + testStruct := testType{} + + _, err := FindStructField[string](testStruct, "") + require.EqualError(t, err, ErrEmptyFieldName.Error()) +} + +func TestFindStructFieldObjectAsValue(t *testing.T) { + type testType struct { + Val string + } + testStruct := testType{} + + val, err := FindStructField[string](testStruct, "Val") + require.NoError(t, err) + require.Equal(t, "", val) +} + +func TestFindStructFieldObjectAsPointer(t *testing.T) { + type testType struct { + Val string + } + testStruct := testType{ + Val: "testVal", + } + + val, err := FindStructField[string](&testStruct, "Val") + require.NoError(t, err) + require.Equal(t, "testVal", val) +} + +func TestFindStructFieldUnknownField(t *testing.T) { + type testType struct { + Val string + } + testStruct := testType{ + Val: "testVal", + } + + _, err := FindStructField[string](&testStruct, "Vals") + require.Error(t, err) +} + +func TestFindStructFieldNonMatchingType(t *testing.T) { + type testType struct { + Val string + } + testStruct := testType{ + Val: "testVal", + } + + _, err := FindStructField[int](&testStruct, "Vals") + require.Error(t, err) +}