go-zero/core/contextx/valueonlycontext_test.go

61 lines
1.4 KiB
Go
Raw Normal View History

2020-07-26 17:09:05 +08:00
package contextx
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestContextCancel(t *testing.T) {
type key string
var nameKey key = "name"
c := context.WithValue(context.Background(), nameKey, "value")
2020-07-26 17:09:05 +08:00
c1, cancel := context.WithCancel(c)
o := ValueOnlyFrom(c1)
2020-10-16 10:50:43 +08:00
c2, cancel2 := context.WithCancel(o)
defer cancel2()
2020-07-26 17:09:05 +08:00
contexts := []context.Context{c1, c2}
for _, c := range contexts {
assert.NotNil(t, c.Done())
assert.Nil(t, c.Err())
select {
case x := <-c.Done():
t.Errorf("<-c.Done() == %v want nothing (it should block)", x)
default:
}
}
cancel()
<-c1.Done()
assert.Nil(t, o.Err())
assert.Equal(t, context.Canceled, c1.Err())
assert.NotEqual(t, context.Canceled, c2.Err())
}
2020-08-16 22:25:51 +08:00
func TestContextDeadline(t *testing.T) {
2020-10-16 10:50:43 +08:00
c, cancel := context.WithDeadline(context.Background(), time.Now().Add(10*time.Millisecond))
cancel()
2020-07-26 17:09:05 +08:00
o := ValueOnlyFrom(c)
select {
case <-time.After(100 * time.Millisecond):
case <-o.Done():
t.Fatal("ValueOnlyContext: context should not have timed out")
}
2020-10-16 11:13:55 +08:00
c, cancel = context.WithDeadline(context.Background(), time.Now().Add(10*time.Millisecond))
cancel()
2020-07-26 17:09:05 +08:00
o = ValueOnlyFrom(c)
2020-10-16 11:13:55 +08:00
c, cancel = context.WithDeadline(o, time.Now().Add(20*time.Millisecond))
defer cancel()
2020-07-26 17:09:05 +08:00
select {
case <-time.After(100 * time.Millisecond):
t.Fatal("ValueOnlyContext+Deadline: context should have timed out")
case <-c.Done():
}
}