github.com/gogf/gf@v1.16.9/container/gvar/gvar_z_unit_struct_test.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package gvar_test
     8  
     9  import (
    10  	"github.com/gogf/gf/container/gvar"
    11  	"github.com/gogf/gf/frame/g"
    12  	"github.com/gogf/gf/test/gtest"
    13  	"github.com/gogf/gf/util/gconv"
    14  	"testing"
    15  )
    16  
    17  func TestVar_Struct(t *testing.T) {
    18  	gtest.C(t, func(t *gtest.T) {
    19  		type StTest struct {
    20  			Test int
    21  		}
    22  
    23  		Kv := make(map[string]int, 1)
    24  		Kv["Test"] = 100
    25  
    26  		testObj := &StTest{}
    27  
    28  		objOne := gvar.New(Kv, true)
    29  
    30  		objOne.Struct(testObj)
    31  
    32  		t.Assert(testObj.Test, Kv["Test"])
    33  	})
    34  	gtest.C(t, func(t *gtest.T) {
    35  		type StTest struct {
    36  			Test int8
    37  		}
    38  		o := &StTest{}
    39  		v := gvar.New(g.Slice{"Test", "-25"})
    40  		v.Struct(o)
    41  		t.Assert(o.Test, -25)
    42  	})
    43  }
    44  
    45  func TestVar_Var_Attribute_Struct(t *testing.T) {
    46  	gtest.C(t, func(t *gtest.T) {
    47  		type User struct {
    48  			Uid  int
    49  			Name string
    50  		}
    51  		user := new(User)
    52  		err := gconv.Struct(
    53  			g.Map{
    54  				"uid":  gvar.New(1),
    55  				"name": gvar.New("john"),
    56  			}, user)
    57  		t.Assert(err, nil)
    58  		t.Assert(user.Uid, 1)
    59  		t.Assert(user.Name, "john")
    60  	})
    61  	gtest.C(t, func(t *gtest.T) {
    62  		type User struct {
    63  			Uid  int
    64  			Name string
    65  		}
    66  		var user *User
    67  		err := gconv.Struct(
    68  			g.Map{
    69  				"uid":  gvar.New(1),
    70  				"name": gvar.New("john"),
    71  			}, &user)
    72  		t.Assert(err, nil)
    73  		t.Assert(user.Uid, 1)
    74  		t.Assert(user.Name, "john")
    75  	})
    76  }