github.com/lingyao2333/mo-zero@v1.4.1/core/contextx/valueonlycontext_test.go (about)

     1  package contextx
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  )
    10  
    11  func TestContextCancel(t *testing.T) {
    12  	type key string
    13  	var nameKey key = "name"
    14  	c := context.WithValue(context.Background(), nameKey, "value")
    15  	c1, cancel := context.WithCancel(c)
    16  	o := ValueOnlyFrom(c1)
    17  	c2, cancel2 := context.WithCancel(o)
    18  	defer cancel2()
    19  	contexts := []context.Context{c1, c2}
    20  
    21  	for _, c := range contexts {
    22  		assert.NotNil(t, c.Done())
    23  		assert.Nil(t, c.Err())
    24  
    25  		select {
    26  		case x := <-c.Done():
    27  			t.Errorf("<-c.Done() == %v want nothing (it should block)", x)
    28  		default:
    29  		}
    30  	}
    31  
    32  	cancel()
    33  	<-c1.Done()
    34  
    35  	assert.Nil(t, o.Err())
    36  	assert.Equal(t, context.Canceled, c1.Err())
    37  	assert.NotEqual(t, context.Canceled, c2.Err())
    38  }
    39  
    40  func TestContextDeadline(t *testing.T) {
    41  	c, cancel := context.WithDeadline(context.Background(), time.Now().Add(10*time.Millisecond))
    42  	cancel()
    43  	o := ValueOnlyFrom(c)
    44  	select {
    45  	case <-time.After(100 * time.Millisecond):
    46  	case <-o.Done():
    47  		t.Fatal("ValueOnlyContext: context should not have timed out")
    48  	}
    49  
    50  	c, cancel = context.WithDeadline(context.Background(), time.Now().Add(10*time.Millisecond))
    51  	cancel()
    52  	o = ValueOnlyFrom(c)
    53  	c, cancel = context.WithDeadline(o, time.Now().Add(20*time.Millisecond))
    54  	defer cancel()
    55  	select {
    56  	case <-time.After(100 * time.Millisecond):
    57  		t.Fatal("ValueOnlyContext+Deadline: context should have timed out")
    58  	case <-c.Done():
    59  	}
    60  }