github.com/wangyougui/gf/v2@v2.6.5/util/gutil/gutil_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/wangyougui/gf.
     6  
     7  package gutil_test
     8  
     9  import (
    10  	"testing"
    11  
    12  	"github.com/wangyougui/gf/v2/frame/g"
    13  	"github.com/wangyougui/gf/v2/test/gtest"
    14  	"github.com/wangyougui/gf/v2/util/gutil"
    15  )
    16  
    17  func Test_StructToSlice(t *testing.T) {
    18  	type A struct {
    19  		K1 int
    20  		K2 string
    21  	}
    22  	gtest.C(t, func(t *gtest.T) {
    23  		a := &A{
    24  			K1: 1,
    25  			K2: "v2",
    26  		}
    27  		s := gutil.StructToSlice(a)
    28  		t.Assert(len(s), 4)
    29  		t.AssertIN(s[0], g.Slice{"K1", "K2", 1, "v2"})
    30  		t.AssertIN(s[1], g.Slice{"K1", "K2", 1, "v2"})
    31  		t.AssertIN(s[2], g.Slice{"K1", "K2", 1, "v2"})
    32  		t.AssertIN(s[3], g.Slice{"K1", "K2", 1, "v2"})
    33  	})
    34  	gtest.C(t, func(t *gtest.T) {
    35  		s := gutil.StructToSlice(1)
    36  		t.Assert(s, nil)
    37  	})
    38  }
    39  
    40  func Test_FillStructWithDefault(t *testing.T) {
    41  	gtest.C(t, func(t *gtest.T) {
    42  		type myInt int
    43  		type Inner1 struct {
    44  			I1V1 int
    45  			I1V2 bool `d:"true"`
    46  		}
    47  		type Inner2 struct {
    48  			I2V1 float64 `d:"1.01"`
    49  		}
    50  		type Inner3 struct {
    51  			Inner1 Inner1
    52  			I3V1   myInt `d:"1"`
    53  		}
    54  		type Inner4 struct {
    55  		}
    56  		type Outer struct {
    57  			O1 int     `d:"1.01"`
    58  			O2 string  `d:"1.01"`
    59  			O3 float32 `d:"1.01"`
    60  			*Inner1
    61  			O4 bool `d:"true"`
    62  			Inner2
    63  			Inner3 Inner3
    64  			Inner4 *Inner4
    65  		}
    66  
    67  		outer := Outer{}
    68  		err := gutil.FillStructWithDefault(&outer)
    69  		t.AssertNil(err)
    70  
    71  		t.Assert(outer.O1, 1)
    72  		t.Assert(outer.O2, `1.01`)
    73  		t.Assert(outer.O3, `1.01`)
    74  		t.Assert(outer.O4, true)
    75  		t.Assert(outer.Inner1, nil)
    76  		t.Assert(outer.Inner2.I2V1, `1.01`)
    77  		t.Assert(outer.Inner3.I3V1, 1)
    78  		t.Assert(outer.Inner3.Inner1.I1V1, 0)
    79  		t.Assert(outer.Inner3.Inner1.I1V2, true)
    80  		t.Assert(outer.Inner4, nil)
    81  	})
    82  }