Skip to content

Commit

Permalink
fix(app): add test coverage to FindStructField (#1769)
Browse files Browse the repository at this point in the history
Signed-off-by: Artur Troian <[email protected]>
  • Loading branch information
troian committed Apr 17, 2023
1 parent c489463 commit 957a712
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
8 changes: 8 additions & 0 deletions app/types/app.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package types

import (
"errors"
"fmt"
"reflect"

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down
65 changes: 65 additions & 0 deletions app/types/app_test.go
Original file line number Diff line number Diff line change
@@ -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)
}

0 comments on commit 957a712

Please sign in to comment.