timer_test.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package server
  2. import (
  3. "context"
  4. "net/http"
  5. "net/http/httptest"
  6. "testing"
  7. "time"
  8. "github.com/stretchr/testify/require"
  9. )
  10. func TestCheckTimeout(t *testing.T) {
  11. tests := []struct {
  12. name string
  13. setup func() context.Context
  14. fail bool
  15. }{
  16. {
  17. name: "WithoutTimeout",
  18. setup: context.Background,
  19. fail: false,
  20. },
  21. {
  22. name: "ActiveTimerContext",
  23. setup: func() context.Context {
  24. req := httptest.NewRequest(http.MethodGet, "/test", nil)
  25. newReq, _ := startRequestTimer(req)
  26. return newReq.Context()
  27. },
  28. fail: false,
  29. },
  30. {
  31. name: "CancelledContext",
  32. setup: func() context.Context {
  33. req := httptest.NewRequest(http.MethodGet, "/test", nil)
  34. newReq, cancel := startRequestTimer(req)
  35. cancel() // Cancel immediately
  36. return newReq.Context()
  37. },
  38. fail: true,
  39. },
  40. {
  41. name: "DeadlineExceeded",
  42. setup: func() context.Context {
  43. ctx, cancel := context.WithTimeout(context.Background(), time.Nanosecond)
  44. defer cancel()
  45. time.Sleep(time.Millisecond * 10) // Ensure timeout
  46. return ctx
  47. },
  48. fail: true,
  49. },
  50. }
  51. for _, tt := range tests {
  52. t.Run(tt.name, func(t *testing.T) {
  53. ctx := tt.setup()
  54. err := CheckTimeout(ctx)
  55. if tt.fail {
  56. require.Error(t, err)
  57. } else {
  58. require.NoError(t, err)
  59. }
  60. })
  61. }
  62. }