time_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package time
  2. import (
  3. "context"
  4. "testing"
  5. "time"
  6. )
  7. func TestShrink(t *testing.T) {
  8. var d Duration
  9. err := d.UnmarshalText([]byte("1s"))
  10. if err != nil {
  11. t.Fatalf("TestShrink: d.UnmarshalText failed!err:=%v", err)
  12. }
  13. c := context.Background()
  14. to, ctx, cancel := d.Shrink(c)
  15. defer cancel()
  16. if time.Duration(to) != time.Second {
  17. t.Fatalf("new timeout must be equal 1 second")
  18. }
  19. if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) > time.Second || time.Until(deadline) < time.Millisecond*500 {
  20. t.Fatalf("ctx deadline must be less than 1s and greater than 500ms")
  21. }
  22. }
  23. func TestShrinkWithTimeout(t *testing.T) {
  24. var d Duration
  25. err := d.UnmarshalText([]byte("1s"))
  26. if err != nil {
  27. t.Fatalf("TestShrink: d.UnmarshalText failed!err:=%v", err)
  28. }
  29. c, cancel := context.WithTimeout(context.Background(), time.Second*2)
  30. defer cancel()
  31. to, ctx, cancel := d.Shrink(c)
  32. defer cancel()
  33. if time.Duration(to) != time.Second {
  34. t.Fatalf("new timeout must be equal 1 second")
  35. }
  36. if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) > time.Second || time.Until(deadline) < time.Millisecond*500 {
  37. t.Fatalf("ctx deadline must be less than 1s and greater than 500ms")
  38. }
  39. }
  40. func TestShrinkWithDeadline(t *testing.T) {
  41. var d Duration
  42. err := d.UnmarshalText([]byte("1s"))
  43. if err != nil {
  44. t.Fatalf("TestShrink: d.UnmarshalText failed!err:=%v", err)
  45. }
  46. c, cancel := context.WithTimeout(context.Background(), time.Millisecond*500)
  47. defer cancel()
  48. to, ctx, cancel := d.Shrink(c)
  49. defer cancel()
  50. if time.Duration(to) >= time.Millisecond*500 {
  51. t.Fatalf("new timeout must be less than 500 ms")
  52. }
  53. if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) > time.Millisecond*500 || time.Until(deadline) < time.Millisecond*200 {
  54. t.Fatalf("ctx deadline must be less than 500ms and greater than 200ms")
  55. }
  56. }