github.com/keybase/client/go@v0.0.0-20240309051027-028f7c731f8b/kbfs/libkbfs/coalescing_context_test.go (about)

     1  package libkbfs
     2  
     3  import (
     4  	"testing"
     5  	"time"
     6  
     7  	"github.com/stretchr/testify/require"
     8  	"golang.org/x/net/context"
     9  )
    10  
    11  type testCtxKey struct{ string }
    12  
    13  func TestCoalescingContext(t *testing.T) {
    14  	t.Parallel()
    15  	t.Log("Test basic CoalescingContext with 2 parent contexts.")
    16  	ctx1, cf1 := context.WithCancel(context.WithValue(context.Background(), testCtxKey{"hello"}, "world"))
    17  	ctx2, cf2 := context.WithCancel(context.Background())
    18  
    19  	cc, _ := NewCoalescingContext(ctx1)
    20  	err := cc.AddContext(ctx2)
    21  	require.NoError(t, err)
    22  	require.Equal(t, "world", cc.Value(testCtxKey{"hello"}).(string))
    23  
    24  	select {
    25  	case <-cc.Done():
    26  		t.Fatalf("Expected CoalescingContext to be blocked")
    27  	default:
    28  	}
    29  	cf1()
    30  	t.Log("Ensure that the CoalescingContext's CancelFunc is idempotent")
    31  	cf1()
    32  
    33  	require.NoError(t, cc.Err())
    34  
    35  	select {
    36  	case <-cc.Done():
    37  		t.Fatalf("Expected CoalescingContext to still be blocked")
    38  	default:
    39  	}
    40  	cf2()
    41  
    42  	t.Log("Verify that the CoalescingContext is Done() only after its parent contexts have both been canceled.")
    43  	select {
    44  	case <-time.After(time.Second):
    45  		t.Fatalf("Expected CoalescingContext to complete after its parent contexts were canceled")
    46  	case <-cc.Done():
    47  	}
    48  
    49  	require.EqualError(t, cc.Err(), context.Canceled.Error())
    50  
    51  	ctx3, _ := context.WithCancel(context.Background())
    52  	err = cc.AddContext(ctx3)
    53  	require.EqualError(t, err, context.Canceled.Error())
    54  }