timeoutinterceptor_test.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package serverinterceptors
  2. import (
  3. "context"
  4. "sync"
  5. "testing"
  6. "time"
  7. "github.com/stretchr/testify/assert"
  8. "google.golang.org/grpc"
  9. )
  10. func TestUnaryTimeoutInterceptor(t *testing.T) {
  11. interceptor := UnaryTimeoutInterceptor(time.Millisecond * 10)
  12. _, err := interceptor(context.Background(), nil, &grpc.UnaryServerInfo{
  13. FullMethod: "/",
  14. }, func(ctx context.Context, req interface{}) (interface{}, error) {
  15. return nil, nil
  16. })
  17. assert.Nil(t, err)
  18. }
  19. func TestUnaryTimeoutInterceptor_panic(t *testing.T) {
  20. interceptor := UnaryTimeoutInterceptor(time.Millisecond * 10)
  21. assert.Panics(t, func() {
  22. _, _ = interceptor(context.Background(), nil, &grpc.UnaryServerInfo{
  23. FullMethod: "/",
  24. }, func(ctx context.Context, req interface{}) (interface{}, error) {
  25. panic("any")
  26. })
  27. })
  28. }
  29. func TestUnaryTimeoutInterceptor_timeout(t *testing.T) {
  30. const timeout = time.Millisecond * 10
  31. interceptor := UnaryTimeoutInterceptor(timeout)
  32. ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
  33. defer cancel()
  34. var wg sync.WaitGroup
  35. wg.Add(1)
  36. _, err := interceptor(ctx, nil, &grpc.UnaryServerInfo{
  37. FullMethod: "/",
  38. }, func(ctx context.Context, req interface{}) (interface{}, error) {
  39. defer wg.Done()
  40. tm, ok := ctx.Deadline()
  41. assert.True(t, ok)
  42. assert.True(t, tm.Before(time.Now().Add(timeout+time.Millisecond)))
  43. return nil, nil
  44. })
  45. wg.Wait()
  46. assert.Nil(t, err)
  47. }
  48. func TestUnaryTimeoutInterceptor_timeoutExpire(t *testing.T) {
  49. const timeout = time.Millisecond * 10
  50. interceptor := UnaryTimeoutInterceptor(timeout)
  51. ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond)
  52. defer cancel()
  53. var wg sync.WaitGroup
  54. wg.Add(1)
  55. _, err := interceptor(ctx, nil, &grpc.UnaryServerInfo{
  56. FullMethod: "/",
  57. }, func(ctx context.Context, req interface{}) (interface{}, error) {
  58. defer wg.Done()
  59. time.Sleep(time.Millisecond * 50)
  60. return nil, nil
  61. })
  62. wg.Wait()
  63. assert.Equal(t, context.DeadlineExceeded, err)
  64. }