Parcourir la source

IConfig

- refactor config.Invalidate
- add config.Invalidate tests
Alexey Kim il y a 1 an
Parent
commit
56d9051428
2 fichiers modifiés avec 60 ajouts et 7 suppressions
  1. 18 7
      config/config.go
  2. 42 0
      config/config_test.go

+ 18 - 7
config/config.go

@@ -1,23 +1,34 @@
 package config
 
-import "reflect"
+import (
+	"fmt"
+	"reflect"
+)
 
 type IConfig interface {
 	Invalidate() error
 }
 
 func Invalidate(config IConfig) error {
-	if config == nil || reflect.ValueOf(config).IsZero() {
-		return nil
+	if config == nil {
+		return fmt.Errorf("config must not be a nil")
 	}
 
-	r := reflect.ValueOf(config).Elem()
-	for i := 0; i < r.NumField(); i++ {
-		if !r.Field(i).CanInterface() || r.Field(i).IsZero() {
+	val := reflect.ValueOf(config)
+	if val.Kind() != reflect.Struct {
+		if val.IsZero() {
+			return fmt.Errorf("config is empty")
+		}
+
+		val = reflect.ValueOf(config).Elem()
+	}
+
+	for i := 0; i < val.NumField(); i++ {
+		if !val.Field(i).CanInterface() || val.Field(i).IsZero() {
 			continue
 		}
 
-		if elm, ok := r.Field(i).Interface().(IConfig); ok {
+		if elm, ok := val.Field(i).Interface().(IConfig); ok {
 			if er := elm.Invalidate(); er != nil {
 				return er
 			}

+ 42 - 0
config/config_test.go

@@ -0,0 +1,42 @@
+package config
+
+import "testing"
+
+type _config struct {
+	Debug bool
+}
+
+func (_ _config) Invalidate() error {
+	return nil
+}
+
+func TestInvalidate(t *testing.T) {
+	tests := []struct {
+		config  IConfig
+		wantErr bool
+	}{
+		{
+			config:  nil,
+			wantErr: true,
+		},
+		{
+			config: _config{
+				Debug: false,
+			},
+			wantErr: false,
+		},
+		{
+			config: &_config{
+				Debug: false,
+			},
+			wantErr: false,
+		},
+	}
+	for _, tt := range tests {
+		t.Run("config.Invalidate", func(t *testing.T) {
+			if err := Invalidate(tt.config); (err != nil) != tt.wantErr {
+				t.Errorf("Invalidate() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}