github.com/gogf/gf@v1.16.9/util/gutil/gutil_z_unit_slice_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 gutil_test
     8  
     9  import (
    10  	"github.com/gogf/gf/frame/g"
    11  	"testing"
    12  
    13  	"github.com/gogf/gf/test/gtest"
    14  	"github.com/gogf/gf/util/gutil"
    15  )
    16  
    17  func Test_SliceToMap(t *testing.T) {
    18  	gtest.C(t, func(t *gtest.T) {
    19  		s := g.Slice{
    20  			"K1", "v1", "K2", "v2",
    21  		}
    22  		m := gutil.SliceToMap(s)
    23  		t.Assert(len(m), 2)
    24  		t.Assert(m, g.Map{
    25  			"K1": "v1",
    26  			"K2": "v2",
    27  		})
    28  	})
    29  	gtest.C(t, func(t *gtest.T) {
    30  		s := g.Slice{
    31  			"K1", "v1", "K2",
    32  		}
    33  		m := gutil.SliceToMap(s)
    34  		t.Assert(len(m), 0)
    35  		t.Assert(m, nil)
    36  	})
    37  }
    38  
    39  func Test_SliceToMapWithColumnAsKey(t *testing.T) {
    40  	m1 := g.Map{"K1": "v1", "K2": 1}
    41  	m2 := g.Map{"K1": "v2", "K2": 2}
    42  	s := g.Slice{m1, m2}
    43  	gtest.C(t, func(t *gtest.T) {
    44  		m := gutil.SliceToMapWithColumnAsKey(s, "K1")
    45  		t.Assert(m, g.MapAnyAny{
    46  			"v1": m1,
    47  			"v2": m2,
    48  		})
    49  	})
    50  	gtest.C(t, func(t *gtest.T) {
    51  		m := gutil.SliceToMapWithColumnAsKey(s, "K2")
    52  		t.Assert(m, g.MapAnyAny{
    53  			1: m1,
    54  			2: m2,
    55  		})
    56  	})
    57  }