timeoutinterceptor_test.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package clientinterceptors
  2. import (
  3. "context"
  4. "strconv"
  5. "sync"
  6. "testing"
  7. "time"
  8. "github.com/stretchr/testify/assert"
  9. "google.golang.org/grpc"
  10. )
  11. func TestTimeoutInterceptor(t *testing.T) {
  12. timeouts := []time.Duration{0, time.Millisecond * 10}
  13. for _, timeout := range timeouts {
  14. t.Run(strconv.FormatInt(int64(timeout), 10), func(t *testing.T) {
  15. interceptor := TimeoutInterceptor(timeout)
  16. cc := new(grpc.ClientConn)
  17. err := interceptor(context.Background(), "/foo", nil, nil, cc,
  18. func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn,
  19. opts ...grpc.CallOption) error {
  20. return nil
  21. },
  22. )
  23. assert.Nil(t, err)
  24. })
  25. }
  26. }
  27. func TestTimeoutInterceptor_timeout(t *testing.T) {
  28. const timeout = time.Millisecond * 10
  29. interceptor := TimeoutInterceptor(timeout)
  30. ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
  31. defer cancel()
  32. var wg sync.WaitGroup
  33. wg.Add(1)
  34. cc := new(grpc.ClientConn)
  35. err := interceptor(ctx, "/foo", nil, nil, cc,
  36. func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn,
  37. opts ...grpc.CallOption) error {
  38. defer wg.Done()
  39. tm, ok := ctx.Deadline()
  40. assert.True(t, ok)
  41. assert.True(t, tm.Before(time.Now().Add(timeout+time.Millisecond)))
  42. return nil
  43. })
  44. wg.Wait()
  45. assert.Nil(t, err)
  46. }