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.

107 lines
2.4 KiB

  1. package arbo
  2. import (
  3. "bytes"
  4. "io"
  5. "io/ioutil"
  6. "os"
  7. "testing"
  8. "time"
  9. qt "github.com/frankban/quicktest"
  10. "go.vocdoni.io/dvote/db"
  11. )
  12. func checkRoots(c *qt.C, tree1, tree2 *Tree) {
  13. if !bytes.Equal(tree2.Root(), tree1.Root()) {
  14. dir := "err-dump"
  15. if _, err := os.Stat(dir); os.IsNotExist(err) {
  16. err := os.Mkdir(dir, os.ModePerm)
  17. c.Assert(err, qt.IsNil)
  18. }
  19. // store tree1
  20. storeTree(c, tree1, dir+"/tree1")
  21. // store tree2
  22. storeTree(c, tree2, dir+"/tree2")
  23. c.Check(tree2.Root(), qt.DeepEquals, tree1.Root())
  24. }
  25. }
  26. func storeTree(c *qt.C, tree *Tree, path string) {
  27. dump, err := tree.Dump(nil)
  28. c.Assert(err, qt.IsNil)
  29. err = ioutil.WriteFile(path+"-"+time.Now().String()+".debug", dump, 0600)
  30. c.Assert(err, qt.IsNil)
  31. }
  32. // nolint:unused
  33. func readTree(c *qt.C, tree *Tree, path string) {
  34. b, err := ioutil.ReadFile(path) //nolint:gosec
  35. c.Assert(err, qt.IsNil)
  36. err = tree.ImportDump(b)
  37. c.Assert(err, qt.IsNil)
  38. }
  39. // nolint:unused
  40. func importDumpLoopAdd(tree *Tree, b []byte) error {
  41. r := bytes.NewReader(b)
  42. var err error
  43. for {
  44. l := make([]byte, 2)
  45. _, err = io.ReadFull(r, l)
  46. if err == io.EOF {
  47. break
  48. } else if err != nil {
  49. return err
  50. }
  51. k := make([]byte, l[0])
  52. _, err = io.ReadFull(r, k)
  53. if err != nil {
  54. return err
  55. }
  56. v := make([]byte, l[1])
  57. _, err = io.ReadFull(r, v)
  58. if err != nil {
  59. return err
  60. }
  61. err = tree.Add(k, v)
  62. if err != nil {
  63. return err
  64. }
  65. }
  66. return nil
  67. }
  68. func TestReadTreeDBG(t *testing.T) {
  69. t.Skip() // test just for debugging purposes, disabled by default
  70. c := qt.New(t)
  71. database1, err := db.NewBadgerDB(c.TempDir())
  72. c.Assert(err, qt.IsNil)
  73. tree1, err := NewTree(database1, 100, HashFunctionBlake2b)
  74. c.Assert(err, qt.IsNil)
  75. database2, err := db.NewBadgerDB(c.TempDir())
  76. c.Assert(err, qt.IsNil)
  77. tree2, err := NewTree(database2, 100, HashFunctionBlake2b)
  78. c.Assert(err, qt.IsNil)
  79. // tree1 is generated by a loop of .Add
  80. path := "err-dump/tree1-2021-06-03 16:45:54.104449306 +0200 CEST m=+0.073874545.debug"
  81. b, err := ioutil.ReadFile(path)
  82. c.Assert(err, qt.IsNil)
  83. err = importDumpLoopAdd(tree1, b)
  84. c.Assert(err, qt.IsNil)
  85. // tree2 is generated by .AddBatch
  86. path = "err-dump/tree2-2021-06-03 16:45:54.104525519 +0200 CEST m=+0.073950756.debug"
  87. readTree(c, tree2, path)
  88. // tree1.PrintGraphvizFirstNLevels(nil, 6)
  89. // tree2.PrintGraphvizFirstNLevels(nil, 6)
  90. c.Check(tree2.Root(), qt.DeepEquals, tree1.Root())
  91. }