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.

104 lines
2.3 KiB

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