iterator_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package trie
  17. import (
  18. "testing"
  19. "github.com/ethereum/go-ethereum/common"
  20. "github.com/ethereum/go-ethereum/ethdb"
  21. )
  22. func TestIterator(t *testing.T) {
  23. trie := newEmpty()
  24. vals := []struct{ k, v string }{
  25. {"do", "verb"},
  26. {"ether", "wookiedoo"},
  27. {"horse", "stallion"},
  28. {"shaman", "horse"},
  29. {"doge", "coin"},
  30. {"dog", "puppy"},
  31. {"somethingveryoddindeedthis is", "myothernodedata"},
  32. }
  33. v := make(map[string]bool)
  34. for _, val := range vals {
  35. v[val.k] = false
  36. trie.Update([]byte(val.k), []byte(val.v))
  37. }
  38. trie.Commit()
  39. it := NewIterator(trie)
  40. for it.Next() {
  41. v[string(it.Key)] = true
  42. }
  43. for k, found := range v {
  44. if !found {
  45. t.Error("iterator didn't find", k)
  46. }
  47. }
  48. }
  49. // Tests that the node iterator indeed walks over the entire database contents.
  50. func TestNodeIteratorCoverage(t *testing.T) {
  51. // Create some arbitrary test trie to iterate
  52. db, trie, _ := makeTestTrie()
  53. // Gather all the node hashes found by the iterator
  54. hashes := make(map[common.Hash]struct{})
  55. for it := NewNodeIterator(trie); it.Next(); {
  56. if it.Hash != (common.Hash{}) {
  57. hashes[it.Hash] = struct{}{}
  58. }
  59. }
  60. // Cross check the hashes and the database itself
  61. for hash, _ := range hashes {
  62. if _, err := db.Get(hash.Bytes()); err != nil {
  63. t.Errorf("failed to retrieve reported node %x: %v", hash, err)
  64. }
  65. }
  66. for _, key := range db.(*ethdb.MemDatabase).Keys() {
  67. if _, ok := hashes[common.BytesToHash(key)]; !ok {
  68. t.Errorf("state entry not reported %x", key)
  69. }
  70. }
  71. }