github.com/go-playground/pkg/v5@v5.29.1/context/context_test.go (about)

     1  package contextext
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  	"time"
     7  )
     8  
     9  func TestDetach(t *testing.T) {
    10  
    11  	key := &struct{ name string }{name: "key"}
    12  	ctx := context.WithValue(context.Background(), key, 13)
    13  	ctx, cancel := context.WithTimeout(ctx, time.Nanosecond)
    14  	cancel() // cancel ensuring context has been canceled
    15  
    16  	select {
    17  	case <-ctx.Done():
    18  	default:
    19  		t.Fatal("expected context to be cancelled")
    20  	}
    21  
    22  	ctx = Detach(ctx)
    23  
    24  	select {
    25  	case <-ctx.Done():
    26  		t.Fatal("expected context to be detached from parents cancellation")
    27  	default:
    28  		rawValue := ctx.Value(key)
    29  		n, ok := rawValue.(int)
    30  		if !ok || n != 13 {
    31  			t.Fatalf("expected integer woth value of 13 but got %v", rawValue)
    32  		}
    33  	}
    34  }