github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/collection/set/generic_test.go (about) 1 package set 2 3 import ( 4 "reflect" 5 "sort" 6 "testing" 7 ) 8 9 func TestGeneric_Add(t *testing.T) { 10 t1 := map[int]struct{}{ 11 1: {}, 12 2: {}, 13 3: {}, 14 } 15 set1 := New(1, 2, 3) 16 if !reflect.DeepEqual(t1, set1.m) { 17 t.Errorf("failed: set1") 18 } 19 set2 := New[int]() 20 set2.Add(1, 2, 3) 21 if !reflect.DeepEqual(t1, set2.m) { 22 t.Errorf("failed set3") 23 } 24 } 25 26 func TestGeneric_Zero_Add(t *testing.T) { 27 var set1 Generic[int] 28 set1.Add(1, 2, 3) 29 if set1.Size() != 3 { 30 t.Errorf("failed add to zero set") 31 } 32 } 33 34 func TestGeneric_DiffSlice(t *testing.T) { 35 set1 := New(1, 2, 3, 4) 36 other := []int{2, 4, 5} 37 got := set1.DiffSlice(other) 38 if got.Size() != 2 { 39 t.Errorf("unexpected set size after diff slice") 40 } 41 if !got.Contains(1, 3) { 42 t.Errorf("unexpected set elements after diff slice") 43 } 44 } 45 46 func TestGeneric_FilterInclude(t *testing.T) { 47 set := New(1, 2, 4, 6) 48 slice := []int{2, 3, 4, 5} 49 got := set.FilterContains(slice) 50 want := []int{2, 4} 51 if !reflect.DeepEqual(want, got) { 52 t.Errorf("failed filter include") 53 } 54 } 55 56 func TestGeneric_FilterExclude(t *testing.T) { 57 set := New(1, 2, 4, 6) 58 slice := []int{2, 3, 4, 5} 59 got := set.FilterNotContains(slice) 60 want := []int{3, 5} 61 if !reflect.DeepEqual(want, got) { 62 t.Errorf("failed filter exclude") 63 } 64 } 65 66 func TestGeneric_Slice(t *testing.T) { 67 set1 := New(1, 2, 3) 68 set1.Add([]int{4, 5, 6}...) 69 target := []int{1, 2, 3, 4, 5, 6} 70 71 vals := set1.Slice() 72 sort.Slice(vals, func(i, j int) bool { 73 return vals[i] < vals[j] 74 }) 75 76 if !reflect.DeepEqual(target, vals) { 77 t.Errorf("failed Slice") 78 } 79 } 80 81 func TestGeneric_Map(t *testing.T) { 82 set1 := New(1, 2, 3) 83 set1.Add([]int{4, 5, 6}...) 84 target := map[int]bool{ 85 1: true, 86 2: true, 87 3: true, 88 4: true, 89 5: true, 90 6: true, 91 } 92 93 vals := set1.Map() 94 if !reflect.DeepEqual(target, vals) { 95 t.Errorf("failed Map") 96 } 97 } 98 99 func TestGeneric_Chaining(t *testing.T) { 100 set := New(1, 2, 3, 4). 101 Diff(New(1, 2)). 102 Union(New(7, 8)). 103 Intersect(New(7, 8, 9, 0)) 104 if !reflect.DeepEqual(set.m, New(7, 8).m) { 105 t.Errorf("failed TestGeneric_Chaining") 106 } 107 }