github.com/alimy/mir/v4@v4.1.0/internal/utils/set_test.go (about) 1 // Copyright 2022 Michael Li <alimy@gility.net>. All rights reserved. 2 // Use of this source code is governed by Apache License 2.0 that 3 // can be found in the LICENSE file. 4 5 package utils 6 7 import ( 8 "errors" 9 "net/http" 10 "sync" 11 "testing" 12 ) 13 14 func TestStrSet(t *testing.T) { 15 for _, data := range []struct { 16 input []string 17 expect []string 18 exist string 19 }{ 20 { 21 input: []string{http.MethodGet}, 22 expect: []string{http.MethodGet}, 23 exist: http.MethodGet, 24 }, 25 { 26 input: []string{"others"}, 27 expect: []string{"others"}, 28 exist: "others", 29 }, 30 } { 31 s := NewStrSet() 32 for _, it := range data.input { 33 s.Add(it) 34 } 35 36 if !s.Exist(data.exist) { 37 t.Errorf("want exist %s but not", data.exist) 38 } 39 40 list := s.List() 41 if len(list) != len(data.expect) { 42 t.Errorf("want list length=%d but got %d", len(data.expect), len(list)) 43 } 44 45 Top: 46 for _, lv := range list { 47 for _, ev := range data.expect { 48 if lv == ev { 49 continue Top 50 } 51 } 52 t.Errorf("want list %v but got %v", data.expect, list) 53 } 54 } 55 } 56 57 func TestOnceSet_Add(t *testing.T) { 58 onceSet := newOnceSet() 59 60 if err := onceSet.Add(""); err != nil && err.Error() != "empty item" { 61 t.Error("want an error but not") 62 } 63 64 if err := onceSet.Add("abc"); err != nil { 65 t.Error("want nil error but not") 66 } 67 68 if err := onceSet.Add("abc"); err != nil { 69 t.Error("want an error but not") 70 } 71 } 72 73 func TestOnceSet_Exist(t *testing.T) { 74 onceSet := newOnceSet() 75 76 _ = onceSet.Add("abc") 77 if exist := onceSet.Exist("abc"); !exist { 78 t.Error("want exist an item for 'abc' but not") 79 } 80 } 81 82 func TestMuxSet_Add(t *testing.T) { 83 muxSet := NewMuxSet() 84 if err := muxSet.Add("abc"); err != nil { 85 t.Error("want nil error but not") 86 } 87 if exist := muxSet.Exist("abc"); !exist { 88 t.Error("want exist an item for 'abc' but not") 89 } 90 wg := &sync.WaitGroup{} 91 wg.Add(3) 92 go tinyTest(wg, t, muxSet) 93 go tinyTest(wg, t, muxSet) 94 go tinyTest(wg, t, muxSet) 95 wg.Wait() 96 } 97 98 func newOnceSet() Set { 99 return NewOnceSet(func(it string) error { 100 if it == "" { 101 return errors.New("empty item") 102 } 103 return nil 104 }) 105 } 106 107 func tinyTest(wg *sync.WaitGroup, t *testing.T, set Set) { 108 defer wg.Done() 109 110 for i := 0; i < 10; i++ { 111 if err := set.Add("abc"); err == nil { 112 t.Error("want an error but not") 113 } 114 } 115 }