github.com/lingyao2333/mo-zero@v1.4.1/core/queue/queue_test.go (about)

     1  package queue
     2  
     3  import (
     4  	"sync"
     5  	"sync/atomic"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/stretchr/testify/assert"
    10  )
    11  
    12  const (
    13  	consumers = 4
    14  	rounds    = 100
    15  )
    16  
    17  func TestQueue(t *testing.T) {
    18  	producer := newMockedProducer(rounds)
    19  	consumer := newMockedConsumer()
    20  	consumer.wait.Add(consumers)
    21  	q := NewQueue(func() (Producer, error) {
    22  		return producer, nil
    23  	}, func() (Consumer, error) {
    24  		return consumer, nil
    25  	})
    26  	q.AddListener(new(mockedListener))
    27  	q.SetName("mockqueue")
    28  	q.SetNumConsumer(consumers)
    29  	q.SetNumProducer(1)
    30  	q.pause()
    31  	q.resume()
    32  	go func() {
    33  		producer.wait.Wait()
    34  		q.Stop()
    35  	}()
    36  	q.Start()
    37  	assert.Equal(t, int32(rounds), atomic.LoadInt32(&consumer.count))
    38  }
    39  
    40  type mockedConsumer struct {
    41  	count  int32
    42  	events int32
    43  	wait   sync.WaitGroup
    44  }
    45  
    46  func newMockedConsumer() *mockedConsumer {
    47  	return new(mockedConsumer)
    48  }
    49  
    50  func (c *mockedConsumer) Consume(string) error {
    51  	atomic.AddInt32(&c.count, 1)
    52  	return nil
    53  }
    54  
    55  func (c *mockedConsumer) OnEvent(interface{}) {
    56  	if atomic.AddInt32(&c.events, 1) <= consumers {
    57  		c.wait.Done()
    58  	}
    59  }
    60  
    61  type mockedProducer struct {
    62  	total int32
    63  	count int32
    64  	wait  sync.WaitGroup
    65  }
    66  
    67  func newMockedProducer(total int32) *mockedProducer {
    68  	p := new(mockedProducer)
    69  	p.total = total
    70  	p.wait.Add(int(total))
    71  	return p
    72  }
    73  
    74  func (p *mockedProducer) AddListener(listener ProduceListener) {
    75  }
    76  
    77  func (p *mockedProducer) Produce() (string, bool) {
    78  	if atomic.AddInt32(&p.count, 1) <= p.total {
    79  		p.wait.Done()
    80  		return "item", true
    81  	}
    82  
    83  	time.Sleep(time.Second)
    84  	return "", false
    85  }
    86  
    87  type mockedListener struct{}
    88  
    89  func (l *mockedListener) OnPause() {
    90  }
    91  
    92  func (l *mockedListener) OnResume() {
    93  }