immutableresource_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package syncx
  2. import (
  3. "errors"
  4. "testing"
  5. "time"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. func TestImmutableResource(t *testing.T) {
  9. var count int
  10. r := NewImmutableResource(func() (interface{}, error) {
  11. count++
  12. return "hello", nil
  13. })
  14. res, err := r.Get()
  15. assert.Equal(t, "hello", res)
  16. assert.Equal(t, 1, count)
  17. assert.Nil(t, err)
  18. // again
  19. res, err = r.Get()
  20. assert.Equal(t, "hello", res)
  21. assert.Equal(t, 1, count)
  22. assert.Nil(t, err)
  23. }
  24. func TestImmutableResourceError(t *testing.T) {
  25. var count int
  26. r := NewImmutableResource(func() (interface{}, error) {
  27. count++
  28. return nil, errors.New("any")
  29. })
  30. res, err := r.Get()
  31. assert.Nil(t, res)
  32. assert.NotNil(t, err)
  33. assert.Equal(t, "any", err.Error())
  34. assert.Equal(t, 1, count)
  35. // again
  36. res, err = r.Get()
  37. assert.Nil(t, res)
  38. assert.NotNil(t, err)
  39. assert.Equal(t, "any", err.Error())
  40. assert.Equal(t, 1, count)
  41. r.refreshInterval = 0
  42. time.Sleep(time.Millisecond)
  43. res, err = r.Get()
  44. assert.Nil(t, res)
  45. assert.NotNil(t, err)
  46. assert.Equal(t, "any", err.Error())
  47. assert.Equal(t, 2, count)
  48. }
  49. func TestImmutableResourceErrorRefreshAlways(t *testing.T) {
  50. var count int
  51. r := NewImmutableResource(func() (interface{}, error) {
  52. count++
  53. return nil, errors.New("any")
  54. }, WithRefreshIntervalOnFailure(0))
  55. res, err := r.Get()
  56. assert.Nil(t, res)
  57. assert.NotNil(t, err)
  58. assert.Equal(t, "any", err.Error())
  59. assert.Equal(t, 1, count)
  60. // again
  61. res, err = r.Get()
  62. assert.Nil(t, res)
  63. assert.NotNil(t, err)
  64. assert.Equal(t, "any", err.Error())
  65. assert.Equal(t, 2, count)
  66. }