Skip to content

Commit fdb6ce1

Browse files
committed
[FAB-3723] Unit tests and cleanup for core/peer pkg
Added missing test coverage for config.go,removed unused code and cleaned up a bit to aid in eventually removing test code from peer.go. Increased # lines covered from 51% to 78% Change-Id: I0249d3c9edf6f764b2c1b66dc4af3af1048430a4 Signed-off-by: Gari Singh <[email protected]>
1 parent 0fe5cb2 commit fdb6ce1

File tree

5 files changed

+207
-64
lines changed

5 files changed

+207
-64
lines changed

core/peer/config.go

+1-19
Original file line numberDiff line numberDiff line change
@@ -53,12 +53,6 @@ var peerEndpointError error
5353

5454
// Cached values of commonly used configuration constants.
5555

56-
// Note: There is some kind of circular import issue that prevents us from
57-
// importing the "core" package into the "peer" package. The
58-
// 'peer.SecurityEnabled' bit is a duplicate of the 'core.SecurityEnabled'
59-
// bit.
60-
var securityEnabled bool
61-
6256
// CacheConfiguration computes and caches commonly-used constants and
6357
// computed constants as package variables. Routines which were previously
6458
// global have been embedded here to preserve the original abstraction.
@@ -92,16 +86,12 @@ func CacheConfiguration() (err error) {
9286
}
9387

9488
localAddress, localAddressError = getLocalAddress()
95-
peerEndpoint, peerEndpointError = getPeerEndpoint()
96-
97-
securityEnabled = true
89+
peerEndpoint, _ = getPeerEndpoint()
9890

9991
configurationCached = true
10092

10193
if localAddressError != nil {
10294
return localAddressError
103-
} else if peerEndpointError != nil {
104-
return peerEndpointError
10595
}
10696
return
10797
}
@@ -131,14 +121,6 @@ func GetPeerEndpoint() (*pb.PeerEndpoint, error) {
131121
return peerEndpoint, peerEndpointError
132122
}
133123

