github.com/ethersphere/bee/v2@v2.2.0/pkg/storageincentives/events_test.go (about)

     1  // Copyright 2022 The Swarm Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package storageincentives_test
     6  
     7  import (
     8  	"context"
     9  	"testing"
    10  	"time"
    11  
    12  	"github.com/ethersphere/bee/v2/pkg/storageincentives"
    13  )
    14  
    15  func TestClose(t *testing.T) {
    16  	t.Parallel()
    17  
    18  	ev := storageincentives.NewEvents()
    19  
    20  	done1 := make(chan struct{})
    21  	done2 := make(chan struct{})
    22  	done3 := make(chan struct{})
    23  
    24  	ev.On(1, func(ctx context.Context) {
    25  		<-ctx.Done()
    26  		close(done1)
    27  	})
    28  
    29  	ev.On(1, func(ctx context.Context) {
    30  		<-ctx.Done()
    31  		close(done2)
    32  	})
    33  
    34  	ev.On(2, func(ctx context.Context) {
    35  		<-ctx.Done()
    36  		close(done3)
    37  	})
    38  
    39  	ev.Publish(1)
    40  	ev.Publish(2)
    41  
    42  	ev.Close()
    43  
    44  	for i := 0; i < 3; i++ {
    45  		select {
    46  		case <-done1:
    47  		case <-done2:
    48  		case <-done3:
    49  		case <-time.After(time.Second):
    50  			t.Fatal("timeout")
    51  		}
    52  	}
    53  }
    54  
    55  func TestPhaseCancel(t *testing.T) {
    56  	t.Parallel()
    57  
    58  	ev := storageincentives.NewEvents()
    59  
    60  	done1 := make(chan struct{})
    61  	done2 := make(chan struct{})
    62  	defer ev.Close()
    63  
    64  	// ensure no panics occur on an empty publish
    65  	ev.Publish(0)
    66  
    67  	ev.On(1, func(ctx context.Context) {
    68  		<-ctx.Done()
    69  		close(done1)
    70  	})
    71  
    72  	ev.On(2, func(ctx context.Context) {
    73  		<-ctx.Done()
    74  		close(done2)
    75  	})
    76  
    77  	ev.On(3, func(ctx context.Context) {
    78  		ev.Cancel(1, 2)
    79  	})
    80  
    81  	ev.Publish(1)
    82  	ev.Publish(2)
    83  	ev.Publish(3)
    84  
    85  	for i := 0; i < 2; i++ {
    86  		select {
    87  		case <-done1:
    88  		case <-done2:
    89  		case <-time.After(time.Second):
    90  			t.Fatal("timeout")
    91  		}
    92  	}
    93  }