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.

106 lines
2.3 KiB

  1. package db
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "fmt"
  6. "os"
  7. "testing"
  8. "github.com/syndtr/goleveldb/leveldb/opt"
  9. "github.com/stretchr/testify/require"
  10. cmn "github.com/tendermint/tendermint/libs/common"
  11. )
  12. func TestNewGoLevelDB(t *testing.T) {
  13. name := fmt.Sprintf("test_%x", cmn.RandStr(12))
  14. // Test write locks
  15. db, err := NewGoLevelDB(name, "")
  16. require.Nil(t, err)
  17. defer os.RemoveAll("./" + name + ".db")
  18. _, err = NewGoLevelDB(name, "")
  19. require.NotNil(t, err)
  20. db.Close() // Close the db to release the lock
  21. // Open the db twice in a row to test read-only locks
  22. ro1, err := NewGoLevelDBWithOpts(name, "", &opt.Options{ReadOnly: true})
  23. defer ro1.Close()
  24. require.Nil(t, err)
  25. ro2, err := NewGoLevelDBWithOpts(name, "", &opt.Options{ReadOnly: true})
  26. defer ro2.Close()
  27. require.Nil(t, err)
  28. }
  29. func BenchmarkRandomReadsWrites(b *testing.B) {
  30. b.StopTimer()
  31. numItems := int64(1000000)
  32. internal := map[int64]int64{}
  33. for i := 0; i < int(numItems); i++ {
  34. internal[int64(i)] = int64(0)
  35. }
  36. db, err := NewGoLevelDB(fmt.Sprintf("test_%x", cmn.RandStr(12)), "")
  37. if err != nil {
  38. b.Fatal(err.Error())
  39. return
  40. }
  41. fmt.Println("ok, starting")
  42. b.StartTimer()
  43. for i := 0; i < b.N; i++ {
  44. // Write something
  45. {
  46. idx := (int64(cmn.RandInt()) % numItems)
  47. internal[idx]++
  48. val := internal[idx]
  49. idxBytes := int642Bytes(int64(idx))
  50. valBytes := int642Bytes(int64(val))
  51. //fmt.Printf("Set %X -> %X\n", idxBytes, valBytes)
  52. db.Set(
  53. idxBytes,
  54. valBytes,
  55. )
  56. }
  57. // Read something
  58. {
  59. idx := (int64(cmn.RandInt()) % numItems)
  60. val := internal[idx]
  61. idxBytes := int642Bytes(int64(idx))
  62. valBytes := db.Get(idxBytes)
  63. //fmt.Printf("Get %X -> %X\n", idxBytes, valBytes)
  64. if val == 0 {
  65. if !bytes.Equal(valBytes, nil) {
  66. b.Errorf("Expected %v for %v, got %X",
  67. nil, idx, valBytes)
  68. break
  69. }
  70. } else {
  71. if len(valBytes) != 8 {
  72. b.Errorf("Expected length 8 for %v, got %X",
  73. idx, valBytes)
  74. break
  75. }
  76. valGot := bytes2Int64(valBytes)
  77. if val != valGot {
  78. b.Errorf("Expected %v for %v, got %v",
  79. val, idx, valGot)
  80. break
  81. }
  82. }
  83. }
  84. }
  85. db.Close()
  86. }
  87. func int642Bytes(i int64) []byte {
  88. buf := make([]byte, 8)
  89. binary.BigEndian.PutUint64(buf, uint64(i))
  90. return buf
  91. }
  92. func bytes2Int64(buf []byte) int64 {
  93. return int64(binary.BigEndian.Uint64(buf))
  94. }