block_cache_test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright 2015 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum 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. // go-ethereum 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 go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package core
  17. import (
  18. "math/big"
  19. "testing"
  20. "github.com/ethereum/go-ethereum/common"
  21. "github.com/ethereum/go-ethereum/core/types"
  22. )
  23. func newChain(size int) (chain []*types.Block) {
  24. var parentHash common.Hash
  25. for i := 0; i < size; i++ {
  26. head := &types.Header{ParentHash: parentHash, Number: big.NewInt(int64(i))}
  27. block := types.NewBlock(head, nil, nil, nil)
  28. chain = append(chain, block)
  29. parentHash = block.Hash()
  30. }
  31. return chain
  32. }
  33. func insertChainCache(cache *BlockCache, chain []*types.Block) {
  34. for _, block := range chain {
  35. cache.Push(block)
  36. }
  37. }
  38. func TestNewBlockCache(t *testing.T) {
  39. chain := newChain(3)
  40. cache := NewBlockCache(2)
  41. insertChainCache(cache, chain)
  42. if cache.hashes[0] != chain[1].Hash() {
  43. t.Error("oldest block incorrect")
  44. }
  45. }
  46. func TestInclusion(t *testing.T) {
  47. chain := newChain(3)
  48. cache := NewBlockCache(3)
  49. insertChainCache(cache, chain)
  50. for _, block := range chain {
  51. if b := cache.Get(block.Hash()); b == nil {
  52. t.Errorf("getting %x failed", block.Hash())
  53. }
  54. }
  55. }
  56. func TestDeletion(t *testing.T) {
  57. chain := newChain(3)
  58. cache := NewBlockCache(3)
  59. insertChainCache(cache, chain)
  60. cache.Delete(chain[1].Hash())
  61. if cache.Has(chain[1].Hash()) {
  62. t.Errorf("expected %x not to be included")
  63. }
  64. }