expire_test.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package cache
  2. import (
  3. "context"
  4. "testing"
  5. "time"
  6. "github.com/stretchr/testify/require"
  7. )
  8. func TestExpire(t *testing.T) {
  9. testCache(t, &Expire{
  10. ItemTTL: time.Minute,
  11. })
  12. }
  13. func TestExpireExpire(t *testing.T) {
  14. ctx := context.TODO()
  15. c := Expire{
  16. ItemTTL: time.Minute,
  17. }
  18. c.Set(ctx, "/hello", String("hello"))
  19. require.Equal(t, 1, c.Len())
  20. require.Equal(t, 5, c.Size())
  21. c.Set(ctx, "/world", String("world"))
  22. require.Equal(t, 2, c.Len())
  23. require.Equal(t, 10, c.Size())
  24. c.Set(ctx, "/goodbye", String("goodbye"))
  25. require.Equal(t, 3, c.Len())
  26. require.Equal(t, 17, c.Size())
  27. c.items["/hello"].expiresAt = time.Now().Add(-time.Second)
  28. c.items["/world"].expiresAt = time.Now().Add(-time.Second)
  29. c.Set(ctx, "/goodmorning", String("goodmorning"))
  30. require.Equal(t, 2, c.Len())
  31. require.Equal(t, 18, c.Size())
  32. require.Len(t, c.queue, 2)
  33. }
  34. func TestExpireSetSameKey(t *testing.T) {
  35. ctx := context.TODO()
  36. c := Expire{
  37. ItemTTL: time.Minute,
  38. }
  39. c.Set(ctx, "/foo", String("foo"))
  40. require.Len(t, c.queue, 1)
  41. require.Equal(t, 1, c.Len())
  42. require.Equal(t, 3, c.Size())
  43. c.Set(ctx, "/bar", String("bar"))
  44. require.Len(t, c.queue, 2)
  45. require.Equal(t, 2, c.Len())
  46. require.Equal(t, 6, c.Size())
  47. c.Set(ctx, "/bar", String("barre"))
  48. require.Len(t, c.queue, 3)
  49. require.Equal(t, 2, c.Len())
  50. require.Equal(t, 8, c.Size())
  51. c.Set(ctx, "/foo", String("fooo"))
  52. require.Len(t, c.queue, 2)
  53. require.Equal(t, 2, c.Len())
  54. require.Equal(t, 9, c.Size())
  55. }