Esempio n. 1
0
func TestDBBadJSON(t *testing.T) {

	if ledgerconfig.IsCouchDBEnabled() == true {

		cleanup()
		defer cleanup()

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

		//create a new database
		_, errdb := db.CreateDatabaseIfNotExist()
		testutil.AssertNoError(t, errdb, fmt.Sprintf("Error when trying to create database"))

		//Retrieve the info for the new database and make sure the name matches
		dbResp, _, errdb := db.GetDatabaseInfo()
		testutil.AssertNoError(t, errdb, fmt.Sprintf("Error when trying to retrieve database information"))
		testutil.AssertEquals(t, dbResp.DbName, database)

		badJSON := []byte(`{"asset_name"}`)

		//Save the test document
		_, saveerr := db.SaveDoc("1", "", badJSON, nil)
		testutil.AssertError(t, saveerr, fmt.Sprintf("Error should have been thrown for a bad JSON"))

	}

}
Esempio n. 2
0
//TestSavepoint tests the recordSavepoint and GetBlockNumfromSavepoint methods for recording and reading a savepoint document
func TestSavepoint(t *testing.T) {

	//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)

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

		// record savepoint
		txMgr.blockNum = 5
		err := txMgr.recordSavepoint()
		testutil.AssertNoError(t, err, fmt.Sprintf("Error when saving recordpoint data"))

		// read the savepoint
		blockNum, err := txMgr.GetBlockNumFromSavepoint()
		testutil.AssertNoError(t, err, fmt.Sprintf("Error when saving recordpoint data"))
		testutil.AssertEquals(t, txMgr.blockNum, blockNum)

		txMgr.Shutdown()
	}
}
Esempio n. 3
0
// NewKVLedger constructs new `KVLedger`
func NewKVLedger(conf *Conf) (*KVLedger, error) {

	logger.Debugf("Creating KVLedger using config: ", conf)

	attrsToIndex := []blkstorage.IndexableAttr{
		blkstorage.IndexableAttrBlockHash,
		blkstorage.IndexableAttrBlockNum,
		blkstorage.IndexableAttrTxID,
		blkstorage.IndexableAttrBlockNumTranNum,
	}
	indexConfig := &blkstorage.IndexConfig{AttrsToIndex: attrsToIndex}
	blockStorageConf := fsblkstorage.NewConf(conf.blockStorageDir, conf.maxBlockfileSize)
	blockStore := fsblkstorage.NewFsBlockStore(blockStorageConf, indexConfig)

	//State and History database managers
	var txmgmt txmgr.TxMgr
	var historymgmt history.HistMgr

	if ledgerconfig.IsCouchDBEnabled() == true {
		//By default we can talk to CouchDB with empty id and pw (""), or you can add your own id and password to talk to a secured CouchDB
		logger.Debugf("===COUCHDB=== NewKVLedger() Using CouchDB instead of RocksDB...hardcoding and passing connection config for now")

		couchDBDef := ledgerconfig.GetCouchDBDefinition()

		//create new transaction manager based on couchDB
		txmgmt = couchdbtxmgmt.NewCouchDBTxMgr(&couchdbtxmgmt.Conf{DBPath: conf.txMgrDBPath},
			couchDBDef.URL,      //couchDB connection URL
			"system",            //couchDB db name matches ledger name, TODO for now use system ledger, eventually allow passing in subledger name
			couchDBDef.Username, //enter couchDB id here
			couchDBDef.Password) //enter couchDB pw here
	} else {
		// Fall back to using goleveldb lockbased transaction manager
		db := stateleveldb.NewVersionedDBProvider(&stateleveldb.Conf{DBPath: conf.txMgrDBPath}).GetDBHandle("Default")
		txmgmt = lockbasedtxmgr.NewLockBasedTxMgr(db)
	}

	if ledgerconfig.IsHistoryDBEnabled() == true {
		logger.Debugf("===HISTORYDB=== NewKVLedger() Using CouchDB for transaction history database")

		couchDBDef := ledgerconfig.GetCouchDBDefinition()

		historymgmt = history.NewCouchDBHistMgr(
			couchDBDef.URL,      //couchDB connection URL
			"system_history",    //couchDB db name matches ledger name, TODO for now use system_history ledger, eventually allow passing in subledger name
			couchDBDef.Username, //enter couchDB id here
			couchDBDef.Password) //enter couchDB pw here
	}

	l := &KVLedger{blockStore, txmgmt, historymgmt}

	if err := recoverStateDB(l); err != nil {
		panic(fmt.Errorf(`Error during state DB recovery:%s`, err))
	}

	return l, nil
}
Esempio n. 4
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

	}
}
Esempio n. 5
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"))
	}

}
Esempio n. 6
0
func TestDBTestDropDatabaseBadConnection(t *testing.T) {

	if ledgerconfig.IsCouchDBEnabled() == true {

		cleanup()
		defer cleanup()

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

		//Attempt to drop the database without creating first
		_, errdbdrop := db.DropDatabase()
		testutil.AssertError(t, errdbdrop, fmt.Sprintf("Error should have been reported for attempting to drop a database before creation"))
	}

}
Esempio n. 7
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()

	}

}
Esempio n. 8
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)

	}
}
Esempio n. 9
0
func TestDBCreateSaveWithoutRevision(t *testing.T) {

	if ledgerconfig.IsCouchDBEnabled() == true {

		cleanup()
		defer cleanup()

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

		//create a new database
		_, errdb := db.CreateDatabaseIfNotExist()
		testutil.AssertNoError(t, errdb, fmt.Sprintf("Error when trying to create database"))

		//Save the test document
		_, saveerr := db.SaveDoc("2", "", assetJSON, nil)
		testutil.AssertNoError(t, saveerr, fmt.Sprintf("Error when trying to save a document"))

	}
}
Esempio n. 10
0
func TestDBTestExistingDB(t *testing.T) {

	if ledgerconfig.IsCouchDBEnabled() == true {

		cleanup()
		defer cleanup()

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

		//create a new database
		_, errdb := db.CreateDatabaseIfNotExist()
		testutil.AssertNoError(t, errdb, fmt.Sprintf("Error when attempting to create a database"))

		//run the create if not exist again.  should not return an error
		_, errdb = db.CreateDatabaseIfNotExist()
		testutil.AssertNoError(t, errdb, fmt.Sprintf("Error when attempting to create a database"))

	}
}
Esempio n. 11
0
func TestDBRetrieveNonExistingDocument(t *testing.T) {

	if ledgerconfig.IsCouchDBEnabled() == true {

		cleanup()
		defer cleanup()

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

		//create a new database
		_, errdb := db.CreateDatabaseIfNotExist()
		testutil.AssertNoError(t, errdb, fmt.Sprintf("Error when attempting to create a database"))

		//Attempt to retrieve the updated test document
		_, _, geterr2 := db.ReadDoc("2")
		testutil.AssertError(t, geterr2, fmt.Sprintf("Error should have been thrown while attempting to retrieve a nonexisting document"))

	}
}
Esempio n. 12
0
func TestDBBadConnection(t *testing.T) {

	if ledgerconfig.IsCouchDBEnabled() == true {

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

		//create a new database
		_, errdb := db.CreateDatabaseIfNotExist()
		testutil.AssertError(t, errdb, fmt.Sprintf("Error should have been thrown while creating a database with an invalid connecion"))

		//Save the test document
		_, saveerr := db.SaveDoc("3", "", assetJSON, nil)
		testutil.AssertError(t, saveerr, fmt.Sprintf("Error should have been thrown while saving a document with an invalid connecion"))

		//Retrieve the updated test document
		_, _, geterr := db.ReadDoc("3")
		testutil.AssertError(t, geterr, fmt.Sprintf("Error should have been thrown while retrieving a document with an invalid connecion"))

	}
}
Esempio n. 13
0
func TestDBSaveAttachment(t *testing.T) {

	if ledgerconfig.IsCouchDBEnabled() == true {

		cleanup()
		defer cleanup()
		byteText := []byte(`This is a test document.  This is only a test`)

		attachment := Attachment{}
		attachment.AttachmentBytes = byteText
		attachment.ContentType = "text/plain"
		attachment.Name = "valueBytes"

		attachments := []Attachment{}
		attachments = append(attachments, attachment)

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

		//create a new database
		_, errdb := db.CreateDatabaseIfNotExist()
		testutil.AssertNoError(t, errdb, fmt.Sprintf("Error when trying to create database"))

		//Save the test document
		_, saveerr := db.SaveDoc("10", "", nil, attachments)
		testutil.AssertNoError(t, saveerr, fmt.Sprintf("Error when trying to save a document"))

		//Attempt to retrieve the updated test document with attachments
		returnDoc, _, geterr2 := db.ReadDoc("10")
		testutil.AssertNoError(t, geterr2, fmt.Sprintf("Error when trying to retrieve a document with attachment"))

		//Test to see that the result from CouchDB matches the initial text
		testutil.AssertEquals(t, string(returnDoc), string(byteText))

	}
}
Esempio n. 14
0
func TestDBReadDocumentRange(t *testing.T) {

	if ledgerconfig.IsCouchDBEnabled() == true {

		cleanup()
		defer cleanup()

		var assetJSON1 = []byte(`{"asset_name":"marble1","color":"blue","size":"35","owner":"jerry"}`)
		var assetJSON2 = []byte(`{"asset_name":"marble2","color":"green","size":"25","owner":"jerry"}`)
		var assetJSON3 = []byte(`{"asset_name":"marble3","color":"green","size":"15","owner":"bob"}`)
		var assetJSON4 = []byte(`{"asset_name":"marble4","color":"red","size":"25","owner":"bob"}`)

		var textString1 = []byte("This is a test. iteration 1")
		var textString2 = []byte("This is a test. iteration 2")
		var textString3 = []byte("This is a test. iteration 3")
		var textString4 = []byte("This is a test. iteration 4")

		attachment1 := Attachment{}
		attachment1.AttachmentBytes = textString1
		attachment1.ContentType = "text/plain"
		attachment1.Name = "valueBytes"

		attachments1 := []Attachment{}
		attachments1 = append(attachments1, attachment1)

		attachment2 := Attachment{}
		attachment2.AttachmentBytes = textString2
		attachment2.ContentType = "text/plain"
		attachment2.Name = "valueBytes"

		attachments2 := []Attachment{}
		attachments2 = append(attachments2, attachment2)

		attachment3 := Attachment{}
		attachment3.AttachmentBytes = textString3
		attachment3.ContentType = "text/plain"
		attachment3.Name = "valueBytes"

		attachments3 := []Attachment{}
		attachments3 = append(attachments3, attachment3)

		attachment4 := Attachment{}
		attachment4.AttachmentBytes = textString4
		attachment4.ContentType = "text/plain"
		attachment4.Name = "valueBytes"

		attachments4 := []Attachment{}
		attachments4 = append(attachments4, attachment4)

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

		//create a new database
		_, errdb := db.CreateDatabaseIfNotExist()
		testutil.AssertNoError(t, errdb, fmt.Sprintf("Error when trying to create database"))

		//Retrieve the info for the new database and make sure the name matches
		dbResp, _, errdb := db.GetDatabaseInfo()
		testutil.AssertNoError(t, errdb, fmt.Sprintf("Error when trying to retrieve database information"))
		testutil.AssertEquals(t, dbResp.DbName, database)

		//Save the test document
		_, saveerr1 := db.SaveDoc("1", "", assetJSON1, nil)
		testutil.AssertNoError(t, saveerr1, fmt.Sprintf("Error when trying to save a document"))

		//Save the test document
		_, saveerr2 := db.SaveDoc("2", "", assetJSON2, nil)
		testutil.AssertNoError(t, saveerr2, fmt.Sprintf("Error when trying to save a document"))

		//Save the test document
		_, saveerr3 := db.SaveDoc("3", "", assetJSON3, nil)
		testutil.AssertNoError(t, saveerr3, fmt.Sprintf("Error when trying to save a document"))

		//Save the test document
		_, saveerr4 := db.SaveDoc("4", "", assetJSON4, nil)
		testutil.AssertNoError(t, saveerr4, fmt.Sprintf("Error when trying to save a document"))

		//Save the test document
		_, saveerr5 := db.SaveDoc("11", "", nil, attachments1)
		testutil.AssertNoError(t, saveerr5, fmt.Sprintf("Error when trying to save a document"))

		//Save the test document
		_, saveerr6 := db.SaveDoc("12", "", nil, attachments2)
		testutil.AssertNoError(t, saveerr6, fmt.Sprintf("Error when trying to save a document"))

		//Save the test document
		_, saveerr7 := db.SaveDoc("13", "", nil, attachments3)
		testutil.AssertNoError(t, saveerr7, fmt.Sprintf("Error when trying to save a document"))

		//Save the test document
		_, saveerr8 := db.SaveDoc("5", "", nil, attachments4)
		testutil.AssertNoError(t, saveerr8, fmt.Sprintf("Error when trying to save a document"))

		queryResp, _ := db.ReadDocRange("1", "12", 1000, 0)

		//Ensure the query returns 3 documents
		testutil.AssertEquals(t, len(*queryResp), 3)

		for _, item := range *queryResp {

			if item.ID == "1" {

				//Unmarshal the document to Asset structure
				assetResp := &Asset{}
				json.Unmarshal(item.Value, &assetResp)

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

				//Verify the size retrieved matches
				testutil.AssertEquals(t, assetResp.Size, "35")
			}

			if item.ID == "11" {
				testutil.AssertEquals(t, string(item.Value), string(textString1))
			}

			if item.ID == "12" {
				testutil.AssertEquals(t, string(item.Value), string(textString2))
			}

		}

		queryString := "{\"selector\":{\"owner\": {\"$eq\": \"bob\"}},\"fields\": [\"_id\", \"_rev\", \"owner\", \"asset_name\", \"color\", \"size\"],\"limit\": 10,\"skip\": 0}"

		queryResult, _ := db.QueryDocuments(queryString, 1000, 0)

		//Ensure the query returns 2 documents
		testutil.AssertEquals(t, len(*queryResult), 2)

		for _, item := range *queryResult {

			//Unmarshal the document to Asset structure
			assetResp := &Asset{}
			json.Unmarshal(item.Value, &assetResp)

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

		}

	}

}
Esempio n. 15
0
func TestDBCreateDatabaseAndPersist(t *testing.T) {

	if ledgerconfig.IsCouchDBEnabled() == true {

		cleanup()
		defer cleanup()

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

		//create a new database
		_, errdb := db.CreateDatabaseIfNotExist()
		testutil.AssertNoError(t, errdb, fmt.Sprintf("Error when trying to create database"))

		//Retrieve the info for the new database and make sure the name matches
		dbResp, _, errdb := db.GetDatabaseInfo()
		testutil.AssertNoError(t, errdb, fmt.Sprintf("Error when trying to retrieve database information"))
		testutil.AssertEquals(t, dbResp.DbName, database)

		//Save the test document
		_, saveerr := db.SaveDoc("1", "", assetJSON, nil)
		testutil.AssertNoError(t, saveerr, fmt.Sprintf("Error when trying to save a document"))

		//Retrieve the test document
		dbGetResp, _, geterr := db.ReadDoc("1")
		testutil.AssertNoError(t, geterr, fmt.Sprintf("Error when trying to retrieve a document"))

		//Unmarshal the document to Asset structure
		assetResp := &Asset{}
		json.Unmarshal(dbGetResp, &assetResp)

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

		//Change owner to bob
		assetResp.Owner = "bob"

		//create a byte array of the JSON
		assetDocUpdated, _ := json.Marshal(assetResp)

		//Save the updated test document
		_, saveerr = db.SaveDoc("1", "", assetDocUpdated, nil)
		testutil.AssertNoError(t, saveerr, fmt.Sprintf("Error when trying to save the updated document"))

		//Retrieve the updated test document
		dbGetResp, _, geterr = db.ReadDoc("1")
		testutil.AssertNoError(t, geterr, fmt.Sprintf("Error when trying to retrieve a document"))

		//Unmarshal the document to Asset structure
		assetResp = &Asset{}
		json.Unmarshal(dbGetResp, &assetResp)

		//Assert that the update was saved and retrieved
		testutil.AssertEquals(t, assetResp.Owner, "bob")

		//Drop the database
		_, errdbdrop := db.DropDatabase()
		testutil.AssertNoError(t, errdbdrop, fmt.Sprintf("Error dropping database"))

		//Retrieve the info for the new database and make sure the name matches
		_, _, errdbinfo := db.GetDatabaseInfo()
		testutil.AssertError(t, errdbinfo, fmt.Sprintf("Error should have been thrown for missing database"))

	}

}
Esempio n. 16
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()

	}

}
Esempio n. 17
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)
	}
}