valueonlycontext_test.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. c := context.WithValue(context.Background(), "key", "value")
  10. c1, cancel := context.WithCancel(c)
  11. o := ValueOnlyFrom(c1)
  12. c2, _ := context.WithCancel(o)
  13. contexts := []context.Context{c1, c2}
  14. for _, c := range contexts {
  15. assert.NotNil(t, c.Done())
  16. assert.Nil(t, c.Err())
  17. select {
  18. case x := <-c.Done():
  19. t.Errorf("<-c.Done() == %v want nothing (it should block)", x)
  20. default:
  21. }
  22. }
  23. cancel()
  24. <-c1.Done()
  25. assert.Nil(t, o.Err())
  26. assert.Equal(t, context.Canceled, c1.Err())
  27. assert.NotEqual(t, context.Canceled, c2.Err())
  28. }
  29. func TestContextDeadline(t *testing.T) {
  30. c, _ := context.WithDeadline(context.Background(), time.Now().Add(10*time.Millisecond))
  31. o := ValueOnlyFrom(c)
  32. select {
  33. case <-time.After(100 * time.Millisecond):
  34. case <-o.Done():
  35. t.Fatal("ValueOnlyContext: context should not have timed out")
  36. }
  37. c, _ = context.WithDeadline(context.Background(), time.Now().Add(10*time.Millisecond))
  38. o = ValueOnlyFrom(c)
  39. c, _ = context.WithDeadline(o, time.Now().Add(20*time.Millisecond))
  40. select {
  41. case <-time.After(100 * time.Millisecond):
  42. t.Fatal("ValueOnlyContext+Deadline: context should have timed out")
  43. case <-c.Done():
  44. }
  45. }