You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.2 KiB

  1. package db
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/require"
  5. )
  6. func bz(s string) []byte { return []byte(s) }
  7. func TestCacheDB(t *testing.T) {
  8. mem := NewMemDB()
  9. cdb := mem.CacheDB()
  10. require.Empty(t, cdb.Get(bz("key1")), "Expected `key1` to be empty")
  11. mem.Set(bz("key1"), bz("value1"))
  12. cdb.Set(bz("key1"), bz("value1"))
  13. require.Equal(t, bz("value1"), cdb.Get(bz("key1")))
  14. cdb.Set(bz("key1"), bz("value2"))
  15. require.Equal(t, bz("value2"), cdb.Get(bz("key1")))
  16. require.Equal(t, bz("value1"), mem.Get(bz("key1")))
  17. cdb.Write()
  18. require.Equal(t, bz("value2"), mem.Get(bz("key1")))
  19. require.Panics(t, func() { cdb.Write() }, "Expected second cdb.Write() to fail")
  20. cdb = mem.CacheDB()
  21. cdb.Delete(bz("key1"))
  22. require.Empty(t, cdb.Get(bz("key1")))
  23. require.Equal(t, mem.Get(bz("key1")), bz("value2"))
  24. cdb.Write()
  25. require.Empty(t, cdb.Get(bz("key1")), "Expected `key1` to be empty")
  26. require.Empty(t, mem.Get(bz("key1")), "Expected `key1` to be empty")
  27. }
  28. func TestCacheDBWriteLock(t *testing.T) {
  29. mem := NewMemDB()
  30. cdb := mem.CacheDB()
  31. require.NotPanics(t, func() { cdb.Write() })
  32. require.Panics(t, func() { cdb.Write() })
  33. cdb = mem.CacheDB()
  34. require.NotPanics(t, func() { cdb.Write() })
  35. require.Panics(t, func() { cdb.Write() })
  36. }
  37. func TestCacheDBWriteLockNested(t *testing.T) {
  38. mem := NewMemDB()
  39. cdb := mem.CacheDB()
  40. cdb2 := cdb.CacheDB()
  41. require.NotPanics(t, func() { cdb2.Write() })
  42. require.Panics(t, func() { cdb2.Write() })
  43. cdb2 = cdb.CacheDB()
  44. require.NotPanics(t, func() { cdb2.Write() })
  45. require.Panics(t, func() { cdb2.Write() })
  46. }
  47. func TestCacheDBNested(t *testing.T) {
  48. mem := NewMemDB()
  49. cdb := mem.CacheDB()
  50. cdb.Set(bz("key1"), bz("value1"))
  51. require.Empty(t, mem.Get(bz("key1")))
  52. require.Equal(t, bz("value1"), cdb.Get(bz("key1")))
  53. cdb2 := cdb.CacheDB()
  54. require.Equal(t, bz("value1"), cdb2.Get(bz("key1")))
  55. cdb2.Set(bz("key1"), bz("VALUE2"))
  56. require.Equal(t, []byte(nil), mem.Get(bz("key1")))
  57. require.Equal(t, bz("value1"), cdb.Get(bz("key1")))
  58. require.Equal(t, bz("VALUE2"), cdb2.Get(bz("key1")))
  59. cdb2.Write()
  60. require.Equal(t, []byte(nil), mem.Get(bz("key1")))
  61. require.Equal(t, bz("VALUE2"), cdb.Get(bz("key1")))
  62. cdb.Write()
  63. require.Equal(t, bz("VALUE2"), mem.Get(bz("key1")))
  64. }