valueonlycontext_test.go 1.4 KB

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