lookup_cache_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package util
  2. import (
  3. "errors"
  4. "github.com/stretchr/testify/require"
  5. "testing"
  6. "time"
  7. )
  8. func TestLookupCache_Success(t *testing.T) {
  9. values, i := []string{"first", "second"}, 0
  10. c := NewLookupCache[string](func() (string, error) {
  11. time.Sleep(300 * time.Millisecond)
  12. v := values[i]
  13. i++
  14. return v, nil
  15. }, 500*time.Millisecond)
  16. start := time.Now()
  17. v, err := c.Value()
  18. require.Nil(t, err)
  19. require.Equal(t, values[0], v)
  20. require.True(t, time.Since(start) >= 300*time.Millisecond)
  21. start = time.Now()
  22. v, err = c.Value()
  23. require.Nil(t, err)
  24. require.Equal(t, values[0], v)
  25. require.True(t, time.Since(start) < 200*time.Millisecond)
  26. time.Sleep(550 * time.Millisecond)
  27. start = time.Now()
  28. v, err = c.Value()
  29. require.Nil(t, err)
  30. require.Equal(t, values[1], v)
  31. require.True(t, time.Since(start) >= 300*time.Millisecond)
  32. start = time.Now()
  33. v, err = c.Value()
  34. require.Nil(t, err)
  35. require.Equal(t, values[1], v)
  36. require.True(t, time.Since(start) < 200*time.Millisecond)
  37. }
  38. func TestLookupCache_Error(t *testing.T) {
  39. c := NewLookupCache[string](func() (string, error) {
  40. time.Sleep(200 * time.Millisecond)
  41. return "", errors.New("some error")
  42. }, 500*time.Millisecond)
  43. start := time.Now()
  44. v, err := c.Value()
  45. require.NotNil(t, err)
  46. require.Equal(t, "", v)
  47. require.True(t, time.Since(start) >= 200*time.Millisecond)
  48. start = time.Now()
  49. v, err = c.Value()
  50. require.NotNil(t, err)
  51. require.Equal(t, "", v)
  52. require.True(t, time.Since(start) >= 200*time.Millisecond)
  53. }