github.com/jxskiss/gopkg@v0.17.3/set/set_test.go (about) 1 package set 2 3 import ( 4 "fmt" 5 "reflect" 6 "sort" 7 "testing" 8 ) 9 10 func TestSet_Add(t *testing.T) { 11 t1 := map[interface{}]struct{}{ 12 1: {}, 13 2: {}, 14 3: {}, 15 } 16 set1 := NewSet(1, 2, 3) 17 set2 := NewSet([]int{1, 2, 3}) 18 if !reflect.DeepEqual(t1, set1.m) { 19 t.Errorf("failed: set1") 20 } 21 if !reflect.DeepEqual(t1, set2.m) { 22 t.Errorf("failec: set2") 23 } 24 set3 := NewSet() 25 set3.Add(1, 2, 3) 26 if !reflect.DeepEqual(t1, set3.m) { 27 t.Errorf("failed set3") 28 } 29 set4 := NewSet() 30 set4.Add([]int{1, 2, 3}) 31 if !reflect.DeepEqual(t1, set4.m) { 32 t.Errorf("failed set4") 33 } 34 } 35 36 func TestSet_Zero_Add(t *testing.T) { 37 var set1 Set 38 set1.Add(1, 2, 3) 39 if set1.Size() != 3 { 40 t.Errorf("failed add to zero set") 41 } 42 } 43 44 func TestSet_DiffSlice(t *testing.T) { 45 set1 := NewSet(1, 2, 3, 4) 46 other := []int{2, 4, 5} 47 got := set1.DiffSlice(other) 48 if got.Size() != 2 { 49 t.Errorf("unexpected set size after diff slice") 50 } 51 if !got.Contains(1, 3) { 52 t.Errorf("unexpected set elements after diff slice") 53 } 54 } 55 56 func TestSet_FilterInclude(t *testing.T) { 57 set := NewSet(1, 2, 4, 6) 58 slice := []int{2, 3, 4, 5} 59 got := set.FilterInclude(slice).([]int) 60 want := []int{2, 4} 61 if !reflect.DeepEqual(want, got) { 62 t.Errorf("failed filter include") 63 } 64 } 65 66 func TestSet_FilterExclude(t *testing.T) { 67 set := NewSet(1, 2, 4, 6) 68 slice := []int{2, 3, 4, 5} 69 got := set.FilterExclude(slice).([]int) 70 want := []int{3, 5} 71 if !reflect.DeepEqual(want, got) { 72 t.Errorf("failed filter exclude") 73 } 74 } 75 76 func TestSet_Slice(t *testing.T) { 77 set1 := NewSet(1, 2, 3) 78 set1.Add([]int{4, 5, 6}) 79 target := []interface{}{1, 2, 3, 4, 5, 6} 80 81 vals := set1.Slice() 82 sort.Slice(vals, func(i, j int) bool { 83 return vals[i].(int) < vals[j].(int) 84 }) 85 86 if !reflect.DeepEqual(target, vals) { 87 t.Errorf("failed Slice") 88 } 89 } 90 91 func TestSet_Map(t *testing.T) { 92 set1 := NewSet(1, 2, 3) 93 set1.Add([]int{4, 5, 6}) 94 target := map[interface{}]bool{ 95 1: true, 96 2: true, 97 3: true, 98 4: true, 99 5: true, 100 6: true, 101 } 102 103 vals := set1.Map() 104 if !reflect.DeepEqual(target, vals) { 105 t.Errorf("failed Map") 106 } 107 } 108 109 func TestSet_Chaining(t *testing.T) { 110 set := NewSet(1, 2, 3, 4). 111 Diff(NewSet(1, 2)). 112 Union(NewSet(7, 8)). 113 Intersect(NewSet(7, 8, 9, 0)) 114 if !reflect.DeepEqual(set.m, NewSet(7, 8).m) { 115 t.Errorf("failed TestSet_Chaining") 116 } 117 } 118 119 func shouldPanic(f func()) (err error) { 120 defer func() { 121 if e := recover(); e != nil { 122 err = fmt.Errorf("%v", e) 123 } 124 }() 125 f() 126 return 127 }