github.com/zhongdalu/gf@v1.0.0/g/util/gconv/gconv_z_unit_slice_test.go (about)

     1  // Copyright 2018 gf Author(https://github.com/zhongdalu/gf). 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/zhongdalu/gf.
     6  
     7  package gconv_test
     8  
     9  import (
    10  	"testing"
    11  
    12  	"github.com/zhongdalu/gf/g"
    13  	"github.com/zhongdalu/gf/g/test/gtest"
    14  	"github.com/zhongdalu/gf/g/util/gconv"
    15  )
    16  
    17  func Test_Slice(t *testing.T) {
    18  	gtest.Case(t, func() {
    19  		value := 123.456
    20  		gtest.AssertEQ(gconv.Bytes("123"), []byte("123"))
    21  		gtest.AssertEQ(gconv.Strings(value), []string{"123.456"})
    22  		gtest.AssertEQ(gconv.Ints(value), []int{123})
    23  		gtest.AssertEQ(gconv.Floats(value), []float64{123.456})
    24  		gtest.AssertEQ(gconv.Interfaces(value), []interface{}{123.456})
    25  	})
    26  }
    27  
    28  // 私有属性不会进行转换
    29  func Test_Slice_PrivateAttribute(t *testing.T) {
    30  	type User struct {
    31  		Id   int
    32  		name string
    33  	}
    34  	gtest.Case(t, func() {
    35  		user := &User{1, "john"}
    36  		gtest.Assert(gconv.Interfaces(user), g.Slice{1})
    37  	})
    38  }
    39  
    40  func Test_Slice_Structs(t *testing.T) {
    41  	type Base struct {
    42  		Age int
    43  	}
    44  	type User struct {
    45  		Id   int
    46  		Name string
    47  		Base
    48  	}
    49  
    50  	gtest.Case(t, func() {
    51  		users := make([]User, 0)
    52  		params := []g.Map{
    53  			{"id": 1, "name": "john", "age": 18},
    54  			{"id": 2, "name": "smith", "age": 20},
    55  		}
    56  		err := gconv.Structs(params, &users)
    57  		gtest.Assert(err, nil)
    58  		gtest.Assert(len(users), 2)
    59  		gtest.Assert(users[0].Id, params[0]["id"])
    60  		gtest.Assert(users[0].Name, params[0]["name"])
    61  		gtest.Assert(users[0].Age, 0)
    62  
    63  		gtest.Assert(users[1].Id, params[1]["id"])
    64  		gtest.Assert(users[1].Name, params[1]["name"])
    65  		gtest.Assert(users[1].Age, 0)
    66  	})
    67  
    68  	gtest.Case(t, func() {
    69  		users := make([]User, 0)
    70  		params := []g.Map{
    71  			{"id": 1, "name": "john", "age": 18},
    72  			{"id": 2, "name": "smith", "age": 20},
    73  		}
    74  		err := gconv.StructsDeep(params, &users)
    75  		gtest.Assert(err, nil)
    76  		gtest.Assert(len(users), 2)
    77  		gtest.Assert(users[0].Id, params[0]["id"])
    78  		gtest.Assert(users[0].Name, params[0]["name"])
    79  		gtest.Assert(users[0].Age, params[0]["age"])
    80  
    81  		gtest.Assert(users[1].Id, params[1]["id"])
    82  		gtest.Assert(users[1].Name, params[1]["name"])
    83  		gtest.Assert(users[1].Age, params[1]["age"])
    84  	})
    85  }