valueonlycontext_test.go 1.3 KB

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