github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/setstruct/setstruct_test.go (about)

     1  package setstruct_test
     2  
     3  import (
     4  	"reflect"
     5  	"strings"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/bingoohuang/gg/pkg/setstruct"
    10  	"github.com/stretchr/testify/assert"
    11  )
    12  
    13  type MyParser string
    14  
    15  func (r *MyParser) ValueOf(s string) error {
    16  	*r = MyParser(strings.ToLower(s))
    17  	return nil
    18  }
    19  
    20  func TestSetStruct(t *testing.T) {
    21  	type StructA struct {
    22  		Name           string
    23  		Age            int
    24  		Female         bool
    25  		Weight         float32
    26  		GopherDuration time.Duration
    27  		Budgets        []string
    28  		Props          map[string]string
    29  		My             MyParser
    30  		pri            string
    31  	}
    32  
    33  	a := StructA{}
    34  
    35  	setstruct.Set(&a, func(f reflect.StructField) string {
    36  		return map[string]string{
    37  			"Name":           "bingoohuang",
    38  			"Age":            "100",
    39  			"Female":         "yes",
    40  			"Weight":         "63.5",
    41  			"GopherDuration": "23h",
    42  			"Budgets":        "aa,bb,cc",
    43  			"Props":          "city=beijing,floor=15,alone",
    44  			"My":             "HELLO",
    45  			"pri":            "pri",
    46  		}[f.Name]
    47  	})
    48  
    49  	assert.Equal(t, StructA{
    50  		Name:           "bingoohuang",
    51  		Age:            100,
    52  		Female:         true,
    53  		Weight:         63.5,
    54  		GopherDuration: 23 * time.Hour,
    55  		Budgets:        []string{"aa", "bb", "cc"},
    56  		Props:          map[string]string{"city": "beijing", "floor": "15", "alone": ""},
    57  		My:             "hello",
    58  	}, a)
    59  }