github.com/nyan233/littlerpc@v0.4.6-0.20230316182519-0c8d5c48abaf/core/server/event_test.go (about)

     1  package server
     2  
     3  import (
     4  	"github.com/stretchr/testify/assert"
     5  	"sync"
     6  	"testing"
     7  	"time"
     8  )
     9  
    10  func TestEvent(t *testing.T) {
    11  	ev := new(event)
    12  	testEvent(t, int(_Start), ev)
    13  	testEvent(t, int(_Stop), ev)
    14  	testEvent(t, int(_Restart), ev)
    15  }
    16  
    17  func testEvent(t *testing.T, ev int, i *event) {
    18  	const (
    19  		WaitSize = 200
    20  	)
    21  	done := make(chan struct{})
    22  	go func() {
    23  		if !i.Entry(ev) {
    24  			t.Error("entry event failed")
    25  		}
    26  		done <- struct{}{}
    27  		select {
    28  		case <-done:
    29  			if !i.Complete(ev) {
    30  				t.Error("complete event failed")
    31  			}
    32  			done <- struct{}{}
    33  		}
    34  	}()
    35  	<-done
    36  	var wg sync.WaitGroup
    37  	wg.Add(WaitSize)
    38  	for j := 0; j < WaitSize; j++ {
    39  		go func() {
    40  			wg.Done()
    41  			w, ack, ok := i.Wait()
    42  			assert.Equal(t, ok, true)
    43  			assert.Equal(t, <-w, ev)
    44  			ack()
    45  			wg.Done()
    46  		}()
    47  	}
    48  	wg.Wait()
    49  	wg.Add(WaitSize)
    50  	time.AfterFunc(time.Second*2, func() {
    51  		done <- struct{}{}
    52  	})
    53  	wg.Wait()
    54  	<-done
    55  }