github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/easy/conv_test.go (about)

     1  package easy
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/stretchr/testify/assert"
     7  
     8  	"github.com/jxskiss/gopkg/v2/utils/ptr"
     9  )
    10  
    11  func TestConvInts(t *testing.T) {
    12  	slice1 := []int{1, 2, 3, -3, -2, -1}
    13  	want := []int32{1, 2, 3, -3, -2, -1}
    14  	got := ConvInts[int, int32](slice1)
    15  	assert.Equal(t, want, got)
    16  }
    17  
    18  func TestFormatInts(t *testing.T) {
    19  	slice1 := []int32{1, 2, 3, -3, -2, -1}
    20  	want := []string{"1", "2", "3", "-3", "-2", "-1"}
    21  	got := FormatInts(slice1, 10)
    22  	assert.Equal(t, want, got)
    23  }
    24  
    25  func TestParseInts(t *testing.T) {
    26  	slice := []string{"1", "2", "a", "3", "bc", "-3", "-2", "-1", "ef"}
    27  	want := []int64{1, 2, 3, -3, -2, -1}
    28  	got := ParseInts[int64](slice, 10)
    29  	assert.Equal(t, want, got)
    30  }
    31  
    32  func TestToBoolMap(t *testing.T) {
    33  	slice := []int64{1, 2, 2, 3}
    34  	want := map[int64]bool{1: true, 2: true, 3: true}
    35  	got := ToBoolMap(slice)
    36  	assert.Equal(t, want, got)
    37  }
    38  
    39  func TestToMap(t *testing.T) {
    40  	slice := []*comptyp{
    41  		{I32: 2, Simple: simple{"2"}},
    42  		{I32: 3, Simple: simple{"3"}},
    43  		{I32: 3, Simple: simple{"3"}},
    44  	}
    45  	want := map[int32]simple{
    46  		2: {"2"},
    47  		3: {"3"},
    48  	}
    49  	got := ToMap(slice, func(elem *comptyp) (int32, simple) {
    50  		return elem.I32, elem.Simple
    51  	})
    52  	assert.Equal(t, want, got)
    53  }
    54  
    55  func TestToInterfaceSlice(t *testing.T) {
    56  	slice1 := []int{1, 2, 3}
    57  	want := []any{1, 2, 3}
    58  	got := ToInterfaceSlice(slice1)
    59  	assert.Equal(t, want, got)
    60  
    61  	slice2 := []*int{ptr.Ptr(1), ptr.Ptr(2), ptr.Ptr(3)}
    62  	got2 := ToInterfaceSlice(slice2)
    63  	for i, x := range got2 {
    64  		assert.Equal(t, *slice2[i], *(x.(*int)))
    65  	}
    66  
    67  	slice3 := []simple{
    68  		{"a"},
    69  		{"b"},
    70  		{"c"},
    71  	}
    72  	got3 := ToInterfaceSlice(slice3)
    73  	for i, x := range got3 {
    74  		assert.Equal(t, slice3[i], x.(simple))
    75  	}
    76  
    77  	slice4 := []*simple{
    78  		{"a"},
    79  		{"b"},
    80  		{"c"},
    81  	}
    82  	got4 := ToInterfaceSlice(slice4)
    83  	for i, x := range got4 {
    84  		assert.Equal(t, slice4[i].A, x.(*simple).A)
    85  	}
    86  }
    87  
    88  func TestToTypedSlice(t *testing.T) {
    89  	slice1 := []any{1, 2, 3}
    90  	want := []int{1, 2, 3}
    91  	got := ToTypedSlice[int](slice1)
    92  	assert.Equal(t, want, got)
    93  }