github.com/amazechain/amc@v0.1.3/modules/event/v2/event_test.go (about)

     1  // Copyright 2022 The AmazeChain Authors
     2  // This file is part of the AmazeChain library.
     3  //
     4  // The AmazeChain library is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU Lesser General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // The AmazeChain library is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU Lesser General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU Lesser General Public License
    15  // along with the AmazeChain library. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  package v2
    18  
    19  import (
    20  	"fmt"
    21  	"reflect"
    22  	"sync"
    23  	"testing"
    24  )
    25  
    26  type A struct {
    27  	A string
    28  }
    29  
    30  func TestEvent_Subscribe(t *testing.T) {
    31  	var feed Event
    32  
    33  	c1 := make(chan *int, 10)
    34  	c2 := make(chan *A, 10)
    35  
    36  	feed.Subscribe(c1)
    37  	feed.Subscribe(c2)
    38  }
    39  
    40  func TestEvent_Send2(t *testing.T) {
    41  	c := make(chan int, 1)
    42  	vc := reflect.ValueOf(c)
    43  	var wg sync.WaitGroup
    44  	wg.Add(1)
    45  	go func() {
    46  		defer wg.Done()
    47  		a := <-c
    48  		t.Log("a value ", a)
    49  	}()
    50  
    51  	// use of TrySend() method
    52  	succeeded := vc.TrySend(reflect.ValueOf(123))
    53  
    54  	fmt.Println(succeeded, vc.Len(), vc.Cap())
    55  	wg.Wait()
    56  }
    57  
    58  func TestEvent_Send(t *testing.T) {
    59  	var feed Event
    60  	ch1 := make(chan int, 1)
    61  	ch2 := make(chan A, 1)
    62  
    63  	sub1 := feed.Subscribe(ch1)
    64  	sub2 := feed.Subscribe(ch2)
    65  
    66  	var wg sync.WaitGroup
    67  	wg.Add(2)
    68  	go func() {
    69  		defer wg.Done()
    70  		a := <-ch1
    71  		t.Log("ch1 Value", a)
    72  	}()
    73  
    74  	go func() {
    75  		defer wg.Done()
    76  		a := <-ch2
    77  		t.Log("ch2 Value", a)
    78  	}()
    79  	a := 2
    80  	feed.Send(a)
    81  	feed.Send(A{
    82  		A: "123",
    83  	})
    84  	wg.Wait()
    85  
    86  	sub1.Unsubscribe()
    87  	sub2.Unsubscribe()
    88  }