file_cache_test.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package server
  2. import (
  3. "bytes"
  4. "fmt"
  5. "github.com/stretchr/testify/require"
  6. "heckel.io/ntfy/util"
  7. "os"
  8. "strings"
  9. "testing"
  10. )
  11. var (
  12. oneKilobyteArray = make([]byte, 1024)
  13. )
  14. func TestFileCache_Write_Success(t *testing.T) {
  15. dir, c := newTestFileCache(t)
  16. size, err := c.Write("abcdefghijkl", strings.NewReader("normal file"), util.NewFixedLimiter(999))
  17. require.Nil(t, err)
  18. require.Equal(t, int64(11), size)
  19. require.Equal(t, "normal file", readFile(t, dir+"/abcdefghijkl"))
  20. require.Equal(t, int64(11), c.Size())
  21. require.Equal(t, int64(10229), c.Remaining())
  22. }
  23. func TestFileCache_Write_Remove_Success(t *testing.T) {
  24. dir, c := newTestFileCache(t) // max = 10k (10240), each = 1k (1024)
  25. for i := 0; i < 10; i++ { // 10x999 = 9990
  26. size, err := c.Write(fmt.Sprintf("abcdefghijk%d", i), bytes.NewReader(make([]byte, 999)))
  27. require.Nil(t, err)
  28. require.Equal(t, int64(999), size)
  29. }
  30. require.Equal(t, int64(9990), c.Size())
  31. require.Equal(t, int64(250), c.Remaining())
  32. require.FileExists(t, dir+"/abcdefghijk1")
  33. require.FileExists(t, dir+"/abcdefghijk5")
  34. require.Nil(t, c.Remove("abcdefghijk1", "abcdefghijk5"))
  35. require.NoFileExists(t, dir+"/abcdefghijk1")
  36. require.NoFileExists(t, dir+"/abcdefghijk5")
  37. require.Equal(t, int64(7992), c.Size())
  38. require.Equal(t, int64(2248), c.Remaining())
  39. }
  40. func TestFileCache_Write_FailedTotalSizeLimit(t *testing.T) {
  41. dir, c := newTestFileCache(t)
  42. for i := 0; i < 10; i++ {
  43. size, err := c.Write(fmt.Sprintf("abcdefghijk%d", i), bytes.NewReader(oneKilobyteArray))
  44. require.Nil(t, err)
  45. require.Equal(t, int64(1024), size)
  46. }
  47. _, err := c.Write("abcdefghijkX", bytes.NewReader(oneKilobyteArray))
  48. require.Equal(t, util.ErrLimitReached, err)
  49. require.NoFileExists(t, dir+"/abcdefghijkX")
  50. }
  51. func TestFileCache_Write_FailedAdditionalLimiter(t *testing.T) {
  52. dir, c := newTestFileCache(t)
  53. _, err := c.Write("abcdefghijkl", bytes.NewReader(make([]byte, 1001)), util.NewFixedLimiter(1000))
  54. require.Equal(t, util.ErrLimitReached, err)
  55. require.NoFileExists(t, dir+"/abcdefghijkl")
  56. }
  57. func newTestFileCache(t *testing.T) (dir string, cache *fileCache) {
  58. dir = t.TempDir()
  59. cache, err := newFileCache(dir, 10*1024)
  60. require.Nil(t, err)
  61. return dir, cache
  62. }
  63. func readFile(t *testing.T, f string) string {
  64. b, err := os.ReadFile(f)
  65. require.Nil(t, err)
  66. return string(b)
  67. }