Пример #1
0
func TestDBConnectionDef(t *testing.T) {

	//call a helper method to load the core.yaml
	testutil.SetupCoreYAMLConfig("./../../../../peer")

	//create a new connection
	_, err := CreateConnectionDefinition(connectURL, "database", "", "")
	testutil.AssertNoError(t, err, fmt.Sprintf("Error when trying to create database connection definition"))

}
Пример #2
0
//History Database commit and read is being tested with kv_ledger_test.go.
//This test will push some of the testing down into history itself
func TestHistoryDatabaseCommit(t *testing.T) {
	//call a helper method to load the core.yaml
	testutil.SetupCoreYAMLConfig("./../../../peer")
	logger.Debugf("===HISTORYDB=== TestHistoryDatabaseCommit  IsCouchDBEnabled()value: %v , IsHistoryDBEnabled()value: %v\n",
		ledgerconfig.IsCouchDBEnabled(), ledgerconfig.IsHistoryDBEnabled())

	if ledgerconfig.IsHistoryDBEnabled() == true {
		//TODO Build the necessary infrastructure so that history can be tested iwthout ledger

	}
}
Пример #3
0
//Unit test of couch db util functionality
func TestCreateCouchDBConnectionAndDB(t *testing.T) {

	//call a helper method to load the core.yaml
	testutil.SetupCoreYAMLConfig("./../../../../peer")

	if ledgerconfig.IsCouchDBEnabled() == true {

		cleanup()
		defer cleanup()
		//create a new connection
		_, err := CreateCouchDBConnectionAndDB(connectURL, database, "", "")
		testutil.AssertNoError(t, err, fmt.Sprintf("Error when trying to CreateCouchDBConnectionAndDB"))
	}

}
Пример #4
0
func newTestEnv(t testing.TB) *testEnv {

	//call a helper method to load the core.yaml
	testutil.SetupCoreYAMLConfig("./../../../../../peer")

	couchDBDef := ledgerconfig.GetCouchDBDefinition()

	conf := &Conf{"/tmp/tests/ledger/kvledger/txmgmt/couchdbtxmgmt"}
	os.RemoveAll(conf.DBPath)
	return &testEnv{
		conf:              conf,
		couchDBAddress:    couchDBDef.URL,
		couchDatabaseName: "system_test",
		couchUsername:     couchDBDef.Username,
		couchPassword:     couchDBDef.Password,
	}
}
Пример #5
0
// couchdb_test.go tests couchdb functions already.  This test just tests that a CouchDB state database is auto-created
// upon creating a new ledger transaction manager
func TestDatabaseAutoCreate(t *testing.T) {

	//call a helper method to load the core.yaml
	testutil.SetupCoreYAMLConfig("./../../../../../peer")

	//Only run the tests if CouchDB is explitily enabled in the code,
	//otherwise CouchDB may not be installed and all the tests would fail
	//TODO replace this with external config property rather than config within the code
	if ledgerconfig.IsCouchDBEnabled() == true {

		env := newTestEnv(t)
		env.Cleanup()       //cleanup at the beginning to ensure the database doesn't exist already
		defer env.Cleanup() //and cleanup at the end

		txMgr := NewCouchDBTxMgr(env.conf,
			env.couchDBAddress,    //couchDB Address
			env.couchDatabaseName, //couchDB db name
			env.couchUsername,     //enter couchDB id
			env.couchPassword)     //enter couchDB pw

		//NewCouchDBTxMgr should have automatically created the database, let's make sure it has been created
		//Retrieve the info for the new database and make sure the name matches
		dbResp, _, errdb := txMgr.couchDB.GetDatabaseInfo()
		testutil.AssertNoError(t, errdb, fmt.Sprintf("Error when trying to retrieve database information"))
		testutil.AssertEquals(t, dbResp.DbName, env.couchDatabaseName)

		txMgr.Shutdown()

		//Call NewCouchDBTxMgr again, this time the database will already exist from last time
		txMgr2 := NewCouchDBTxMgr(env.conf,
			env.couchDBAddress,    //couchDB Address
			env.couchDatabaseName, //couchDB db name
			env.couchUsername,     //enter couchDB id
			env.couchPassword)     //enter couchDB pw

		//Retrieve the info for the database again, and make sure the name still matches
		dbResp2, _, errdb2 := txMgr2.couchDB.GetDatabaseInfo()
		testutil.AssertNoError(t, errdb2, fmt.Sprintf("Error when trying to retrieve database information"))
		testutil.AssertEquals(t, dbResp2.DbName, env.couchDatabaseName)

		txMgr2.Shutdown()

	}

}
Пример #6
0
func init() {

	//call a helper method to load the core.yaml
	testutil.SetupCoreYAMLConfig("./../../../../../peer")

	// Initialization will get a handle to the ledger at the specified path
	// Note, if subledgers are supported in the future,
	// the various ledgers could be created/managed at this level
	os.RemoveAll(ledgerPath)
	ledgerConf := kvledger.NewConf(ledgerPath, 0)
	var err error
	finalLedger, err = kvledger.NewKVLedger(ledgerConf)
	if err != nil {
		panic(fmt.Errorf("Error in NewKVLedger(): %s", err))
	}
	app = example.ConstructAppInstance(finalLedger)
	committer = example.ConstructCommitter(finalLedger)
	consenter = example.ConstructConsenter()
}
Пример #7
0
// Note that the couchdb_test.go tests couchdb functions already.  This test just tests that a
// CouchDB history database is auto-created upon creating a new history manager
func TestHistoryDatabaseAutoCreate(t *testing.T) {

	//call a helper method to load the core.yaml
	testutil.SetupCoreYAMLConfig("./../../../peer")
	logger.Debugf("===HISTORYDB=== TestHistoryDatabaseAutoCreate IsCouchDBEnabled()value: %v , IsHistoryDBEnabled()value: %v\n",
		ledgerconfig.IsCouchDBEnabled(), ledgerconfig.IsHistoryDBEnabled())

	if ledgerconfig.IsHistoryDBEnabled() == true {

		env := newTestEnvHistoryCouchDB(t, "history-test")
		env.cleanup()       //cleanup at the beginning to ensure the database doesn't exist already
		defer env.cleanup() //and cleanup at the end

		logger.Debugf("===HISTORYDB=== env.couchDBAddress: %v , env.couchDatabaseName: %v env.couchUsername: %v env.couchPassword: %v\n",
			env.couchDBAddress, env.couchDatabaseName, env.couchUsername, env.couchPassword)

		histMgr := NewCouchDBHistMgr(
			env.couchDBAddress,    //couchDB Address
			env.couchDatabaseName, //couchDB db name
			env.couchUsername,     //enter couchDB id
			env.couchPassword)     //enter couchDB pw

		//NewCouchDBhistMgr should have automatically created the database, let's make sure it has been created
		//Retrieve the info for the new database and make sure the name matches
		dbResp, _, errdb := histMgr.couchDB.GetDatabaseInfo()
		testutil.AssertNoError(t, errdb, fmt.Sprintf("Error when trying to retrieve database information"))
		testutil.AssertEquals(t, dbResp.DbName, env.couchDatabaseName)

		//Call NewCouchDBhistMgr again, this time the database will already exist from last time
		histMgr2 := NewCouchDBHistMgr(
			env.couchDBAddress,    //couchDB Address
			env.couchDatabaseName, //couchDB db name
			env.couchUsername,     //enter couchDB id
			env.couchPassword)     //enter couchDB pw

		//Retrieve the info for the database again, and make sure the name still matches
		dbResp2, _, errdb2 := histMgr2.couchDB.GetDatabaseInfo()
		testutil.AssertNoError(t, errdb2, fmt.Sprintf("Error when trying to retrieve database information"))
		testutil.AssertEquals(t, dbResp2.DbName, env.couchDatabaseName)

	}
}
Пример #8
0
func TestDatabaseQuery(t *testing.T) {

	//call a helper method to load the core.yaml
	testutil.SetupCoreYAMLConfig("./../../../../../peer")

	//Only run the tests if CouchDB is explitily enabled in the code,
	//otherwise CouchDB may not be installed and all the tests would fail
	//TODO replace this with external config property rather than config within the code
	if ledgerconfig.IsCouchDBEnabled() == true {

		env := newTestEnv(t)
		//env.Cleanup() //cleanup at the beginning to ensure the database doesn't exist already
		//defer env.Cleanup() //and cleanup at the end

		txMgr := NewCouchDBTxMgr(env.conf,
			env.couchDBAddress,    //couchDB Address
			env.couchDatabaseName, //couchDB db name
			env.couchUsername,     //enter couchDB id
			env.couchPassword)     //enter couchDB pw

		type Asset struct {
			ID        string `json:"_id"`
			Rev       string `json:"_rev"`
			AssetName string `json:"asset_name"`
			Color     string `json:"color"`
			Size      string `json:"size"`
			Owner     string `json:"owner"`
		}

		s1, _ := txMgr.NewTxSimulator()

		s1.SetState("ns1", "key1", []byte("value1"))
		s1.SetState("ns1", "key2", []byte("value2"))
		s1.SetState("ns1", "key3", []byte("value3"))
		s1.SetState("ns1", "key4", []byte("value4"))
		s1.SetState("ns1", "key5", []byte("value5"))
		s1.SetState("ns1", "key6", []byte("value6"))
		s1.SetState("ns1", "key7", []byte("value7"))
		s1.SetState("ns1", "key8", []byte("value8"))

		s1.SetState("ns1", "key9", []byte(`{"asset_name":"marble1","color":"red","size":"25","owner":"jerry"}`))
		s1.SetState("ns1", "key10", []byte(`{"asset_name":"marble2","color":"blue","size":"10","owner":"bob"}`))
		s1.SetState("ns1", "key11", []byte(`{"asset_name":"marble3","color":"blue","size":"35","owner":"jerry"}`))
		s1.SetState("ns1", "key12", []byte(`{"asset_name":"marble4","color":"green","size":"15","owner":"bob"}`))
		s1.SetState("ns1", "key13", []byte(`{"asset_name":"marble5","color":"red","size":"35","owner":"jerry"}`))
		s1.SetState("ns1", "key14", []byte(`{"asset_name":"marble6","color":"blue","size":"25","owner":"bob"}`))

		s1.Done()

		// validate and commit RWset
		txRWSet := s1.(*CouchDBTxSimulator).getTxReadWriteSet()
		isValid, err := txMgr.validateTx(txRWSet)
		testutil.AssertNoError(t, err, fmt.Sprintf("Error in validateTx(): %s", err))
		testutil.AssertSame(t, isValid, true)
		txMgr.addWriteSetToBatch(txRWSet, version.NewHeight(1, 1))
		err = txMgr.Commit()
		testutil.AssertNoError(t, err, fmt.Sprintf("Error while calling commit(): %s", err))

		queryExecuter, _ := txMgr.NewQueryExecutor()
		queryString := "{\"selector\":{\"owner\": {\"$eq\": \"bob\"}},\"limit\": 10,\"skip\": 0}"

		itr, _ := queryExecuter.ExecuteQuery(queryString)

		counter := 0
		for {
			queryRecord, _ := itr.Next()
			if queryRecord == nil {
				break
			}

			//Unmarshal the document to Asset structure
			assetResp := &Asset{}
			json.Unmarshal(queryRecord.(*ledger.QueryRecord).Record, &assetResp)

			//Verify the owner retrieved matches
			testutil.AssertEquals(t, assetResp.Owner, "bob")

			counter++

		}

		//Ensure the query returns 3 documents
		testutil.AssertEquals(t, counter, 3)

		txMgr.Shutdown()

	}

}
Пример #9
0
func setUpCoreYAMLConfig() {
	//call a helper method to load the core.yaml
	testutil.SetupCoreYAMLConfig("./../../../peer")
}
Пример #10
0
func TestLedgerWithCouchDbEnabledWithBinaryAndJSONData(t *testing.T) {

	//call a helper method to load the core.yaml
	testutil.SetupCoreYAMLConfig("./../../../peer")

	logger.Debugf("TestLedgerWithCouchDbEnabledWithBinaryAndJSONData  IsCouchDBEnabled()value: %v , IsHistoryDBEnabled()value: %v\n",
		ledgerconfig.IsCouchDBEnabled(), ledgerconfig.IsHistoryDBEnabled())

	env := newTestEnv(t)
	defer env.cleanup()
	ledger, _ := NewKVLedger(env.conf)
	defer ledger.Close()

	//testNs := "ns1"

	bcInfo, _ := ledger.GetBlockchainInfo()
	testutil.AssertEquals(t, bcInfo, &pb.BlockchainInfo{
		Height: 0, CurrentBlockHash: nil, PreviousBlockHash: nil})

	simulator, _ := ledger.NewTxSimulator()
	simulator.SetState("ns1", "key4", []byte("value1"))
	simulator.SetState("ns1", "key5", []byte("value2"))
	simulator.SetState("ns1", "key6", []byte("{\"shipmentID\":\"161003PKC7300\",\"customsInvoice\":{\"methodOfTransport\":\"GROUND\",\"invoiceNumber\":\"00091622\"},\"weightUnitOfMeasure\":\"KGM\",\"volumeUnitOfMeasure\": \"CO\",\"dimensionUnitOfMeasure\":\"CM\",\"currency\":\"USD\"}"))
	simulator.SetState("ns1", "key7", []byte("{\"shipmentID\":\"161003PKC7600\",\"customsInvoice\":{\"methodOfTransport\":\"AIR MAYBE\",\"invoiceNumber\":\"00091624\"},\"weightUnitOfMeasure\":\"KGM\",\"volumeUnitOfMeasure\": \"CO\",\"dimensionUnitOfMeasure\":\"CM\",\"currency\":\"USD\"}"))
	simulator.Done()
	simRes, _ := simulator.GetTxSimulationResults()
	bg := testutil.NewBlockGenerator(t)
	block1 := bg.NextBlock([][]byte{simRes}, false)

	ledger.Commit(block1)

	bcInfo, _ = ledger.GetBlockchainInfo()
	block1Hash := block1.Header.Hash()
	testutil.AssertEquals(t, bcInfo, &pb.BlockchainInfo{
		Height: 1, CurrentBlockHash: block1Hash, PreviousBlockHash: []byte{}})

	//Note key 4 and 6 are updates but key 7 is new.  I.E. should see history for key 4 and 6 if history is enabled
	simulationResults := [][]byte{}
	simulator, _ = ledger.NewTxSimulator()
	simulator.SetState("ns1", "key4", []byte("value3"))
	simulator.SetState("ns1", "key5", []byte("{\"shipmentID\":\"161003PKC7500\",\"customsInvoice\":{\"methodOfTransport\":\"AIR FREIGHT\",\"invoiceNumber\":\"00091623\"},\"weightUnitOfMeasure\":\"KGM\",\"volumeUnitOfMeasure\": \"CO\",\"dimensionUnitOfMeasure\":\"CM\",\"currency\":\"USD\"}"))
	simulator.SetState("ns1", "key6", []byte("value4"))
	simulator.SetState("ns1", "key7", []byte("{\"shipmentID\":\"161003PKC7600\",\"customsInvoice\":{\"methodOfTransport\":\"GROUND\",\"invoiceNumber\":\"00091624\"},\"weightUnitOfMeasure\":\"KGM\",\"volumeUnitOfMeasure\": \"CO\",\"dimensionUnitOfMeasure\":\"CM\",\"currency\":\"USD\"}"))
	simulator.SetState("ns1", "key8", []byte("{\"shipmentID\":\"161003PKC7700\",\"customsInvoice\":{\"methodOfTransport\":\"SHIP\",\"invoiceNumber\":\"00091625\"},\"weightUnitOfMeasure\":\"KGM\",\"volumeUnitOfMeasure\": \"CO\",\"dimensionUnitOfMeasure\":\"CM\",\"currency\":\"USD\"}"))
	simulator.Done()
	simRes, _ = simulator.GetTxSimulationResults()
	simulationResults = append(simulationResults, simRes)
	//add a 2nd transaction
	simulator2, _ := ledger.NewTxSimulator()
	simulator2.SetState("ns1", "key7", []byte("{\"shipmentID\":\"161003PKC7600\",\"customsInvoice\":{\"methodOfTransport\":\"TRAIN\",\"invoiceNumber\":\"00091624\"},\"weightUnitOfMeasure\":\"KGM\",\"volumeUnitOfMeasure\": \"CO\",\"dimensionUnitOfMeasure\":\"CM\",\"currency\":\"USD\"}"))
	simulator2.SetState("ns1", "key9", []byte("value5"))
	simulator2.SetState("ns1", "key10", []byte("{\"shipmentID\":\"261003PKC8000\",\"customsInvoice\":{\"methodOfTransport\":\"DONKEY\",\"invoiceNumber\":\"00091626\"},\"weightUnitOfMeasure\":\"KGM\",\"volumeUnitOfMeasure\": \"CO\",\"dimensionUnitOfMeasure\":\"CM\",\"currency\":\"USD\"}"))
	simulator2.Done()
	simRes2, _ := simulator2.GetTxSimulationResults()
	simulationResults = append(simulationResults, simRes2)

	block2 := bg.NextBlock(simulationResults, false)
	ledger.Commit(block2)

	bcInfo, _ = ledger.GetBlockchainInfo()
	block2Hash := block2.Header.Hash()
	testutil.AssertEquals(t, bcInfo, &pb.BlockchainInfo{
		Height: 2, CurrentBlockHash: block2Hash, PreviousBlockHash: block1.Header.Hash()})

	b1, _ := ledger.GetBlockByHash(block1Hash)
	testutil.AssertEquals(t, b1, block1)

	b2, _ := ledger.GetBlockByHash(block2Hash)
	testutil.AssertEquals(t, b2, block2)

	b1, _ = ledger.GetBlockByNumber(1)
	testutil.AssertEquals(t, b1, block1)

	b2, _ = ledger.GetBlockByNumber(2)
	testutil.AssertEquals(t, b2, block2)

	//TODO move this test to history.
	if ledgerconfig.IsHistoryDBEnabled() == true {
		qhistory, err := ledger.NewHistoryQueryExecutor()
		testutil.AssertNoError(t, err, fmt.Sprintf("Error when trying to retrieve history database executor"))

		itr, err2 := qhistory.GetTransactionsForKey("ns1", "key7", true, false)
		testutil.AssertNoError(t, err2, fmt.Sprintf("Error when trying to retrieve history database executor"))

		count := 0
		for {
			kmod, _ := itr.Next()
			if kmod == nil {
				break
			}
			//TODO TEST CONTENT - need to point to ledger import and not the KVledger
			//TODO MOVE TEST TO HISTORY
			//bt := kmod.(*ledger.KeyModification).TxID
			//v := kmod.(*ledger.KeyModification).Value
			//t.Logf("Retrieved for ns=%s, key=key7  : k=%s, v=%s at count=%d start=%s end=%s", testNs, bt, v, count)
			count++
		}
		testutil.AssertEquals(t, count, 3)
	}
}