github.com/myafeier/fabric@v1.0.1-0.20170722181825-3a4b1f2bce86/core/peer/peer_test.go (about)

     1  /*
     2  Copyright IBM Corp. 2016 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  
    17  package peer
    18  
    19  import (
    20  	"fmt"
    21  	"net"
    22  	"os"
    23  	"path/filepath"
    24  	"testing"
    25  
    26  	configtxtest "github.com/hyperledger/fabric/common/configtx/test"
    27  	"github.com/hyperledger/fabric/common/localmsp"
    28  	mscc "github.com/hyperledger/fabric/common/mocks/scc"
    29  	"github.com/hyperledger/fabric/core/comm"
    30  	ccp "github.com/hyperledger/fabric/core/common/ccprovider"
    31  	"github.com/hyperledger/fabric/core/common/sysccprovider"
    32  	"github.com/hyperledger/fabric/core/deliverservice"
    33  	"github.com/hyperledger/fabric/core/deliverservice/blocksprovider"
    34  	"github.com/hyperledger/fabric/core/mocks/ccprovider"
    35  	"github.com/hyperledger/fabric/gossip/api"
    36  	"github.com/hyperledger/fabric/gossip/service"
    37  	"github.com/hyperledger/fabric/msp/mgmt"
    38  	"github.com/hyperledger/fabric/msp/mgmt/testtools"
    39  	peergossip "github.com/hyperledger/fabric/peer/gossip"
    40  	"github.com/hyperledger/fabric/peer/gossip/mocks"
    41  	"github.com/spf13/viper"
    42  	"github.com/stretchr/testify/assert"
    43  	"google.golang.org/grpc"
    44  )
    45  
    46  type mockDeliveryClient struct {
    47  }
    48  
    49  // StartDeliverForChannel dynamically starts delivery of new blocks from ordering service
    50  // to channel peers.
    51  func (ds *mockDeliveryClient) StartDeliverForChannel(chainID string, ledgerInfo blocksprovider.LedgerInfo) error {
    52  	return nil
    53  }
    54  
    55  // StopDeliverForChannel dynamically stops delivery of new blocks from ordering service
    56  // to channel peers.
    57  func (ds *mockDeliveryClient) StopDeliverForChannel(chainID string) error {
    58  	return nil
    59  }
    60  
    61  // Stop terminates delivery service and closes the connection
    62  func (*mockDeliveryClient) Stop() {
    63  
    64  }
    65  
    66  type mockDeliveryClientFactory struct {
    67  }
    68  
    69  func (*mockDeliveryClientFactory) Service(g service.GossipService, endpoints []string, mcs api.MessageCryptoService) (deliverclient.DeliverService, error) {
    70  	return &mockDeliveryClient{}, nil
    71  }
    72  
    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  
   123  func TestInitialize(t *testing.T) {
   124  	viper.Set("peer.fileSystemPath", "/var/hyperledger/test/")
   125  
   126  	// we mock this because we can't import the chaincode package lest we create an import cycle
   127  	ccp.RegisterChaincodeProviderFactory(&ccprovider.MockCcProviderFactory{})
   128  	sysccprovider.RegisterSystemChaincodeProviderFactory(&mscc.MocksccProviderFactory{})
   129  
   130  	Initialize(nil)
   131  }
   132  
   133  func TestCreateChainFromBlock(t *testing.T) {
   134  	viper.Set("peer.fileSystemPath", "/var/hyperledger/test/")
   135  	defer os.RemoveAll("/var/hyperledger/test/")
   136  	testChainID := "mytestchainid"
   137  	block, err := configtxtest.MakeGenesisBlock(testChainID)
   138  	if err != nil {
   139  		fmt.Printf("Failed to create a config block, err %s\n", err)
   140  		t.FailNow()
   141  	}
   142  
   143  	// Initialize gossip service
   144  	grpcServer := grpc.NewServer()
   145  	socket, err := net.Listen("tcp", fmt.Sprintf("%s:%d", "", 13611))
   146  	assert.NoError(t, err)
   147  	go grpcServer.Serve(socket)
   148  	defer grpcServer.Stop()
   149  
   150  	msptesttools.LoadMSPSetupForTesting()
   151  
   152  	identity, _ := mgmt.GetLocalSigningIdentityOrPanic().Serialize()
   153  	messageCryptoService := peergossip.NewMCS(&mocks.ChannelPolicyManagerGetter{}, localmsp.NewSigner(), mgmt.NewDeserializersManager())
   154  	secAdv := peergossip.NewSecurityAdvisor(mgmt.NewDeserializersManager())
   155  	var defaultSecureDialOpts = func() []grpc.DialOption {
   156  		var dialOpts []grpc.DialOption
   157  		dialOpts = append(dialOpts, grpc.WithInsecure())
   158  		return dialOpts
   159  	}
   160  	err = service.InitGossipServiceCustomDeliveryFactory(
   161  		identity, "localhost:13611", grpcServer,
   162  		&mockDeliveryClientFactory{},
   163  		messageCryptoService, secAdv, defaultSecureDialOpts)
   164  
   165  	assert.NoError(t, err)
   166  
   167  	err = CreateChainFromBlock(block)
   168  	if err != nil {
   169  		t.Fatalf("failed to create chain %s", err)
   170  	}
   171  
   172  	// Correct ledger
   173  	ledger := GetLedger(testChainID)
   174  	if ledger == nil {
   175  		t.Fatalf("failed to get correct ledger")
   176  	}
   177  
   178  	// Get config block from ledger
   179  	block, err = getCurrConfigBlockFromLedger(ledger)
   180  	assert.NoError(t, err, "Failed to get config block from ledger")
   181  	assert.NotNil(t, block, "Config block should not be nil")
   182  	assert.Equal(t, uint64(0), block.Header.Number, "config block should have been block 0")
   183  
   184  	// Bad ledger
   185  	ledger = GetLedger("BogusChain")
   186  	if ledger != nil {
   187  		t.Fatalf("got a bogus ledger")
   188  	}
   189  
   190  	// Correct block
   191  	block = GetCurrConfigBlock(testChainID)
   192  	if block == nil {
   193  		t.Fatalf("failed to get correct block")
   194  	}
   195  
   196  	// Bad block
   197  	block = GetCurrConfigBlock("BogusBlock")
   198  	if block != nil {
   199  		t.Fatalf("got a bogus block")
   200  	}
   201  
   202  	// Correct PolicyManager
   203  	pmgr := GetPolicyManager(testChainID)
   204  	if pmgr == nil {
   205  		t.Fatal("failed to get PolicyManager")
   206  	}
   207  
   208  	// Bad PolicyManager
   209  	pmgr = GetPolicyManager("BogusChain")
   210  	if pmgr != nil {
   211  		t.Fatal("got a bogus PolicyManager")
   212  	}
   213  
   214  	// PolicyManagerGetter
   215  	pmg := NewChannelPolicyManagerGetter()
   216  	assert.NotNil(t, pmg, "PolicyManagerGetter should not be nil")
   217  
   218  	pmgr, ok := pmg.Manager(testChainID)
   219  	assert.NotNil(t, pmgr, "PolicyManager should not be nil")
   220  	assert.Equal(t, true, ok, "expected Manage() to return true")
   221  
   222  	// Chaos monkey test
   223  	Initialize(nil)
   224  
   225  	SetCurrConfigBlock(block, testChainID)
   226  
   227  	channels := GetChannelsInfo()
   228  	if len(channels) != 1 {
   229  		t.Fatalf("incorrect number of channels")
   230  	}
   231  }
   232  
   233  func TestNewPeerClientConnection(t *testing.T) {
   234  	if _, err := NewPeerClientConnection(); err != nil {
   235  		t.Log(err)
   236  	}
   237  }
   238  
   239  func TestGetLocalIP(t *testing.T) {
   240  	ip := GetLocalIP()
   241  	t.Log(ip)
   242  }