134-
// SecurityEnabled returns the securityEnabled property from cached configuration
135-
func SecurityEnabled() bool {
136-
if !configurationCached {
137-
cacheConfiguration()
138-
}
139-
return securityEnabled
140-
}
141-
142124
// GetSecureConfig returns the secure server configuration for the peer
143125
func GetSecureConfig() (comm.SecureServerConfig, error) {
144126
secureConfig := comm.SecureServerConfig{

core/peer/config_test.go

+125
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
/*
2+
Copyright IBM Corp. 2017 All Rights Reserved.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
package peer
17+
18+
import (
19+
"net"
20+
"testing"
21+
22+
"github.com/spf13/viper"
23+
"github.com/stretchr/testify/assert"
24+
)
25+
26+
func TestCacheConfigurationNegative(t *testing.T) {
27+
28+
// set a bad peer.address
29+
viper.Set("peer.addressAutoDetect", true)
30+
viper.Set("peer.address", "testing.com")
31+
cacheConfiguration()
32+
err := CacheConfiguration()
33+
assert.Error(t, err, "Expected error for bad configuration")
34+
}
35+
36+
func TestConfiguration(t *testing.T) {
37+
38+
var ips []string
39+
// get the interface addresses
40+
if addresses, err := net.InterfaceAddrs(); err == nil {
41+
for _, address := range addresses {
42+
// eliminate loopback interfaces
43+
if ip, ok := address.(*net.IPNet); ok && !ip.IP.IsLoopback() {
44+
ips = append(ips, ip.IP.String()+":7051")
45+
t.Logf("found interface address [%s]", ip.IP.String())
46+
}
47+
}
48+
} else {
49+
t.Fatal("Failed to get interface addresses")
50+
}
51+
52+
var tests = []struct {
53+
name string
54+
settings map[string]interface{}
55+
validAddresses []string
56+
invalidAddresses []string
57+
}{
58+
{
59+
name: "test1",
60+
settings: map[string]interface{}{
61+
"peer.addressAutoDetect": false,
62+
"peer.address": "testing.com:7051",
63+
"peer.id": "testPeer",
64+
},
65+
validAddresses: []string{"testing.com:7051"},
66+
invalidAddresses: ips,
67+
},
68+
{
69+
name: "test2",
70+
settings: map[string]interface{}{
71+
"peer.addressAutoDetect": true,
72+
"peer.address": "testing.com:7051",
73+
"peer.id": "testPeer",
74+
},
75+
validAddresses: ips,
76+
invalidAddresses: []string{"testing.com:7051"},
77+
},
78+
}
79+
80+
for _, test := range tests {
81+
test := test
82+
t.Run(test.name, func(t *testing.T) {
83+
for k, v := range test.settings {
84+
viper.Set(k, v)
85+
}
86+
// reset the cache
87+
configurationCached = false
88+
// GetLocalAddress
89+
address, err := GetLocalAddress()
90+
assert.NoError(t, err, "GetLocalAddress returned unexpected error")
91+
assert.Contains(t, test.validAddresses, address,
92+
"GetLocalAddress returned unexpected address")
93+
assert.NotContains(t, test.invalidAddresses, address,
94+
"GetLocalAddress returned invalid address")
95+
// reset the cache
96+
configurationCached = false
97+
// GetPeerEndpoint
98+
pe, err := GetPeerEndpoint()
99+
assert.NoError(t, err, "GetPeerEndpoint returned unexpected error")
100+
assert.Equal(t, test.settings["peer.id"], pe.Id.Name,
101+
"GetPeerEndpoint returned the wrong peer ID")
102+
assert.Equal(t, address, pe.Address,
103+
"GetPeerEndpoint returned the wrong peer address")
104+
105+
// now check with cached configuration
106+
err = CacheConfiguration()
107+
assert.NoError(t, err, "CacheConfiguration should not have returned an err")
108+
// check functions again
109+
// GetLocalAddress
110+
address, err = GetLocalAddress()
111+
assert.NoError(t, err, "GetLocalAddress should not have returned error")
112+
assert.Contains(t, test.validAddresses, address,
113+
"GetLocalAddress returned unexpected address")
114+
assert.NotContains(t, test.invalidAddresses, address,
115+
"GetLocalAddress returned invalid address")
116+
// GetPeerEndpoint
117+
pe, err = GetPeerEndpoint()
118+
assert.NoError(t, err, "GetPeerEndpoint returned unexpected error")
119+
assert.Equal(t, test.settings["peer.id"], pe.Id.Name,
120+
"GetPeerEndpoint returned the wrong peer ID")
121+
assert.Equal(t, address, pe.Address,
122+
"GetPeerEndpoint returned the wrong peer address")
123+
})
124+
}
125+
}

core/peer/errors.go

-32
This file was deleted.

core/peer/peer.go

+6-13
Original file line numberDiff line numberDiff line change
@@ -267,8 +267,12 @@ func CreateChainFromBlock(cb *common.Block) error {
267267
func MockCreateChain(cid string) error {
268268
var ledger ledger.PeerLedger
269269
var err error
270-
if ledger, err = createLedger(cid); err != nil {
271-
return err
270+
271+
if ledger = GetLedger(cid); ledger == nil {
272+
gb, _ := configtxtest.MakeGenesisBlock(cid)
273+
if ledger, err = ledgermgmt.CreateLedger(gb); err != nil {
274+
return err
275+
}
272276
}
273277

274278
// Here we need to mock also the policy manager
@@ -485,17 +489,6 @@ func SetCurrConfigBlock(block *common.Block, cid string) error {
485489
return fmt.Errorf("Chain %s doesn't exist on the peer", cid)
486490
}
487491

488-
// createLedger function is used only for the testing (see function 'MockCreateChain').
489-
// TODO - this function should not be in this file which contains production code
490-
func createLedger(cid string) (ledger.PeerLedger, error) {
491-
var ledger ledger.PeerLedger
492-
if ledger = GetLedger(cid); ledger != nil {
493-
return ledger, nil
494-
}
495-
gb, _ := configtxtest.MakeGenesisBlock(cid)
496-
return ledgermgmt.CreateLedger(gb)
497-
}
498-
499492
// NewPeerClientConnection Returns a new grpc.ClientConn to the configured local PEER.
500493
func NewPeerClientConnection() (*grpc.ClientConn, error) {
501494
return NewPeerClientConnectionWithAddress(viper.GetString("peer.address"))

core/peer/peer_test.go

+75
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,13 @@ import (
2020
"fmt"
2121
"net"
2222
"os"
23+
"path/filepath"
2324
"testing"
2425

2526
configtxtest "github.com/hyperledger/fabric/common/configtx/test"
2627
"github.com/hyperledger/fabric/common/localmsp"
2728
mscc "github.com/hyperledger/fabric/common/mocks/scc"
29+
"github.com/hyperledger/fabric/core/comm"
2830
ccp "github.com/hyperledger/fabric/core/common/ccprovider"
2931
"github.com/hyperledger/fabric/core/common/sysccprovider"
3032
"github.com/hyperledger/fabric/core/deliverservice"
@@ -68,6 +70,56 @@ func (*mockDeliveryClientFactory) Service(g service.GossipService, endpoints []s
6870
return &mockDeliveryClient{}, nil
6971
}
7072

73+
func TestCreatePeerServer(t *testing.T) {
74+
75+
server, err := CreatePeerServer(":4050", comm.SecureServerConfig{})
76+
assert.NoError(t, err, "CreatePeerServer returned unexpected error")
77+
assert.Equal(t, "[::]:4050", server.Address(),
78+
"CreatePeerServer returned the wrong address")
79+
server.Stop()
80+
81+
_, err = CreatePeerServer("", comm.SecureServerConfig{})
82+
assert.Error(t, err, "expected CreatePeerServer to return error with missing address")
83+
84+
}
85+
86+
func TestGetSecureConfig(t *testing.T) {
87+
88+
// good config without TLS
89+
viper.Set("peer.tls.enabled", false)
90+
sc, _ := GetSecureConfig()
91+
assert.Equal(t, false, sc.UseTLS, "SecureConfig.UseTLS should be false")
92+
93+
// good config with TLS
94+
viper.Set("peer.tls.enabled", true)
95+
viper.Set("peer.tls.cert.file", filepath.Join("testdata", "Org1-server1-cert.pem"))
96+
viper.Set("peer.tls.key.file", filepath.Join("testdata", "Org1-server1-key.pem"))
97+
viper.Set("peer.tls.rootcert.file", filepath.Join("testdata", "Org1-cert.pem"))
98+
sc, _ = GetSecureConfig()
99+
assert.Equal(t, true, sc.UseTLS, "SecureConfig.UseTLS should be true")
100+
101+
// bad config with TLS
102+
viper.Set("peer.tls.rootcert.file", filepath.Join("testdata", "Org11-cert.pem"))
103+
_, err := GetSecureConfig()
104+
assert.Error(t, err, "GetSecureConfig should return error with bad root cert path")
105+
viper.Set("peer.tls.cert.file", filepath.Join("testdata", "Org11-cert.pem"))
106+
_, err = GetSecureConfig()
107+
assert.Error(t, err, "GetSecureConfig should return error with bad tls cert path")
108+
109+
// disable TLS for remaining tests
110+
viper.Set("peer.tls.enabled", false)
111+
112+
}
113+
114+
func TestInitChain(t *testing.T) {
115+
116+
chainId := "testChain"
117+
chainInitializer = func(cid string) {
118+
assert.Equal(t, chainId, cid, "chainInitializer received unexpected cid")
119+
}
120+
InitChain(chainId)
121+
}
122+
71123
func TestInitialize(t *testing.T) {
72124
viper.Set("peer.fileSystemPath", "/var/hyperledger/test/")
73125

@@ -121,6 +173,9 @@ func TestCreateChainFromBlock(t *testing.T) {
121173
t.Fatalf("failed to get correct ledger")
122174
}
123175

176+
// Config block from ledger
177+
block, err = getCurrConfigBlockFromLedger(ledger)
178+
124179
// Bad ledger
125180
ledger = GetLedger("BogusChain")
126181
if ledger != nil {
@@ -139,6 +194,26 @@ func TestCreateChainFromBlock(t *testing.T) {
139194
t.Fatalf("got a bogus block")
140195
}
141196

197+
// Correct PolicyManager
198+
pmgr := GetPolicyManager(testChainID)
199+
if pmgr == nil {
200+
t.Fatal("failed to get PolicyManager")
201+
}
202+
203+
// Bad PolicyManager
204+
pmgr = GetPolicyManager("BogusChain")
205+
if pmgr != nil {
206+
t.Fatal("got a bogus PolicyManager")
207+
}
208+
209+
// PolicyManagerGetter
210+
pmg := NewChannelPolicyManagerGetter()
211+
assert.NotNil(t, pmg, "PolicyManagerGetter should not be nil")
212+
213+
pmgr, ok := pmg.Manager(testChainID)
214+
assert.NotNil(t, pmgr, "PolicyManager should not be nil")
215+
assert.Equal(t, true, ok, "expected Manage() to return true")
216+
142217
// Chaos monkey test
143218
Initialize(nil)
144219

0 commit comments

Comments
 (0)