github.com/mailgun/holster/v4@v4.20.0/cancel/context_test.go (about)

     1  package cancel_test
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/mailgun/holster/v4/cancel"
     9  )
    10  
    11  func TestWrapFirst(t *testing.T) {
    12  	// First context
    13  	firstCtx := cancel.New(context.Background())
    14  	// Second context
    15  	secondCtx, cancelCtx := context.WithCancel(context.Background())
    16  	defer cancelCtx()
    17  
    18  	// Now if either firstCtx or secondCtx is cancelled 'ctx' should cancel
    19  	ctx := firstCtx.Wrap(secondCtx)
    20  
    21  	done := make(chan struct{})
    22  	go func() {
    23  		<-ctx.Done()
    24  		close(done)
    25  	}()
    26  
    27  	firstCtx.Cancel()
    28  
    29  	select {
    30  	case <-done:
    31  	case <-time.After(time.Second):
    32  		t.Fatalf("timeout waiting for context to cancel")
    33  	}
    34  }
    35  
    36  func TestWrapSecond(t *testing.T) {
    37  	// First context
    38  	firstCtx := cancel.New(context.Background())
    39  	// Second context
    40  	secondCtx, cancelCtx := context.WithCancel(context.Background())
    41  
    42  	// Now if either firstCtx or secondCtx is cancelled 'ctx' should cancel
    43  	ctx := firstCtx.Wrap(secondCtx)
    44  
    45  	done := make(chan struct{})
    46  	go func() {
    47  		<-ctx.Done()
    48  		close(done)
    49  	}()
    50  
    51  	cancelCtx()
    52  
    53  	select {
    54  	case <-done:
    55  	case <-time.After(time.Second):
    56  		t.Fatalf("timeout waiting for context to cancel")
    57  	}
    58  }