timeoutinterceptor_test.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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_timeout(t *testing.T) {
  20. const timeout = time.Millisecond * 10
  21. interceptor := UnaryTimeoutInterceptor(timeout)
  22. ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
  23. defer cancel()
  24. var wg sync.WaitGroup
  25. wg.Add(1)
  26. _, err := interceptor(ctx, nil, &grpc.UnaryServerInfo{
  27. FullMethod: "/",
  28. }, func(ctx context.Context, req interface{}) (interface{}, error) {
  29. defer wg.Done()
  30. tm, ok := ctx.Deadline()
  31. assert.True(t, ok)
  32. assert.True(t, tm.Before(time.Now().Add(timeout+time.Millisecond)))
  33. return nil, nil
  34. })
  35. wg.Wait()
  36. assert.Nil(t, err)
  37. }