storj.io/minio@v0.0.0-20230509071714-0cbc90f649b1/pkg/pubsub/pubsub_test.go (about) 1 /* 2 * MinIO Cloud Storage, (C) 2019 MinIO, Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package pubsub 18 19 import ( 20 "fmt" 21 "testing" 22 "time" 23 ) 24 25 func TestSubscribe(t *testing.T) { 26 ps := New() 27 ch1 := make(chan interface{}, 1) 28 ch2 := make(chan interface{}, 1) 29 doneCh := make(chan struct{}) 30 defer close(doneCh) 31 ps.Subscribe(ch1, doneCh, nil) 32 ps.Subscribe(ch2, doneCh, nil) 33 ps.Lock() 34 defer ps.Unlock() 35 if len(ps.subs) != 2 { 36 t.Errorf("expected 2 subscribers") 37 } 38 } 39 40 func TestUnsubscribe(t *testing.T) { 41 ps := New() 42 ch1 := make(chan interface{}, 1) 43 ch2 := make(chan interface{}, 1) 44 doneCh1 := make(chan struct{}) 45 doneCh2 := make(chan struct{}) 46 ps.Subscribe(ch1, doneCh1, nil) 47 ps.Subscribe(ch2, doneCh2, nil) 48 49 close(doneCh1) 50 // Allow for the above statement to take effect. 51 time.Sleep(100 * time.Millisecond) 52 ps.Lock() 53 if len(ps.subs) != 1 { 54 t.Errorf("expected 1 subscriber") 55 } 56 ps.Unlock() 57 close(doneCh2) 58 } 59 60 func TestPubSub(t *testing.T) { 61 ps := New() 62 ch1 := make(chan interface{}, 1) 63 doneCh1 := make(chan struct{}) 64 defer close(doneCh1) 65 ps.Subscribe(ch1, doneCh1, func(entry interface{}) bool { return true }) 66 val := "hello" 67 ps.Publish(val) 68 msg := <-ch1 69 if msg != "hello" { 70 t.Errorf(fmt.Sprintf("expected %s , found %s", val, msg)) 71 } 72 } 73 74 func TestMultiPubSub(t *testing.T) { 75 ps := New() 76 ch1 := make(chan interface{}, 1) 77 ch2 := make(chan interface{}, 1) 78 doneCh := make(chan struct{}) 79 defer close(doneCh) 80 ps.Subscribe(ch1, doneCh, func(entry interface{}) bool { return true }) 81 ps.Subscribe(ch2, doneCh, func(entry interface{}) bool { return true }) 82 val := "hello" 83 ps.Publish(val) 84 85 msg1 := <-ch1 86 msg2 := <-ch2 87 if msg1 != "hello" && msg2 != "hello" { 88 t.Errorf(fmt.Sprintf("expected both subscribers to have%s , found %s and %s", val, msg1, msg2)) 89 } 90 }