Skip to content

Commit

Permalink
[FAB-12516] GetBlock: Close() ledger iterator
Browse files Browse the repository at this point in the history
This change set ensures the ledger iterator is closed
in GetBlock method

Change-Id: I294cfe1ba94a6f11b266184f01a30be6c5780dff
Signed-off-by: yacovm <yacovm@il.ibm.com>
  • Loading branch information
yacovm committed Oct 17, 2018
1 parent 43d0772 commit 3b36b1a
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 2 deletions.
8 changes: 6 additions & 2 deletions common/ledger/blockledger/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,16 @@ func CreateNextBlock(rl Reader, messages []*cb.Envelope) *cb.Block {

// GetBlock is a utility method for retrieving a single block
func GetBlock(rl Reader, index uint64) *cb.Block {
i, _ := rl.Iterator(&ab.SeekPosition{
iterator, _ := rl.Iterator(&ab.SeekPosition{
Type: &ab.SeekPosition_Specified{
Specified: &ab.SeekSpecified{Number: index},
},
})
block, status := i.Next()
if iterator == nil {
return nil
}
defer iterator.Close()
block, status := iterator.Next()
if status != cb.Status_SUCCESS {
return nil
}
Expand Down
55 changes: 55 additions & 0 deletions common/ledger/blockledger/util_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/

package blockledger_test

import (
"testing"

"github.com/hyperledger/fabric/common/deliver/mock"
"github.com/hyperledger/fabric/common/ledger/blockledger"
"github.com/hyperledger/fabric/protos/common"
"github.com/stretchr/testify/assert"
)

func TestClose(t *testing.T) {
for _, testCase := range []struct {
name string
status common.Status
isIteratorNil bool
expectedCloseCount int
}{
{
name: "nil iterator",
isIteratorNil: true,
},
{
name: "Next() fails",
status: common.Status_INTERNAL_SERVER_ERROR,
expectedCloseCount: 1,
},
{
name: "Next() succeeds",
status: common.Status_SUCCESS,
expectedCloseCount: 1,
},
} {
t.Run(testCase.name, func(t *testing.T) {
var iterator *mock.BlockIterator
reader := &mock.BlockReader{}
if !testCase.isIteratorNil {
iterator = &mock.BlockIterator{}
iterator.NextReturns(&common.Block{}, testCase.status)
reader.IteratorReturns(iterator, 1)
}

blockledger.GetBlock(reader, 1)
if !testCase.isIteratorNil {
assert.Equal(t, testCase.expectedCloseCount, iterator.CloseCallCount())
}
})
}
}

0 comments on commit 3b36b1a

Please sign in to comment.