From e579007fcf8e1dc40ee28530c1a935f771bce4d1 Mon Sep 17 00:00:00 2001 From: senthil Date: Fri, 19 Jun 2020 22:00:39 +0530 Subject: [PATCH] statecouchdb pkg -- consistently use testify/require Signed-off-by: senthil --- .../statecouchdb/commit_handling_test.go | 78 +-- .../statedb/statecouchdb/couchdb_test.go | 487 +++++++++--------- .../statedb/statecouchdb/couchdbutil_test.go | 76 +-- .../statecouchdb/dbvalue_encoding_test.go | 9 +- .../statedb/statecouchdb/redolog_test.go | 60 +-- .../statedb/statecouchdb/statecouchdb_test.go | 115 ++--- .../statecouchdb/version_cache_test.go | 18 +- 7 files changed, 420 insertions(+), 423 deletions(-) diff --git a/core/ledger/kvledger/txmgmt/statedb/statecouchdb/commit_handling_test.go b/core/ledger/kvledger/txmgmt/statedb/statecouchdb/commit_handling_test.go index 0f6e70ca3a3..b30377fa628 100644 --- a/core/ledger/kvledger/txmgmt/statedb/statecouchdb/commit_handling_test.go +++ b/core/ledger/kvledger/txmgmt/statedb/statecouchdb/commit_handling_test.go @@ -12,7 +12,7 @@ import ( "github.com/hyperledger/fabric/core/ledger/internal/version" "github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/statedb" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetRevision(t *testing.T) { @@ -20,7 +20,7 @@ func TestGetRevision(t *testing.T) { defer vdbEnv.cleanup() versionedDB, err := vdbEnv.DBProvider.GetDBHandle("test-get-revisions", nil) - assert.NoError(t, err) + require.NoError(t, err) db := versionedDB.(*VersionedDB) // initializing data in couchdb @@ -28,7 +28,7 @@ func TestGetRevision(t *testing.T) { batch.Put("ns", "key-in-db", []byte("value1"), version.NewHeight(1, 1)) batch.Put("ns", "key-in-both-db-cache", []byte("value2"), version.NewHeight(1, 2)) savePoint := version.NewHeight(1, 2) - assert.NoError(t, db.ApplyUpdates(batch, savePoint)) + require.NoError(t, db.ApplyUpdates(batch, savePoint)) // load revision cache with couchDB revision number. keys := []*statedb.CompositeKey{ @@ -68,16 +68,16 @@ func TestGetRevision(t *testing.T) { } revisionsMap, err := db.getRevisions("ns", nsUpdates) - assert.NoError(t, err) - assert.Equal(t, "revision-cache-number", revisionsMap["key-in-cache"]) - assert.NotEqual(t, "", revisionsMap["key-in-db"]) - assert.Equal(t, "revision-db-number", revisionsMap["key-in-both-db-cache"]) - assert.Equal(t, "", revisionsMap["bad-key"]) + require.NoError(t, err) + require.Equal(t, "revision-cache-number", revisionsMap["key-in-cache"]) + require.NotEqual(t, "", revisionsMap["key-in-db"]) + require.Equal(t, "revision-db-number", revisionsMap["key-in-both-db-cache"]) + require.Equal(t, "", revisionsMap["bad-key"]) // Get revisions of non-existing nameSpace. revisionsMap, err = db.getRevisions("bad-namespace", nsUpdates) - assert.NoError(t, err) - assert.Equal(t, "", revisionsMap["key-in-db"]) + require.NoError(t, err) + require.Equal(t, "", revisionsMap["key-in-db"]) } @@ -86,7 +86,7 @@ func TestBuildCommittersForNs(t *testing.T) { defer vdbEnv.cleanup() versionedDB, err := vdbEnv.DBProvider.GetDBHandle("test-build-committers-for-ns", nil) - assert.NoError(t, err) + require.NoError(t, err) db := versionedDB.(*VersionedDB) nsUpdates := map[string]*statedb.VersionedValue{ @@ -94,7 +94,7 @@ func TestBuildCommittersForNs(t *testing.T) { } _, err = db.buildCommittersForNs("ns", nsUpdates) - assert.EqualError(t, err, "nil version not supported") + require.EqualError(t, err, "nil version not supported") nsUpdates = make(map[string]*statedb.VersionedValue) // populate updates with maxBatchSize + 1. @@ -108,10 +108,10 @@ func TestBuildCommittersForNs(t *testing.T) { } committers, err := db.buildCommittersForNs("ns", nsUpdates) - assert.NoError(t, err) - assert.Equal(t, 2, len(committers)) - assert.Equal(t, "ns", committers[0].namespace) - assert.Equal(t, "ns", committers[1].namespace) + require.NoError(t, err) + require.Equal(t, 2, len(committers)) + require.Equal(t, "ns", committers[0].namespace) + require.Equal(t, "ns", committers[1].namespace) } @@ -120,7 +120,7 @@ func TestBuildCommitters(t *testing.T) { defer vdbEnv.cleanup() versionedDB, err := vdbEnv.DBProvider.GetDBHandle("test-build-committers", nil) - assert.NoError(t, err) + require.NoError(t, err) db := versionedDB.(*VersionedDB) dummyHeight := version.NewHeight(1, 1) @@ -135,17 +135,17 @@ func TestBuildCommitters(t *testing.T) { } committer, err := db.buildCommitters(batch) - assert.NoError(t, err) - assert.Equal(t, 3, len(committer)) + require.NoError(t, err) + require.Equal(t, 3, len(committer)) for _, commit := range committer { - assert.True(t, namespaceSet[commit.namespace]) + require.True(t, namespaceSet[commit.namespace]) } badBatch := statedb.NewUpdateBatch() badBatch.Put("bad-ns", "bad-key", []byte("bad-value"), nil) _, err = db.buildCommitters(badBatch) - assert.EqualError(t, err, "nil version not supported") + require.EqualError(t, err, "nil version not supported") } func TestExecuteCommitter(t *testing.T) { @@ -153,23 +153,23 @@ func TestExecuteCommitter(t *testing.T) { defer vdbEnv.cleanup() versionedDB, err := vdbEnv.DBProvider.GetDBHandle("test-execute-committer", nil) - assert.NoError(t, err) + require.NoError(t, err) db := versionedDB.(*VersionedDB) committerDB, err := db.getNamespaceDBHandle("ns") - assert.NoError(t, err) + require.NoError(t, err) couchDocKey1, err := keyValToCouchDoc(&keyValue{ key: "key1", revision: "", VersionedValue: &statedb.VersionedValue{Value: []byte("value1"), Metadata: nil, Version: version.NewHeight(1, 1)}, }) - assert.NoError(t, err) + require.NoError(t, err) couchDocKey2, err := keyValToCouchDoc(&keyValue{ key: "key2", revision: "", VersionedValue: &statedb.VersionedValue{Value: nil, Metadata: nil, Version: version.NewHeight(1, 1)}, }) - assert.NoError(t, err) + require.NoError(t, err) committers := []*committer{ { @@ -189,11 +189,11 @@ func TestExecuteCommitter(t *testing.T) { } err = db.executeCommitter(committers) - assert.NoError(t, err) + require.NoError(t, err) vv, err := db.GetState("ns", "key1") - assert.NoError(t, err) - assert.Equal(t, vv.Value, []byte("value1")) - assert.Equal(t, vv.Version, version.NewHeight(1, 1)) + require.NoError(t, err) + require.Equal(t, vv.Value, []byte("value1")) + require.Equal(t, vv.Version, version.NewHeight(1, 1)) committers = []*committer{ { @@ -205,7 +205,7 @@ func TestExecuteCommitter(t *testing.T) { }, } err = db.executeCommitter(committers) - assert.EqualError(t, err, "error handling CouchDB request. Error:bad_request, Status Code:400, Reason:`docs` parameter must be an array.") + require.EqualError(t, err, "error handling CouchDB request. Error:bad_request, Status Code:400, Reason:`docs` parameter must be an array.") } func TestCommitUpdates(t *testing.T) { @@ -213,7 +213,7 @@ func TestCommitUpdates(t *testing.T) { defer vdbEnv.cleanup() versionedDB, err := vdbEnv.DBProvider.GetDBHandle("test-commitupdates", nil) - assert.NoError(t, err) + require.NoError(t, err) db := versionedDB.(*VersionedDB) nsUpdates := map[string]*statedb.VersionedValue{ @@ -230,9 +230,9 @@ func TestCommitUpdates(t *testing.T) { } committerDB, err := db.getNamespaceDBHandle("ns") - assert.NoError(t, err) + require.NoError(t, err) couchDoc, err := keyValToCouchDoc(&keyValue{key: "key1", revision: "", VersionedValue: nsUpdates["key1"]}) - assert.NoError(t, err) + require.NoError(t, err) var tests = []struct { committer *committer @@ -273,14 +273,14 @@ func TestCommitUpdates(t *testing.T) { for _, test := range tests { err := test.committer.commitUpdates() if test.expectedErr == "" { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.EqualError(t, err, test.expectedErr) + require.EqualError(t, err, test.expectedErr) } } couchDoc, err = keyValToCouchDoc(&keyValue{key: "key2", revision: "", VersionedValue: nsUpdates["key2"]}) - assert.NoError(t, err) + require.NoError(t, err) committer := &committer{ db: committerDB, @@ -290,8 +290,8 @@ func TestCommitUpdates(t *testing.T) { cacheEnabled: true, } - assert.Empty(t, committer.cacheKVs["key2"].AdditionalInfo) + require.Empty(t, committer.cacheKVs["key2"].AdditionalInfo) err = committer.commitUpdates() - assert.NoError(t, err) - assert.NotEmpty(t, committer.cacheKVs["key2"].AdditionalInfo) + require.NoError(t, err) + require.NotEmpty(t, committer.cacheKVs["key2"].AdditionalInfo) } diff --git a/core/ledger/kvledger/txmgmt/statedb/statecouchdb/couchdb_test.go b/core/ledger/kvledger/txmgmt/statedb/statecouchdb/couchdb_test.go index ea545d71d29..a32d1801888 100644 --- a/core/ledger/kvledger/txmgmt/statedb/statecouchdb/couchdb_test.go +++ b/core/ledger/kvledger/txmgmt/statedb/statecouchdb/couchdb_test.go @@ -18,7 +18,6 @@ import ( "github.com/hyperledger/fabric/common/metrics/disabled" "github.com/hyperledger/fabric/core/ledger" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -60,24 +59,24 @@ func TestDBBadConnectionDef(t *testing.T) { RequestTimeout: 35 * time.Second, } _, err := createCouchInstance(config, &disabled.Provider{}) - assert.Error(t, err, "Did not receive error when trying to create database connection definition with a bad hostname") + require.Error(t, err, "Did not receive error when trying to create database connection definition with a bad hostname") } func TestEncodePathElement(t *testing.T) { encodedString := encodePathElement("testelement") - assert.Equal(t, "testelement", encodedString) + require.Equal(t, "testelement", encodedString) encodedString = encodePathElement("test element") - assert.Equal(t, "test%20element", encodedString) + require.Equal(t, "test%20element", encodedString) encodedString = encodePathElement("/test element") - assert.Equal(t, "%2Ftest%20element", encodedString) + require.Equal(t, "%2Ftest%20element", encodedString) encodedString = encodePathElement("/test element:") - assert.Equal(t, "%2Ftest%20element:", encodedString) + require.Equal(t, "%2Ftest%20element:", encodedString) encodedString = encodePathElement("/test+ element:") - assert.Equal(t, "%2Ftest%2B%20element:", encodedString) + require.Equal(t, "%2Ftest%2B%20element:", encodedString) } func TestHealthCheck(t *testing.T) { @@ -94,8 +93,8 @@ func TestHealthCheck(t *testing.T) { stats: newStats(&disabled.Provider{}), } err := badCouchDBInstance.healthCheck(context.Background()) - assert.Error(t, err, "Health check should result in an error if unable to connect to couch db") - assert.Contains(t, err.Error(), "failed to connect to couch db") + require.Error(t, err, "Health check should result in an error if unable to connect to couch db") + require.Contains(t, err.Error(), "failed to connect to couch db") //Create a good couchdb instance goodCouchDBInstance := couchInstance{ @@ -104,7 +103,7 @@ func TestHealthCheck(t *testing.T) { stats: newStats(&disabled.Provider{}), } err = goodCouchDBInstance.healthCheck(context.Background()) - assert.NoError(t, err) + require.NoError(t, err) } func TestBadCouchDBInstance(t *testing.T) { @@ -130,67 +129,67 @@ func TestBadCouchDBInstance(t *testing.T) { //Test createCouchDatabase with bad connection _, err := createCouchDatabase(&badCouchDBInstance, "baddbtest") - assert.Error(t, err, "Error should have been thrown with createCouchDatabase and invalid connection") + require.Error(t, err, "Error should have been thrown with createCouchDatabase and invalid connection") //Test createSystemDatabasesIfNotExist with bad connection err = createSystemDatabasesIfNotExist(&badCouchDBInstance) - assert.Error(t, err, "Error should have been thrown with createSystemDatabasesIfNotExist and invalid connection") + require.Error(t, err, "Error should have been thrown with createSystemDatabasesIfNotExist and invalid connection") //Test createDatabaseIfNotExist with bad connection err = badDB.createDatabaseIfNotExist() - assert.Error(t, err, "Error should have been thrown with createDatabaseIfNotExist and invalid connection") + require.Error(t, err, "Error should have been thrown with createDatabaseIfNotExist and invalid connection") //Test getDatabaseInfo with bad connection _, _, err = badDB.getDatabaseInfo() - assert.Error(t, err, "Error should have been thrown with getDatabaseInfo and invalid connection") + require.Error(t, err, "Error should have been thrown with getDatabaseInfo and invalid connection") //Test verifyCouchConfig with bad connection _, _, err = badCouchDBInstance.verifyCouchConfig() - assert.Error(t, err, "Error should have been thrown with verifyCouchConfig and invalid connection") + require.Error(t, err, "Error should have been thrown with verifyCouchConfig and invalid connection") //Test dropDatabase with bad connection _, err = badDB.dropDatabase() - assert.Error(t, err, "Error should have been thrown with dropDatabase and invalid connection") + require.Error(t, err, "Error should have been thrown with dropDatabase and invalid connection") //Test readDoc with bad connection _, _, err = badDB.readDoc("1") - assert.Error(t, err, "Error should have been thrown with readDoc and invalid connection") + require.Error(t, err, "Error should have been thrown with readDoc and invalid connection") //Test saveDoc with bad connection _, err = badDB.saveDoc("1", "1", nil) - assert.Error(t, err, "Error should have been thrown with saveDoc and invalid connection") + require.Error(t, err, "Error should have been thrown with saveDoc and invalid connection") //Test deleteDoc with bad connection err = badDB.deleteDoc("1", "1") - assert.Error(t, err, "Error should have been thrown with deleteDoc and invalid connection") + require.Error(t, err, "Error should have been thrown with deleteDoc and invalid connection") //Test readDocRange with bad connection _, _, err = badDB.readDocRange("1", "2", 1000) - assert.Error(t, err, "Error should have been thrown with readDocRange and invalid connection") + require.Error(t, err, "Error should have been thrown with readDocRange and invalid connection") //Test queryDocuments with bad connection _, _, err = badDB.queryDocuments("1") - assert.Error(t, err, "Error should have been thrown with queryDocuments and invalid connection") + require.Error(t, err, "Error should have been thrown with queryDocuments and invalid connection") //Test batchRetrieveDocumentMetadata with bad connection _, err = badDB.batchRetrieveDocumentMetadata(nil) - assert.Error(t, err, "Error should have been thrown with batchRetrieveDocumentMetadata and invalid connection") + require.Error(t, err, "Error should have been thrown with batchRetrieveDocumentMetadata and invalid connection") //Test batchUpdateDocuments with bad connection _, err = badDB.batchUpdateDocuments(nil) - assert.Error(t, err, "Error should have been thrown with batchUpdateDocuments and invalid connection") + require.Error(t, err, "Error should have been thrown with batchUpdateDocuments and invalid connection") //Test listIndex with bad connection _, err = badDB.listIndex() - assert.Error(t, err, "Error should have been thrown with listIndex and invalid connection") + require.Error(t, err, "Error should have been thrown with listIndex and invalid connection") //Test createIndex with bad connection _, err = badDB.createIndex("") - assert.Error(t, err, "Error should have been thrown with createIndex and invalid connection") + require.Error(t, err, "Error should have been thrown with createIndex and invalid connection") //Test deleteIndex with bad connection err = badDB.deleteIndex("", "") - assert.Error(t, err, "Error should have been thrown with deleteIndex and invalid connection") + require.Error(t, err, "Error should have been thrown with deleteIndex and invalid connection") } @@ -203,16 +202,16 @@ func TestDBCreateSaveWithoutRevision(t *testing.T) { //create a new instance and database object couchInstance, err := createCouchInstance(config, &disabled.Provider{}) - assert.NoError(t, err, "Error when trying to create couch instance") + require.NoError(t, err, "Error when trying to create couch instance") db := couchDatabase{couchInstance: couchInstance, dbName: database} //create a new database errdb := db.createDatabaseIfNotExist() - assert.NoError(t, errdb, "Error when trying to create database") + require.NoError(t, errdb, "Error when trying to create database") //Save the test document _, saveerr := db.saveDoc("2", "", &couchDoc{jsonValue: assetJSON, attachments: nil}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") } @@ -225,16 +224,16 @@ func TestDBCreateEnsureFullCommit(t *testing.T) { //create a new instance and database object couchInstance, err := createCouchInstance(config, &disabled.Provider{}) - assert.NoError(t, err, "Error when trying to create couch instance") + require.NoError(t, err, "Error when trying to create couch instance") db := couchDatabase{couchInstance: couchInstance, dbName: database} //create a new database errdb := db.createDatabaseIfNotExist() - assert.NoError(t, errdb, "Error when trying to create database") + require.NoError(t, errdb, "Error when trying to create database") //Save the test document _, saveerr := db.saveDoc("2", "", &couchDoc{jsonValue: assetJSON, attachments: nil}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") } func TestIsEmpty(t *testing.T) { @@ -244,7 +243,7 @@ func TestIsEmpty(t *testing.T) { defer couchDBEnv.cleanup(config) couchInstance, err := createCouchInstance(config, &disabled.Provider{}) - assert.NoError(t, err) + require.NoError(t, err) ignore := []string{"_global_changes", "_replicator", "_users", "fabric__internal"} isEmpty, err := couchInstance.isEmpty(ignore) @@ -288,30 +287,30 @@ func TestDBBadDatabaseName(t *testing.T) { defer couchDBEnv.cleanup(config) //create a new instance and database object using a valid database name mixed case couchInstance, err := createCouchInstance(config, &disabled.Provider{}) - assert.NoError(t, err, "Error when trying to create couch instance") + require.NoError(t, err, "Error when trying to create couch instance") _, dberr := createCouchDatabase(couchInstance, "testDB") - assert.Error(t, dberr, "Error should have been thrown for an invalid db name") + require.Error(t, dberr, "Error should have been thrown for an invalid db name") //create a new instance and database object using a valid database name letters and numbers couchInstance, err = createCouchInstance(config, &disabled.Provider{}) - assert.NoError(t, err, "Error when trying to create couch instance") + require.NoError(t, err, "Error when trying to create couch instance") _, dberr = createCouchDatabase(couchInstance, "test132") - assert.NoError(t, dberr, "Error when testing a valid database name") + require.NoError(t, dberr, "Error when testing a valid database name") //create a new instance and database object using a valid database name - special characters couchInstance, err = createCouchInstance(config, &disabled.Provider{}) - assert.NoError(t, err, "Error when trying to create couch instance") + require.NoError(t, err, "Error when trying to create couch instance") _, dberr = createCouchDatabase(couchInstance, "test1234~!@#$%^&*()[]{}.") - assert.Error(t, dberr, "Error should have been thrown for an invalid db name") + require.Error(t, dberr, "Error should have been thrown for an invalid db name") //create a new instance and database object using a invalid database name - too long /* couchInstance, err = createCouchInstance(config, &disabled.Provider{}) - assert.NoError(t, err, "Error when trying to create couch instance") + require.NoError(t, err, "Error when trying to create couch instance") _, dberr = createCouchDatabase(couchInstance, "a12345678901234567890123456789012345678901234"+ "56789012345678901234567890123456789012345678901234567890123456789012345678901234567890"+ "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456"+ "78901234567890123456789012345678901234567890") - assert.Error(t, dberr, "Error should have been thrown for invalid database name") + require.Error(t, dberr, "Error should have been thrown for invalid database name") } @@ -327,7 +326,7 @@ func TestDBBadConnection(t *testing.T) { RequestTimeout: 35 * time.Second, } _, err := createCouchInstance(config, &disabled.Provider{}) - assert.Error(t, err, "Error should have been thrown for a bad connection") + require.Error(t, err, "Error should have been thrown for a bad connection") } func TestBadDBCredentials(t *testing.T) { @@ -342,7 +341,7 @@ func TestBadDBCredentials(t *testing.T) { badConfig.Password = "fred" //create a new instance and database object _, err := createCouchInstance(badConfig, &disabled.Provider{}) - assert.Error(t, err, "Error should have been thrown for bad credentials") + require.Error(t, err, "Error should have been thrown for bad credentials") } func TestDBCreateDatabaseAndPersist(t *testing.T) { @@ -374,49 +373,49 @@ func testDBCreateDatabaseAndPersist(t *testing.T, config *ledger.CouchDBConfig) //create a new instance and database object couchInstance, err := createCouchInstance(config, &disabled.Provider{}) - assert.NoError(t, err, "Error when trying to create couch instance") + require.NoError(t, err, "Error when trying to create couch instance") db := couchDatabase{couchInstance: couchInstance, dbName: database} //create a new database errdb := db.createDatabaseIfNotExist() - assert.NoError(t, errdb, "Error when trying to create database") + require.NoError(t, errdb, "Error when trying to create database") //Retrieve the info for the new database and make sure the name matches dbResp, _, errdb := db.getDatabaseInfo() - assert.NoError(t, errdb, "Error when trying to retrieve database information") - assert.Equal(t, database, dbResp.DbName) + require.NoError(t, errdb, "Error when trying to retrieve database information") + require.Equal(t, database, dbResp.DbName) //Save the test document _, saveerr := db.saveDoc("idWith/slash", "", &couchDoc{jsonValue: assetJSON, attachments: nil}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") //Retrieve the test document dbGetResp, _, geterr := db.readDoc("idWith/slash") - assert.NoError(t, geterr, "Error when trying to retrieve a document") + require.NoError(t, geterr, "Error when trying to retrieve a document") //Unmarshal the document to Asset structure assetResp := &Asset{} geterr = json.Unmarshal(dbGetResp.jsonValue, &assetResp) - assert.NoError(t, geterr, "Error when trying to retrieve a document") + require.NoError(t, geterr, "Error when trying to retrieve a document") //Verify the owner retrieved matches - assert.Equal(t, "jerry", assetResp.Owner) + require.Equal(t, "jerry", assetResp.Owner) //Save the test document _, saveerr = db.saveDoc("1", "", &couchDoc{jsonValue: assetJSON, attachments: nil}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") //Retrieve the test document dbGetResp, _, geterr = db.readDoc("1") - assert.NoError(t, geterr, "Error when trying to retrieve a document") + require.NoError(t, geterr, "Error when trying to retrieve a document") //Unmarshal the document to Asset structure assetResp = &Asset{} geterr = json.Unmarshal(dbGetResp.jsonValue, &assetResp) - assert.NoError(t, geterr, "Error when trying to retrieve a document") + require.NoError(t, geterr, "Error when trying to retrieve a document") //Verify the owner retrieved matches - assert.Equal(t, "jerry", assetResp.Owner) + require.Equal(t, "jerry", assetResp.Owner) //Change owner to bob assetResp.Owner = "bob" @@ -426,18 +425,18 @@ func testDBCreateDatabaseAndPersist(t *testing.T, config *ledger.CouchDBConfig) //Save the updated test document _, saveerr = db.saveDoc("1", "", &couchDoc{jsonValue: assetDocUpdated, attachments: nil}) - assert.NoError(t, saveerr, "Error when trying to save the updated document") + require.NoError(t, saveerr, "Error when trying to save the updated document") //Retrieve the updated test document dbGetResp, _, geterr = db.readDoc("1") - assert.NoError(t, geterr, "Error when trying to retrieve a document") + require.NoError(t, geterr, "Error when trying to retrieve a document") //Unmarshal the document to Asset structure assetResp = &Asset{} json.Unmarshal(dbGetResp.jsonValue, &assetResp) //Assert that the update was saved and retrieved - assert.Equal(t, "bob", assetResp.Owner) + require.Equal(t, "bob", assetResp.Owner) testBytes2 := []byte(`test attachment 2`) @@ -450,15 +449,15 @@ func testDBCreateDatabaseAndPersist(t *testing.T, config *ledger.CouchDBConfig) //Save the test document with an attachment _, saveerr = db.saveDoc("2", "", &couchDoc{jsonValue: nil, attachments: attachments2}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") //Retrieve the test document with attachments dbGetResp, _, geterr = db.readDoc("2") - assert.NoError(t, geterr, "Error when trying to retrieve a document") + require.NoError(t, geterr, "Error when trying to retrieve a document") //verify the text from the attachment is correct testattach := dbGetResp.attachments[0].AttachmentBytes - assert.Equal(t, testBytes2, testattach) + require.Equal(t, testBytes2, testattach) testBytes3 := []byte{} @@ -471,15 +470,15 @@ func testDBCreateDatabaseAndPersist(t *testing.T, config *ledger.CouchDBConfig) //Save the test document with a zero length attachment _, saveerr = db.saveDoc("3", "", &couchDoc{jsonValue: nil, attachments: attachments3}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") //Retrieve the test document with attachments dbGetResp, _, geterr = db.readDoc("3") - assert.NoError(t, geterr, "Error when trying to retrieve a document") + require.NoError(t, geterr, "Error when trying to retrieve a document") //verify the text from the attachment is correct, zero bytes testattach = dbGetResp.attachments[0].AttachmentBytes - assert.Equal(t, testBytes3, testattach) + require.Equal(t, testBytes3, testattach) testBytes4a := []byte(`test attachment 4a`) attachment4a := &attachmentInfo{} @@ -499,20 +498,20 @@ func testDBCreateDatabaseAndPersist(t *testing.T, config *ledger.CouchDBConfig) //Save the updated test document with multiple attachments _, saveerr = db.saveDoc("4", "", &couchDoc{jsonValue: assetJSON, attachments: attachments4}) - assert.NoError(t, saveerr, "Error when trying to save the updated document") + require.NoError(t, saveerr, "Error when trying to save the updated document") //Retrieve the test document with attachments dbGetResp, _, geterr = db.readDoc("4") - assert.NoError(t, geterr, "Error when trying to retrieve a document") + require.NoError(t, geterr, "Error when trying to retrieve a document") for _, attach4 := range dbGetResp.attachments { currentName := attach4.Name if currentName == "data1" { - assert.Equal(t, testBytes4a, attach4.AttachmentBytes) + require.Equal(t, testBytes4a, attach4.AttachmentBytes) } if currentName == "data2" { - assert.Equal(t, testBytes4b, attach4.AttachmentBytes) + require.Equal(t, testBytes4b, attach4.AttachmentBytes) } } @@ -535,47 +534,47 @@ func testDBCreateDatabaseAndPersist(t *testing.T, config *ledger.CouchDBConfig) //Save the updated test document with multiple attachments and zero length attachments _, saveerr = db.saveDoc("5", "", &couchDoc{jsonValue: assetJSON, attachments: attachments5}) - assert.NoError(t, saveerr, "Error when trying to save the updated document") + require.NoError(t, saveerr, "Error when trying to save the updated document") //Retrieve the test document with attachments dbGetResp, _, geterr = db.readDoc("5") - assert.NoError(t, geterr, "Error when trying to retrieve a document") + require.NoError(t, geterr, "Error when trying to retrieve a document") for _, attach5 := range dbGetResp.attachments { currentName := attach5.Name if currentName == "data1" { - assert.Equal(t, testBytes5a, attach5.AttachmentBytes) + require.Equal(t, testBytes5a, attach5.AttachmentBytes) } if currentName == "data2" { - assert.Equal(t, testBytes5b, attach5.AttachmentBytes) + require.Equal(t, testBytes5b, attach5.AttachmentBytes) } } //Attempt to save the document with an invalid id _, saveerr = db.saveDoc(string([]byte{0xff, 0xfe, 0xfd}), "", &couchDoc{jsonValue: assetJSON, attachments: nil}) - assert.Error(t, saveerr, "Error should have been thrown when saving a document with an invalid ID") + require.Error(t, saveerr, "Error should have been thrown when saving a document with an invalid ID") //Attempt to read a document with an invalid id _, _, readerr := db.readDoc(string([]byte{0xff, 0xfe, 0xfd})) - assert.Error(t, readerr, "Error should have been thrown when reading a document with an invalid ID") + require.Error(t, readerr, "Error should have been thrown when reading a document with an invalid ID") //Drop the database _, errdbdrop := db.dropDatabase() - assert.NoError(t, errdbdrop, "Error dropping database") + require.NoError(t, errdbdrop, "Error dropping database") //Make sure an error is thrown for getting info for a missing database _, _, errdbinfo := db.getDatabaseInfo() - assert.Error(t, errdbinfo, "Error should have been thrown for missing database") + require.Error(t, errdbinfo, "Error should have been thrown for missing database") //Attempt to save a document to a deleted database _, saveerr = db.saveDoc("6", "", &couchDoc{jsonValue: assetJSON, attachments: nil}) - assert.Error(t, saveerr, "Error should have been thrown while attempting to save to a deleted database") + require.Error(t, saveerr, "Error should have been thrown while attempting to save to a deleted database") //Attempt to read from a deleted database _, _, geterr = db.readDoc("6") - assert.NoError(t, geterr, "Error should not have been thrown for a missing database, nil value is returned") + require.NoError(t, geterr, "Error should not have been thrown for a missing database, nil value is returned") } @@ -593,13 +592,13 @@ func TestDBRequestTimeout(t *testing.T) { impossibleTimeout := time.Nanosecond configCopy.RequestTimeout = impossibleTimeout _, err := createCouchInstance(&configCopy, &disabled.Provider{}) - assert.Error(t, err, "Error should have been thown while trying to create a couchdb instance with a connection timeout") + require.Error(t, err, "Error should have been thown while trying to create a couchdb instance with a connection timeout") //create a new instance and database object configCopy.MaxRetries = -1 configCopy.MaxRetriesOnStartup = 3 _, err = createCouchInstance(&configCopy, &disabled.Provider{}) - assert.Error(t, err, "Error should have been thrown while attempting to create a database") + require.Error(t, err, "Error should have been thrown while attempting to create a database") } func TestDBTimeoutConflictRetry(t *testing.T) { @@ -613,33 +612,33 @@ func TestDBTimeoutConflictRetry(t *testing.T) { configCopy := *config configCopy.MaxRetriesOnStartup = 3 couchInstance, err := createCouchInstance(&configCopy, &disabled.Provider{}) - assert.NoError(t, err, "Error when trying to create couch instance") + require.NoError(t, err, "Error when trying to create couch instance") db := couchDatabase{couchInstance: couchInstance, dbName: database} //create a new database errdb := db.createDatabaseIfNotExist() - assert.NoError(t, errdb, "Error when trying to create database") + require.NoError(t, errdb, "Error when trying to create database") //Retrieve the info for the new database and make sure the name matches dbResp, _, errdb := db.getDatabaseInfo() - assert.NoError(t, errdb, "Error when trying to retrieve database information") - assert.Equal(t, database, dbResp.DbName) + require.NoError(t, errdb, "Error when trying to retrieve database information") + require.Equal(t, database, dbResp.DbName) //Save the test document _, saveerr := db.saveDoc("1", "", &couchDoc{jsonValue: assetJSON, attachments: nil}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") //Retrieve the test document _, _, geterr := db.readDoc("1") - assert.NoError(t, geterr, "Error when trying to retrieve a document") + require.NoError(t, geterr, "Error when trying to retrieve a document") //Save the test document with an invalid rev. This should cause a retry _, saveerr = db.saveDoc("1", "1-11111111111111111111111111111111", &couchDoc{jsonValue: assetJSON, attachments: nil}) - assert.NoError(t, saveerr, "Error when trying to save a document with a revision conflict") + require.NoError(t, saveerr, "Error when trying to save a document with a revision conflict") //Delete the test document with an invalid rev. This should cause a retry deleteerr := db.deleteDoc("1", "1-11111111111111111111111111111111") - assert.NoError(t, deleteerr, "Error when trying to delete a document with a revision conflict") + require.NoError(t, deleteerr, "Error when trying to delete a document with a revision conflict") } func TestDBBadNumberOfRetries(t *testing.T) { @@ -653,7 +652,7 @@ func TestDBBadNumberOfRetries(t *testing.T) { configCopy.MaxRetries = -1 configCopy.MaxRetriesOnStartup = 3 _, err := createCouchInstance(&configCopy, &disabled.Provider{}) - assert.Error(t, err, "Error should have been thrown while attempting to create a database") + require.Error(t, err, "Error should have been thrown while attempting to create a database") } func TestDBBadJSON(t *testing.T) { @@ -665,23 +664,23 @@ func TestDBBadJSON(t *testing.T) { //create a new instance and database object couchInstance, err := createCouchInstance(config, &disabled.Provider{}) - assert.NoError(t, err, "Error when trying to create couch instance") + require.NoError(t, err, "Error when trying to create couch instance") db := couchDatabase{couchInstance: couchInstance, dbName: database} //create a new database errdb := db.createDatabaseIfNotExist() - assert.NoError(t, errdb, "Error when trying to create database") + require.NoError(t, errdb, "Error when trying to create database") //Retrieve the info for the new database and make sure the name matches dbResp, _, errdb := db.getDatabaseInfo() - assert.NoError(t, errdb, "Error when trying to retrieve database information") - assert.Equal(t, database, dbResp.DbName) + require.NoError(t, errdb, "Error when trying to retrieve database information") + require.Equal(t, database, dbResp.DbName) badJSON := []byte(`{"asset_name"}`) //Save the test document _, saveerr := db.saveDoc("1", "", &couchDoc{jsonValue: badJSON, attachments: nil}) - assert.Error(t, saveerr, "Error should have been thrown for a bad JSON") + require.Error(t, saveerr, "Error should have been thrown for a bad JSON") } @@ -694,17 +693,17 @@ func TestPrefixScan(t *testing.T) { //create a new instance and database object couchInstance, err := createCouchInstance(config, &disabled.Provider{}) - assert.NoError(t, err, "Error when trying to create couch instance") + require.NoError(t, err, "Error when trying to create couch instance") db := couchDatabase{couchInstance: couchInstance, dbName: database} //create a new database errdb := db.createDatabaseIfNotExist() - assert.NoError(t, errdb, "Error when trying to create database") + require.NoError(t, errdb, "Error when trying to create database") //Retrieve the info for the new database and make sure the name matches dbResp, _, errdb := db.getDatabaseInfo() - assert.NoError(t, errdb, "Error when trying to retrieve database information") - assert.Equal(t, database, dbResp.DbName) + require.NoError(t, errdb, "Error when trying to retrieve database information") + require.Equal(t, database, dbResp.DbName) //Save documents for i := 0; i < 20; i++ { @@ -712,34 +711,34 @@ func TestPrefixScan(t *testing.T) { id2 := string(0) + string(i) + string(1) id3 := string(0) + string(i) + string(utf8.MaxRune-1) _, saveerr := db.saveDoc(id1, "", &couchDoc{jsonValue: assetJSON, attachments: nil}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") _, saveerr = db.saveDoc(id2, "", &couchDoc{jsonValue: assetJSON, attachments: nil}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") _, saveerr = db.saveDoc(id3, "", &couchDoc{jsonValue: assetJSON, attachments: nil}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") } startKey := string(0) + string(10) endKey := startKey + string(utf8.MaxRune) _, _, geterr := db.readDoc(endKey) - assert.NoError(t, geterr, "Error when trying to get lastkey") + require.NoError(t, geterr, "Error when trying to get lastkey") resultsPtr, _, geterr := db.readDocRange(startKey, endKey, 1000) - assert.NoError(t, geterr, "Error when trying to perform a range scan") - assert.NotNil(t, resultsPtr) + require.NoError(t, geterr, "Error when trying to perform a range scan") + require.NotNil(t, resultsPtr) results := resultsPtr - assert.Equal(t, 3, len(results)) - assert.Equal(t, string(0)+string(10)+string(0), results[0].id) - assert.Equal(t, string(0)+string(10)+string(1), results[1].id) - assert.Equal(t, string(0)+string(10)+string(utf8.MaxRune-1), results[2].id) + require.Equal(t, 3, len(results)) + require.Equal(t, string(0)+string(10)+string(0), results[0].id) + require.Equal(t, string(0)+string(10)+string(1), results[1].id) + require.Equal(t, string(0)+string(10)+string(utf8.MaxRune-1), results[2].id) //Drop the database _, errdbdrop := db.dropDatabase() - assert.NoError(t, errdbdrop, "Error dropping database") + require.NoError(t, errdbdrop, "Error dropping database") //Retrieve the info for the new database and make sure the name matches _, _, errdbinfo := db.getDatabaseInfo() - assert.Error(t, errdbinfo, "Error should have been thrown for missing database") + require.Error(t, errdbinfo, "Error should have been thrown for missing database") } @@ -763,23 +762,23 @@ func TestDBSaveAttachment(t *testing.T) { //create a new instance and database object couchInstance, err := createCouchInstance(config, &disabled.Provider{}) - assert.NoError(t, err, "Error when trying to create couch instance") + require.NoError(t, err, "Error when trying to create couch instance") db := couchDatabase{couchInstance: couchInstance, dbName: database} //create a new database errdb := db.createDatabaseIfNotExist() - assert.NoError(t, errdb, "Error when trying to create database") + require.NoError(t, errdb, "Error when trying to create database") //Save the test document _, saveerr := db.saveDoc("10", "", &couchDoc{jsonValue: nil, attachments: attachments}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") //Attempt to retrieve the updated test document with attachments couchDoc, _, geterr2 := db.readDoc("10") - assert.NoError(t, geterr2, "Error when trying to retrieve a document with attachment") - assert.NotNil(t, couchDoc.attachments) - assert.Equal(t, byteText, couchDoc.attachments[0].AttachmentBytes) - assert.Equal(t, attachment.Length, couchDoc.attachments[0].Length) + require.NoError(t, geterr2, "Error when trying to retrieve a document with attachment") + require.NotNil(t, couchDoc.attachments) + require.Equal(t, byteText, couchDoc.attachments[0].AttachmentBytes) + require.Equal(t, attachment.Length, couchDoc.attachments[0].Length) } @@ -792,28 +791,28 @@ func TestDBDeleteDocument(t *testing.T) { //create a new instance and database object couchInstance, err := createCouchInstance(config, &disabled.Provider{}) - assert.NoError(t, err, "Error when trying to create couch instance") + require.NoError(t, err, "Error when trying to create couch instance") db := couchDatabase{couchInstance: couchInstance, dbName: database} //create a new database errdb := db.createDatabaseIfNotExist() - assert.NoError(t, errdb, "Error when trying to create database") + require.NoError(t, errdb, "Error when trying to create database") //Save the test document _, saveerr := db.saveDoc("2", "", &couchDoc{jsonValue: assetJSON, attachments: nil}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") //Attempt to retrieve the test document _, _, readErr := db.readDoc("2") - assert.NoError(t, readErr, "Error when trying to retrieve a document with attachment") + require.NoError(t, readErr, "Error when trying to retrieve a document with attachment") //Delete the test document deleteErr := db.deleteDoc("2", "") - assert.NoError(t, deleteErr, "Error when trying to delete a document") + require.NoError(t, deleteErr, "Error when trying to delete a document") //Attempt to retrieve the test document readValue, _, _ := db.readDoc("2") - assert.Nil(t, readValue) + require.Nil(t, readValue) } @@ -826,16 +825,16 @@ func TestDBDeleteNonExistingDocument(t *testing.T) { //create a new instance and database object couchInstance, err := createCouchInstance(config, &disabled.Provider{}) - assert.NoError(t, err, "Error when trying to create couch instance") + require.NoError(t, err, "Error when trying to create couch instance") db := couchDatabase{couchInstance: couchInstance, dbName: database} //create a new database errdb := db.createDatabaseIfNotExist() - assert.NoError(t, errdb, "Error when trying to create database") + require.NoError(t, errdb, "Error when trying to create database") //Save the test document deleteErr := db.deleteDoc("2", "") - assert.NoError(t, deleteErr, "Error when trying to delete a non existing document") + require.NoError(t, deleteErr, "Error when trying to delete a non existing document") } func TestCouchDBVersion(t *testing.T) { @@ -845,16 +844,16 @@ func TestCouchDBVersion(t *testing.T) { defer couchDBEnv.cleanup(config) err := checkCouchDBVersion("2.0.0") - assert.NoError(t, err, "Error should not have been thrown for valid version") + require.NoError(t, err, "Error should not have been thrown for valid version") err = checkCouchDBVersion("4.5.0") - assert.NoError(t, err, "Error should not have been thrown for valid version") + require.NoError(t, err, "Error should not have been thrown for valid version") err = checkCouchDBVersion("1.6.5.4") - assert.Error(t, err, "Error should have been thrown for invalid version") + require.Error(t, err, "Error should have been thrown for invalid version") err = checkCouchDBVersion("0.0.0.0") - assert.Error(t, err, "Error should have been thrown for invalid version") + require.Error(t, err, "Error should have been thrown for invalid version") } @@ -878,12 +877,12 @@ func TestIndexOperations(t *testing.T) { //create a new instance and database object -------------------------------------------------------- couchInstance, err := createCouchInstance(config, &disabled.Provider{}) - assert.NoError(t, err, "Error when trying to create couch instance") + require.NoError(t, err, "Error when trying to create couch instance") db := couchDatabase{couchInstance: couchInstance, dbName: database} //create a new database errdb := db.createDatabaseIfNotExist() - assert.NoError(t, errdb, "Error when trying to create database") + require.NoError(t, errdb, "Error when trying to create database") batchUpdateDocs := []*couchDoc{} @@ -899,30 +898,30 @@ func TestIndexOperations(t *testing.T) { batchUpdateDocs = append(batchUpdateDocs, &couchDoc{jsonValue: byteJSON10, attachments: nil}) _, err = db.batchUpdateDocuments(batchUpdateDocs) - assert.NoError(t, err, "Error adding batch of documents") + require.NoError(t, err, "Error adding batch of documents") //Create an index definition indexDefSize := `{"index":{"fields":[{"size":"desc"}]},"ddoc":"indexSizeSortDoc", "name":"indexSizeSortName","type":"json"}` //Create the index _, err = db.createIndex(indexDefSize) - assert.NoError(t, err, "Error thrown while creating an index") + require.NoError(t, err, "Error thrown while creating an index") //Retrieve the list of indexes //Delay for 100ms since CouchDB index list is updated async after index create/drop time.Sleep(100 * time.Millisecond) listResult, err := db.listIndex() - assert.NoError(t, err, "Error thrown while retrieving indexes") + require.NoError(t, err, "Error thrown while retrieving indexes") //There should only be one item returned - assert.Equal(t, 1, len(listResult)) + require.Equal(t, 1, len(listResult)) //Verify the returned definition for _, elem := range listResult { - assert.Equal(t, "indexSizeSortDoc", elem.DesignDocument) - assert.Equal(t, "indexSizeSortName", elem.Name) + require.Equal(t, "indexSizeSortDoc", elem.DesignDocument) + require.Equal(t, "indexSizeSortName", elem.Name) //ensure the index definition is correct, CouchDB 2.1.1 will also return "partial_filter_selector":{} - assert.Equal(t, true, strings.Contains(elem.Definition, `"fields":[{"size":"desc"}]`)) + require.Equal(t, true, strings.Contains(elem.Definition, `"fields":[{"size":"desc"}]`)) } //Create an index definition with no DesignDocument or name @@ -930,103 +929,103 @@ func TestIndexOperations(t *testing.T) { //Create the index _, err = db.createIndex(indexDefColor) - assert.NoError(t, err, "Error thrown while creating an index") + require.NoError(t, err, "Error thrown while creating an index") //Retrieve the list of indexes //Delay for 100ms since CouchDB index list is updated async after index create/drop time.Sleep(100 * time.Millisecond) listResult, err = db.listIndex() - assert.NoError(t, err, "Error thrown while retrieving indexes") + require.NoError(t, err, "Error thrown while retrieving indexes") //There should be two indexes returned - assert.Equal(t, 2, len(listResult)) + require.Equal(t, 2, len(listResult)) //Delete the named index err = db.deleteIndex("indexSizeSortDoc", "indexSizeSortName") - assert.NoError(t, err, "Error thrown while deleting an index") + require.NoError(t, err, "Error thrown while deleting an index") //Retrieve the list of indexes //Delay for 100ms since CouchDB index list is updated async after index create/drop time.Sleep(100 * time.Millisecond) listResult, err = db.listIndex() - assert.NoError(t, err, "Error thrown while retrieving indexes") + require.NoError(t, err, "Error thrown while retrieving indexes") //There should be one index returned - assert.Equal(t, 1, len(listResult)) + require.Equal(t, 1, len(listResult)) //Delete the unnamed index for _, elem := range listResult { err = db.deleteIndex(elem.DesignDocument, elem.Name) - assert.NoError(t, err, "Error thrown while deleting an index") + require.NoError(t, err, "Error thrown while deleting an index") } //Retrieve the list of indexes //Delay for 100ms since CouchDB index list is updated async after index create/drop time.Sleep(100 * time.Millisecond) listResult, err = db.listIndex() - assert.NoError(t, err, "Error thrown while retrieving indexes") - assert.Equal(t, 0, len(listResult)) + require.NoError(t, err, "Error thrown while retrieving indexes") + require.Equal(t, 0, len(listResult)) //Create a query string with a descending sort, this will require an index queryString := `{"selector":{"size": {"$gt": 0}},"fields": ["_id", "_rev", "owner", "asset_name", "color", "size"], "sort":[{"size":"desc"}], "limit": 10,"skip": 0}` //Execute a query with a sort, this should throw the exception _, _, err = db.queryDocuments(queryString) - assert.Error(t, err, "Error should have thrown while querying without a valid index") + require.Error(t, err, "Error should have thrown while querying without a valid index") //Create the index _, err = db.createIndex(indexDefSize) - assert.NoError(t, err, "Error thrown while creating an index") + require.NoError(t, err, "Error thrown while creating an index") //Delay for 100ms since CouchDB index list is updated async after index create/drop time.Sleep(100 * time.Millisecond) //Execute a query with an index, this should succeed _, _, err = db.queryDocuments(queryString) - assert.NoError(t, err, "Error thrown while querying with an index") + require.NoError(t, err, "Error thrown while querying with an index") //Create another index definition indexDefSize = `{"index":{"fields":[{"data.size":"desc"},{"data.owner":"desc"}]},"ddoc":"indexSizeOwnerSortDoc", "name":"indexSizeOwnerSortName","type":"json"}` //Create the index dbResp, err := db.createIndex(indexDefSize) - assert.NoError(t, err, "Error thrown while creating an index") + require.NoError(t, err, "Error thrown while creating an index") //verify the response is "created" for an index creation - assert.Equal(t, "created", dbResp.Result) + require.Equal(t, "created", dbResp.Result) //Delay for 100ms since CouchDB index list is updated async after index create/drop time.Sleep(100 * time.Millisecond) //Update the index dbResp, err = db.createIndex(indexDefSize) - assert.NoError(t, err, "Error thrown while creating an index") + require.NoError(t, err, "Error thrown while creating an index") //verify the response is "exists" for an update - assert.Equal(t, "exists", dbResp.Result) + require.Equal(t, "exists", dbResp.Result) //Retrieve the list of indexes //Delay for 100ms since CouchDB index list is updated async after index create/drop time.Sleep(100 * time.Millisecond) listResult, err = db.listIndex() - assert.NoError(t, err, "Error thrown while retrieving indexes") + require.NoError(t, err, "Error thrown while retrieving indexes") //There should only be two definitions - assert.Equal(t, 2, len(listResult)) + require.Equal(t, 2, len(listResult)) //Create an invalid index definition with an invalid JSON indexDefSize = `{"index"{"fields":[{"data.size":"desc"},{"data.owner":"desc"}]},"ddoc":"indexSizeOwnerSortDoc", "name":"indexSizeOwnerSortName","type":"json"}` //Create the index _, err = db.createIndex(indexDefSize) - assert.Error(t, err, "Error should have been thrown for an invalid index JSON") + require.Error(t, err, "Error should have been thrown for an invalid index JSON") //Create an invalid index definition with a valid JSON and an invalid index definition indexDefSize = `{"index":{"fields2":[{"data.size":"desc"},{"data.owner":"desc"}]},"ddoc":"indexSizeOwnerSortDoc", "name":"indexSizeOwnerSortName","type":"json"}` //Create the index _, err = db.createIndex(indexDefSize) - assert.Error(t, err, "Error should have been thrown for an invalid index definition") + require.Error(t, err, "Error should have been thrown for an invalid index definition") } @@ -1136,176 +1135,176 @@ func TestRichQuery(t *testing.T) { //create a new instance and database object -------------------------------------------------------- couchInstance, err := createCouchInstance(config, &disabled.Provider{}) - assert.NoError(t, err, "Error when trying to create couch instance") + require.NoError(t, err, "Error when trying to create couch instance") db := couchDatabase{couchInstance: couchInstance, dbName: database} //create a new database errdb := db.createDatabaseIfNotExist() - assert.NoError(t, errdb, "Error when trying to create database") + require.NoError(t, errdb, "Error when trying to create database") //Save the test document _, saveerr := db.saveDoc("marble01", "", &couchDoc{jsonValue: byteJSON01, attachments: attachments1}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") //Save the test document _, saveerr = db.saveDoc("marble02", "", &couchDoc{jsonValue: byteJSON02, attachments: attachments2}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") //Save the test document _, saveerr = db.saveDoc("marble03", "", &couchDoc{jsonValue: byteJSON03, attachments: attachments3}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") //Save the test document _, saveerr = db.saveDoc("marble04", "", &couchDoc{jsonValue: byteJSON04, attachments: attachments4}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") //Save the test document _, saveerr = db.saveDoc("marble05", "", &couchDoc{jsonValue: byteJSON05, attachments: attachments5}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") //Save the test document _, saveerr = db.saveDoc("marble06", "", &couchDoc{jsonValue: byteJSON06, attachments: attachments6}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") //Save the test document _, saveerr = db.saveDoc("marble07", "", &couchDoc{jsonValue: byteJSON07, attachments: attachments7}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") //Save the test document _, saveerr = db.saveDoc("marble08", "", &couchDoc{jsonValue: byteJSON08, attachments: attachments8}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") //Save the test document _, saveerr = db.saveDoc("marble09", "", &couchDoc{jsonValue: byteJSON09, attachments: attachments9}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") //Save the test document _, saveerr = db.saveDoc("marble10", "", &couchDoc{jsonValue: byteJSON10, attachments: attachments10}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") //Save the test document _, saveerr = db.saveDoc("marble11", "", &couchDoc{jsonValue: byteJSON11, attachments: attachments11}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") //Save the test document _, saveerr = db.saveDoc("marble12", "", &couchDoc{jsonValue: byteJSON12, attachments: attachments12}) - assert.NoError(t, saveerr, "Error when trying to save a document") + require.NoError(t, saveerr, "Error when trying to save a document") //Test query with invalid JSON ------------------------------------------------------------------- queryString := `{"selector":{"owner":}}` _, _, err = db.queryDocuments(queryString) - assert.Error(t, err, "Error should have been thrown for bad json") + require.Error(t, err, "Error should have been thrown for bad json") //Test query with object ------------------------------------------------------------------- queryString = `{"selector":{"owner":{"$eq":"jerry"}}}` queryResult, _, err := db.queryDocuments(queryString) - assert.NoError(t, err, "Error when attempting to execute a query") + require.NoError(t, err, "Error when attempting to execute a query") //There should be 3 results for owner="jerry" - assert.Equal(t, 3, len(queryResult)) + require.Equal(t, 3, len(queryResult)) //Test query with implicit operator -------------------------------------------------------------- queryString = `{"selector":{"owner":"jerry"}}` queryResult, _, err = db.queryDocuments(queryString) - assert.NoError(t, err, "Error when attempting to execute a query") + require.NoError(t, err, "Error when attempting to execute a query") //There should be 3 results for owner="jerry" - assert.Equal(t, 3, len(queryResult)) + require.Equal(t, 3, len(queryResult)) //Test query with specified fields ------------------------------------------------------------------- queryString = `{"selector":{"owner":{"$eq":"jerry"}},"fields": ["owner","asset_name","color","size"]}` queryResult, _, err = db.queryDocuments(queryString) - assert.NoError(t, err, "Error when attempting to execute a query") + require.NoError(t, err, "Error when attempting to execute a query") //There should be 3 results for owner="jerry" - assert.Equal(t, 3, len(queryResult)) + require.Equal(t, 3, len(queryResult)) //Test query with a leading operator ------------------------------------------------------------------- queryString = `{"selector":{"$or":[{"owner":{"$eq":"jerry"}},{"owner": {"$eq": "frank"}}]}}` queryResult, _, err = db.queryDocuments(queryString) - assert.NoError(t, err, "Error when attempting to execute a query") + require.NoError(t, err, "Error when attempting to execute a query") //There should be 4 results for owner="jerry" or owner="frank" - assert.Equal(t, 4, len(queryResult)) + require.Equal(t, 4, len(queryResult)) //Test query implicit and explicit operator ------------------------------------------------------------------ queryString = `{"selector":{"color":"green","$or":[{"owner":"tom"},{"owner":"frank"}]}}` queryResult, _, err = db.queryDocuments(queryString) - assert.NoError(t, err, "Error when attempting to execute a query") + require.NoError(t, err, "Error when attempting to execute a query") //There should be 2 results for color="green" and (owner="jerry" or owner="frank") - assert.Equal(t, 2, len(queryResult)) + require.Equal(t, 2, len(queryResult)) //Test query with a leading operator ------------------------------------------------------------------------- queryString = `{"selector":{"$and":[{"size":{"$gte":2}},{"size":{"$lte":5}}]}}` queryResult, _, err = db.queryDocuments(queryString) - assert.NoError(t, err, "Error when attempting to execute a query") + require.NoError(t, err, "Error when attempting to execute a query") //There should be 4 results for size >= 2 and size <= 5 - assert.Equal(t, 4, len(queryResult)) + require.Equal(t, 4, len(queryResult)) //Test query with leading and embedded operator ------------------------------------------------------------- queryString = `{"selector":{"$and":[{"size":{"$gte":3}},{"size":{"$lte":10}},{"$not":{"size":7}}]}}` queryResult, _, err = db.queryDocuments(queryString) - assert.NoError(t, err, "Error when attempting to execute a query") + require.NoError(t, err, "Error when attempting to execute a query") //There should be 7 results for size >= 3 and size <= 10 and not 7 - assert.Equal(t, 7, len(queryResult)) + require.Equal(t, 7, len(queryResult)) //Test query with leading operator and array of objects ---------------------------------------------------------- queryString = `{"selector":{"$and":[{"size":{"$gte":2}},{"size":{"$lte":10}},{"$nor":[{"size":3},{"size":5},{"size":7}]}]}}` queryResult, _, err = db.queryDocuments(queryString) - assert.NoError(t, err, "Error when attempting to execute a query") + require.NoError(t, err, "Error when attempting to execute a query") //There should be 6 results for size >= 2 and size <= 10 and not 3,5 or 7 - assert.Equal(t, 6, len(queryResult)) + require.Equal(t, 6, len(queryResult)) //Test a range query --------------------------------------------------------------------------------------------- queryResult, _, err = db.readDocRange("marble02", "marble06", 10000) - assert.NoError(t, err, "Error when attempting to execute a range query") + require.NoError(t, err, "Error when attempting to execute a range query") //There should be 4 results - assert.Equal(t, 4, len(queryResult)) + require.Equal(t, 4, len(queryResult)) //Attachments retrieved should be correct - assert.Equal(t, attachment2.AttachmentBytes, queryResult[0].attachments[0].AttachmentBytes) - assert.Equal(t, attachment3.AttachmentBytes, queryResult[1].attachments[0].AttachmentBytes) - assert.Equal(t, attachment4.AttachmentBytes, queryResult[2].attachments[0].AttachmentBytes) - assert.Equal(t, attachment5.AttachmentBytes, queryResult[3].attachments[0].AttachmentBytes) + require.Equal(t, attachment2.AttachmentBytes, queryResult[0].attachments[0].AttachmentBytes) + require.Equal(t, attachment3.AttachmentBytes, queryResult[1].attachments[0].AttachmentBytes) + require.Equal(t, attachment4.AttachmentBytes, queryResult[2].attachments[0].AttachmentBytes) + require.Equal(t, attachment5.AttachmentBytes, queryResult[3].attachments[0].AttachmentBytes) //Test query with for tom ------------------------------------------------------------------- queryString = `{"selector":{"owner":{"$eq":"tom"}}}` queryResult, _, err = db.queryDocuments(queryString) - assert.NoError(t, err, "Error when attempting to execute a query") + require.NoError(t, err, "Error when attempting to execute a query") //There should be 8 results for owner="tom" - assert.Equal(t, 8, len(queryResult)) + require.Equal(t, 8, len(queryResult)) //Test query with for tom with limit ------------------------------------------------------------------- queryString = `{"selector":{"owner":{"$eq":"tom"}},"limit":2}` queryResult, _, err = db.queryDocuments(queryString) - assert.NoError(t, err, "Error when attempting to execute a query") + require.NoError(t, err, "Error when attempting to execute a query") //There should be 2 results for owner="tom" with a limit of 2 - assert.Equal(t, 2, len(queryResult)) + require.Equal(t, 2, len(queryResult)) //Create an index definition indexDefSize := `{"index":{"fields":[{"size":"desc"}]},"ddoc":"indexSizeSortDoc", "name":"indexSizeSortName","type":"json"}` //Create the index _, err = db.createIndex(indexDefSize) - assert.NoError(t, err, "Error thrown while creating an index") + require.NoError(t, err, "Error thrown while creating an index") //Delay for 100ms since CouchDB index list is updated async after index create/drop time.Sleep(100 * time.Millisecond) @@ -1314,7 +1313,7 @@ func TestRichQuery(t *testing.T) { queryString = `{"selector":{"size":{"$gt":0}}, "use_index":["indexSizeSortDoc","indexSizeSortName"]}` _, _, err = db.queryDocuments(queryString) - assert.NoError(t, err, "Error when attempting to execute a query with a valid index") + require.NoError(t, err, "Error when attempting to execute a query with a valid index") } @@ -1373,12 +1372,12 @@ func testBatchBatchOperations(t *testing.T, config *ledger.CouchDBConfig) { //create a new instance and database object -------------------------------------------------------- couchInstance, err := createCouchInstance(config, &disabled.Provider{}) - assert.NoError(t, err, "Error when trying to create couch instance") + require.NoError(t, err, "Error when trying to create couch instance") db := couchDatabase{couchInstance: couchInstance, dbName: database} //create a new database errdb := db.createDatabaseIfNotExist() - assert.NoError(t, errdb, "Error when trying to create database") + require.NoError(t, errdb, "Error when trying to create database") batchUpdateDocs := []*couchDoc{} @@ -1397,59 +1396,59 @@ func testBatchBatchOperations(t *testing.T, config *ledger.CouchDBConfig) { batchUpdateDocs = append(batchUpdateDocs, value6) batchUpdateResp, err := db.batchUpdateDocuments(batchUpdateDocs) - assert.NoError(t, err, "Error when attempting to update a batch of documents") + require.NoError(t, err, "Error when attempting to update a batch of documents") //check to make sure each batch update response was successful for _, updateDoc := range batchUpdateResp { - assert.Equal(t, true, updateDoc.Ok) + require.Equal(t, true, updateDoc.Ok) } //---------------------------------------------- //Test Retrieve JSON dbGetResp, _, geterr := db.readDoc("marble01") - assert.NoError(t, geterr, "Error when attempting read a document") + require.NoError(t, geterr, "Error when attempting read a document") assetResp := &Asset{} geterr = json.Unmarshal(dbGetResp.jsonValue, &assetResp) - assert.NoError(t, geterr, "Error when trying to retrieve a document") + require.NoError(t, geterr, "Error when trying to retrieve a document") //Verify the owner retrieved matches - assert.Equal(t, "jerry", assetResp.Owner) + require.Equal(t, "jerry", assetResp.Owner) //---------------------------------------------- // Test Retrieve JSON using ID with URL special characters, // this will confirm that batch document IDs and URL IDs are consistent, even if they include special characters dbGetResp, _, geterr = db.readDoc("marble06#$&'()*+,/:;=?@[]") - assert.NoError(t, geterr, "Error when attempting read a document") + require.NoError(t, geterr, "Error when attempting read a document") assetResp = &Asset{} geterr = json.Unmarshal(dbGetResp.jsonValue, &assetResp) - assert.NoError(t, geterr, "Error when trying to retrieve a document") + require.NoError(t, geterr, "Error when trying to retrieve a document") //Verify the owner retrieved matches - assert.Equal(t, "jerry", assetResp.Owner) + require.Equal(t, "jerry", assetResp.Owner) //---------------------------------------------- //Test retrieve binary dbGetResp, _, geterr = db.readDoc("marble03") - assert.NoError(t, geterr, "Error when attempting read a document") + require.NoError(t, geterr, "Error when attempting read a document") //Retrieve the attachments attachments := dbGetResp.attachments //Only one was saved, so take the first retrievedAttachment := attachments[0] //Verify the text matches - assert.Equal(t, retrievedAttachment.AttachmentBytes, attachment3.AttachmentBytes) + require.Equal(t, retrievedAttachment.AttachmentBytes, attachment3.AttachmentBytes) //---------------------------------------------- //Test Bad Updates batchUpdateDocs = []*couchDoc{} batchUpdateDocs = append(batchUpdateDocs, value1) batchUpdateDocs = append(batchUpdateDocs, value2) batchUpdateResp, err = db.batchUpdateDocuments(batchUpdateDocs) - assert.NoError(t, err, "Error when attempting to update a batch of documents") + require.NoError(t, err, "Error when attempting to update a batch of documents") //No revision was provided, so these two updates should fail //Verify that the "Ok" field is returned as false for _, updateDoc := range batchUpdateResp { - assert.Equal(t, false, updateDoc.Ok) - assert.Equal(t, updateDocumentConflictError, updateDoc.Error) - assert.Equal(t, updateDocumentConflictReason, updateDoc.Reason) + require.Equal(t, false, updateDoc.Ok) + require.Equal(t, updateDocumentConflictError, updateDoc.Error) + require.Equal(t, updateDocumentConflictReason, updateDoc.Reason) } //---------------------------------------------- @@ -1461,7 +1460,7 @@ func testBatchBatchOperations(t *testing.T, config *ledger.CouchDBConfig) { keys = append(keys, "marble03") batchRevs, err := db.batchRetrieveDocumentMetadata(keys) - assert.NoError(t, err, "Error when attempting retrieve revisions") + require.NoError(t, err, "Error when attempting retrieve revisions") batchUpdateDocs = []*couchDoc{} @@ -1482,10 +1481,10 @@ func testBatchBatchOperations(t *testing.T, config *ledger.CouchDBConfig) { //Update couchdb with the batch batchUpdateResp, err = db.batchUpdateDocuments(batchUpdateDocs) - assert.NoError(t, err, "Error when attempting to update a batch of documents") + require.NoError(t, err, "Error when attempting to update a batch of documents") //check to make sure each batch update response was successful for _, updateDoc := range batchUpdateResp { - assert.Equal(t, true, updateDoc.Ok) + require.Equal(t, true, updateDoc.Ok) } //---------------------------------------------- @@ -1497,7 +1496,7 @@ func testBatchBatchOperations(t *testing.T, config *ledger.CouchDBConfig) { keys = append(keys, "marble04") batchRevs, err = db.batchRetrieveDocumentMetadata(keys) - assert.NoError(t, err, "Error when attempting retrieve revisions") + require.NoError(t, err, "Error when attempting retrieve revisions") batchUpdateDocs = []*couchDoc{} @@ -1517,26 +1516,26 @@ func testBatchBatchOperations(t *testing.T, config *ledger.CouchDBConfig) { //Update couchdb with the batch batchUpdateResp, err = db.batchUpdateDocuments(batchUpdateDocs) - assert.NoError(t, err, "Error when attempting to update a batch of documents") + require.NoError(t, err, "Error when attempting to update a batch of documents") //check to make sure each batch update response was successful for _, updateDoc := range batchUpdateResp { - assert.Equal(t, true, updateDoc.Ok) + require.Equal(t, true, updateDoc.Ok) } //Retrieve the test document dbGetResp, _, geterr = db.readDoc("marble02") - assert.NoError(t, geterr, "Error when trying to retrieve a document") + require.NoError(t, geterr, "Error when trying to retrieve a document") //assert the value was deleted - assert.Nil(t, dbGetResp) + require.Nil(t, dbGetResp) //Retrieve the test document dbGetResp, _, geterr = db.readDoc("marble04") - assert.NoError(t, geterr, "Error when trying to retrieve a document") + require.NoError(t, geterr, "Error when trying to retrieve a document") //assert the value was deleted - assert.Nil(t, dbGetResp) + require.Nil(t, dbGetResp) } @@ -1573,12 +1572,12 @@ func TestDatabaseSecuritySettings(t *testing.T) { //create a new instance and database object -------------------------------------------------------- couchInstance, err := createCouchInstance(config, &disabled.Provider{}) - assert.NoError(t, err, "Error when trying to create couch instance") + require.NoError(t, err, "Error when trying to create couch instance") db := couchDatabase{couchInstance: couchInstance, dbName: database} //create a new database errdb := db.createDatabaseIfNotExist() - assert.NoError(t, errdb, "Error when trying to create database") + require.NoError(t, errdb, "Error when trying to create database") //Create a database security object securityPermissions := &databaseSecurity{} @@ -1587,34 +1586,34 @@ func TestDatabaseSecuritySettings(t *testing.T) { //Apply security err = db.applyDatabaseSecurity(securityPermissions) - assert.NoError(t, err, "Error when trying to apply database security") + require.NoError(t, err, "Error when trying to apply database security") //Retrieve database security dbSecurity, err := db.getDatabaseSecurity() - assert.NoError(t, err, "Error when retrieving database security") + require.NoError(t, err, "Error when retrieving database security") //Verify retrieval of admins - assert.Equal(t, "admin", dbSecurity.Admins.Names[0]) + require.Equal(t, "admin", dbSecurity.Admins.Names[0]) //Verify retrieval of members - assert.Equal(t, "admin", dbSecurity.Members.Names[0]) + require.Equal(t, "admin", dbSecurity.Members.Names[0]) //Create an empty database security object securityPermissions = &databaseSecurity{} //Apply the security err = db.applyDatabaseSecurity(securityPermissions) - assert.NoError(t, err, "Error when trying to apply database security") + require.NoError(t, err, "Error when trying to apply database security") //Retrieve database security dbSecurity, err = db.getDatabaseSecurity() - assert.NoError(t, err, "Error when retrieving database security") + require.NoError(t, err, "Error when retrieving database security") //Verify retrieval of admins, should be an empty array - assert.Equal(t, 0, len(dbSecurity.Admins.Names)) + require.Equal(t, 0, len(dbSecurity.Admins.Names)) //Verify retrieval of members, should be an empty array - assert.Equal(t, 0, len(dbSecurity.Members.Names)) + require.Equal(t, 0, len(dbSecurity.Members.Names)) } @@ -1627,25 +1626,25 @@ func TestURLWithSpecialCharacters(t *testing.T) { // parse a contructed URL finalURL, err := url.Parse("http://127.0.0.1:5984") - assert.NoError(t, err, "error thrown while parsing couchdb url") + require.NoError(t, err, "error thrown while parsing couchdb url") // test the constructCouchDBUrl function with multiple path elements couchdbURL := constructCouchDBUrl(finalURL, database, "_index", "designdoc", "json", "indexname") - assert.Equal(t, "http://127.0.0.1:5984/testdb%2Bwith%2Bplus_sign/_index/designdoc/json/indexname", couchdbURL.String()) + require.Equal(t, "http://127.0.0.1:5984/testdb%2Bwith%2Bplus_sign/_index/designdoc/json/indexname", couchdbURL.String()) //create a new instance and database object -------------------------------------------------------- couchInstance, err := createCouchInstance(config, &disabled.Provider{}) - assert.NoError(t, err, "Error when trying to create couch instance") + require.NoError(t, err, "Error when trying to create couch instance") db := couchDatabase{couchInstance: couchInstance, dbName: database} //create a new database errdb := db.createDatabaseIfNotExist() - assert.NoError(t, errdb, "Error when trying to create database") + require.NoError(t, errdb, "Error when trying to create database") dbInfo, _, errInfo := db.getDatabaseInfo() - assert.NoError(t, errInfo, "Error when trying to get database info") + require.NoError(t, errInfo, "Error when trying to get database info") - assert.Equal(t, database, dbInfo.DbName) + require.Equal(t, database, dbInfo.DbName) } diff --git a/core/ledger/kvledger/txmgmt/statedb/statecouchdb/couchdbutil_test.go b/core/ledger/kvledger/txmgmt/statedb/statecouchdb/couchdbutil_test.go index e03a3271a2e..f59fdd851b0 100644 --- a/core/ledger/kvledger/txmgmt/statedb/statecouchdb/couchdbutil_test.go +++ b/core/ledger/kvledger/txmgmt/statedb/statecouchdb/couchdbutil_test.go @@ -13,7 +13,7 @@ import ( "github.com/hyperledger/fabric/common/metrics/disabled" "github.com/hyperledger/fabric/common/util" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) //Unit test of couch db util functionality @@ -25,10 +25,10 @@ func TestCreateCouchDBConnectionAndDB(t *testing.T) { database := "testcreatecouchdbconnectionanddb" //create a new connection couchInstance, err := createCouchInstance(config, &disabled.Provider{}) - assert.NoError(t, err, "Error when trying to CreateCouchInstance") + require.NoError(t, err, "Error when trying to CreateCouchInstance") _, err = createCouchDatabase(couchInstance, database) - assert.NoError(t, err, "Error when trying to CreateCouchDatabase") + require.NoError(t, err, "Error when trying to CreateCouchDatabase") } @@ -43,13 +43,13 @@ func TestNotCreateCouchGlobalChangesDB(t *testing.T) { //create a new connection couchInstance, err := createCouchInstance(config, &disabled.Provider{}) - assert.NoError(t, err, "Error when trying to CreateCouchInstance") + require.NoError(t, err, "Error when trying to CreateCouchInstance") db := couchDatabase{couchInstance: couchInstance, dbName: database} //Retrieve the info for the new database and make sure the name matches _, _, errdb := db.getDatabaseInfo() - assert.NotNil(t, errdb) + require.NotNil(t, errdb) } //Unit test of couch db util functionality @@ -63,60 +63,60 @@ func TestCreateCouchDBSystemDBs(t *testing.T) { //create a new connection couchInstance, err := createCouchInstance(config, &disabled.Provider{}) - assert.NoError(t, err, "Error when trying to CreateCouchInstance") + require.NoError(t, err, "Error when trying to CreateCouchInstance") err = createSystemDatabasesIfNotExist(couchInstance) - assert.NoError(t, err, "Error when trying to create system databases") + require.NoError(t, err, "Error when trying to create system databases") db := couchDatabase{couchInstance: couchInstance, dbName: "_users"} //Retrieve the info for the new database and make sure the name matches dbResp, _, errdb := db.getDatabaseInfo() - assert.NoError(t, errdb, "Error when trying to retrieve _users database information") - assert.Equal(t, "_users", dbResp.DbName) + require.NoError(t, errdb, "Error when trying to retrieve _users database information") + require.Equal(t, "_users", dbResp.DbName) db = couchDatabase{couchInstance: couchInstance, dbName: "_replicator"} //Retrieve the info for the new database and make sure the name matches dbResp, _, errdb = db.getDatabaseInfo() - assert.NoError(t, errdb, "Error when trying to retrieve _replicator database information") - assert.Equal(t, "_replicator", dbResp.DbName) + require.NoError(t, errdb, "Error when trying to retrieve _replicator database information") + require.Equal(t, "_replicator", dbResp.DbName) db = couchDatabase{couchInstance: couchInstance, dbName: "_global_changes"} //Retrieve the info for the new database and make sure the name matches dbResp, _, errdb = db.getDatabaseInfo() - assert.NoError(t, errdb, "Error when trying to retrieve _global_changes database information") - assert.Equal(t, "_global_changes", dbResp.DbName) + require.NoError(t, errdb, "Error when trying to retrieve _global_changes database information") + require.Equal(t, "_global_changes", dbResp.DbName) } func TestDatabaseMapping(t *testing.T) { //create a new instance and database object using a database name mixed case _, err := mapAndValidateDatabaseName("testDB") - assert.Error(t, err, "Error expected because the name contains capital letters") + require.Error(t, err, "Error expected because the name contains capital letters") //create a new instance and database object using a database name with special characters _, err = mapAndValidateDatabaseName("test1234/1") - assert.Error(t, err, "Error expected because the name contains illegal chars") + require.Error(t, err, "Error expected because the name contains illegal chars") //create a new instance and database object using a database name with special characters _, err = mapAndValidateDatabaseName("5test1234") - assert.Error(t, err, "Error expected because the name starts with a number") + require.Error(t, err, "Error expected because the name starts with a number") //create a new instance and database object using an empty string _, err = mapAndValidateDatabaseName("") - assert.Error(t, err, "Error should have been thrown for an invalid name") + require.Error(t, err, "Error should have been thrown for an invalid name") _, err = mapAndValidateDatabaseName("a12345678901234567890123456789012345678901234" + "56789012345678901234567890123456789012345678901234567890123456789012345678901234567890" + "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456" + "78901234567890123456789012345678901234567890") - assert.Error(t, err, "Error should have been thrown for an invalid name") + require.Error(t, err, "Error should have been thrown for an invalid name") transformedName, err := mapAndValidateDatabaseName("test.my.db-1") - assert.NoError(t, err, "") - assert.Equal(t, "test$my$db-1", transformedName) + require.NoError(t, err, "") + require.Equal(t, "test$my$db-1", transformedName) } func TestConstructMetadataDBName(t *testing.T) { @@ -124,7 +124,7 @@ func TestConstructMetadataDBName(t *testing.T) { chainName := "tob2g.y-z0f.qwp-rq5g4-ogid5g6oucyryg9sc16mz0t4vuake5q557esz7sn493nf0ghch0xih6dwuirokyoi4jvs67gh6r5v6mhz3-292un2-9egdcs88cstg3f7xa9m1i8v4gj0t3jedsm-woh3kgiqehwej6h93hdy5tr4v.1qmmqjzz0ox62k.507sh3fkw3-mfqh.ukfvxlm5szfbwtpfkd1r4j.cy8oft5obvwqpzjxb27xuw6" truncatedChainName := "tob2g.y-z0f.qwp-rq5g4-ogid5g6oucyryg9sc16mz0t4vuak" - assert.Equal(t, chainNameAllowedLength, len(truncatedChainName)) + require.Equal(t, chainNameAllowedLength, len(truncatedChainName)) // + 1 char for '(' + <64 chars for SHA256 hash // (hex encoding) of untruncated chainName> + 1 char for ')' + 1 char for '_' = 117 chars @@ -133,8 +133,8 @@ func TestConstructMetadataDBName(t *testing.T) { expectedDBNameLength := 117 constructedDBName := constructMetadataDBName(chainName) - assert.Equal(t, expectedDBNameLength, len(constructedDBName)) - assert.Equal(t, expectedDBName, constructedDBName) + require.Equal(t, expectedDBNameLength, len(constructedDBName)) + require.Equal(t, expectedDBName, constructedDBName) } func TestConstructedNamespaceDBName(t *testing.T) { @@ -152,9 +152,9 @@ func TestConstructedNamespaceDBName(t *testing.T) { truncatedChainName := "tob2g.y-z0f.qwp-rq5g4-ogid5g6oucyryg9sc16mz0t4vuak" truncatedEscapedNs := "w$m$cn$s$xi$v9$yo$iq$n$qy$nv$f$v$td$m8$xn$utvr$o$f" truncatedEscapedColl := "pv$wjtf$s$t$x$v$k8$w$jus5s6z$wo$m$ici$xd7q$h$r$z$i" - assert.Equal(t, chainNameAllowedLength, len(truncatedChainName)) - assert.Equal(t, namespaceNameAllowedLength, len(truncatedEscapedNs)) - assert.Equal(t, collectionNameAllowedLength, len(truncatedEscapedColl)) + require.Equal(t, chainNameAllowedLength, len(truncatedChainName)) + require.Equal(t, namespaceNameAllowedLength, len(truncatedEscapedNs)) + require.Equal(t, collectionNameAllowedLength, len(truncatedEscapedColl)) untruncatedDBName := chainName + "_" + ns + "$$" + coll hash := hex.EncodeToString(util.ComputeSHA256([]byte(untruncatedDBName))) @@ -167,8 +167,8 @@ func TestConstructedNamespaceDBName(t *testing.T) { namespace := ns + "$$" + coll constructedDBName := constructNamespaceDBName(chainName, namespace) - assert.Equal(t, expectedDBNameLength, len(constructedDBName)) - assert.Equal(t, expectedDBName, constructedDBName) + require.Equal(t, expectedDBNameLength, len(constructedDBName)) + require.Equal(t, expectedDBName, constructedDBName) // === SCENARIO 2: chainName_ns === @@ -182,8 +182,8 @@ func TestConstructedNamespaceDBName(t *testing.T) { namespace = ns constructedDBName = constructNamespaceDBName(chainName, namespace) - assert.Equal(t, expectedDBNameLength, len(constructedDBName)) - assert.Equal(t, expectedDBName, constructedDBName) + require.Equal(t, expectedDBNameLength, len(constructedDBName)) + require.Equal(t, expectedDBName, constructedDBName) } func TestDropApplicationDBs(t *testing.T) { @@ -194,24 +194,24 @@ func TestDropApplicationDBs(t *testing.T) { database := "testdropapplicationdbs" couchInstance, err := createCouchInstance(config, &disabled.Provider{}) - assert.NoError(t, err, "Error when trying to create couch instance") + require.NoError(t, err, "Error when trying to create couch instance") numCouchdbs := 10 for i := 0; i < numCouchdbs; i++ { db, err := createCouchDatabase(couchInstance, fmt.Sprintf("%s_%d", database, i)) - assert.NoErrorf(t, err, "Error when trying to create database %s", db.dbName) + require.NoErrorf(t, err, "Error when trying to create database %s", db.dbName) } dbs, err := couchInstance.retrieveApplicationDBNames() - assert.NoError(t, err, "Error when retrieving application db names") - assert.Equal(t, numCouchdbs, len(dbs), "Expected number of databases are not created") + require.NoError(t, err, "Error when retrieving application db names") + require.Equal(t, numCouchdbs, len(dbs), "Expected number of databases are not created") err = DropApplicationDBs(config) - assert.NoError(t, err, "Error when dropping all application dbs") + require.NoError(t, err, "Error when dropping all application dbs") dbs, err = couchInstance.retrieveApplicationDBNames() - assert.NoError(t, err, "Error when retrieving application db names") - assert.Equal(t, 0, len(dbs), "Databases should be dropped") + require.NoError(t, err, "Error when retrieving application db names") + require.Equal(t, 0, len(dbs), "Databases should be dropped") } func TestDropApplicationDBsWhenDBNotStarted(t *testing.T) { @@ -219,5 +219,5 @@ func TestDropApplicationDBsWhenDBNotStarted(t *testing.T) { config.MaxRetriesOnStartup = 1 config.Address = "127.0.0.1:5984" err := DropApplicationDBs(config) - assert.EqualError(t, err, `unable to connect to CouchDB, check the hostname and port: http error calling couchdb: Get "http://127.0.0.1:5984/": dial tcp 127.0.0.1:5984: connect: connection refused`) + require.EqualError(t, err, `unable to connect to CouchDB, check the hostname and port: http error calling couchdb: Get "http://127.0.0.1:5984/": dial tcp 127.0.0.1:5984: connect: connection refused`) } diff --git a/core/ledger/kvledger/txmgmt/statedb/statecouchdb/dbvalue_encoding_test.go b/core/ledger/kvledger/txmgmt/statedb/statecouchdb/dbvalue_encoding_test.go index 37869d7a239..5c1358db1ed 100644 --- a/core/ledger/kvledger/txmgmt/statedb/statecouchdb/dbvalue_encoding_test.go +++ b/core/ledger/kvledger/txmgmt/statedb/statecouchdb/dbvalue_encoding_test.go @@ -12,7 +12,6 @@ import ( "github.com/hyperledger/fabric/core/ledger/internal/version" "github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/statedb" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -39,12 +38,12 @@ func TestEncodeDecodeOfVersionAndMetadata(t *testing.T) { func testEncodeDecodeOfVersionAndMetadata(t *testing.T, v *statedb.VersionedValue) { encodedVerField, err := encodeVersionAndMetadata(v.Version, v.Metadata) - assert.NoError(t, err) + require.NoError(t, err) ver, metadata, err := decodeVersionAndMetadata(encodedVerField) - assert.NoError(t, err) - assert.Equal(t, v.Version, ver) - assert.Equal(t, v.Metadata, metadata) + require.NoError(t, err) + require.Equal(t, v.Version, ver) + require.Equal(t, v.Metadata, metadata) } func TestEncodeDecodeOfValueVersionMetadata(t *testing.T) { diff --git a/core/ledger/kvledger/txmgmt/statedb/statecouchdb/redolog_test.go b/core/ledger/kvledger/txmgmt/statedb/statecouchdb/redolog_test.go index 744272f6c16..2ad993023be 100644 --- a/core/ledger/kvledger/txmgmt/statedb/statecouchdb/redolog_test.go +++ b/core/ledger/kvledger/txmgmt/statedb/statecouchdb/redolog_test.go @@ -15,7 +15,7 @@ import ( "github.com/davecgh/go-spew/spew" "github.com/hyperledger/fabric/core/ledger/internal/version" "github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/statedb" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRedoLogger(t *testing.T) { @@ -28,8 +28,8 @@ func TestRedoLogger(t *testing.T) { verifyLogRecords := func() { for i := 0; i < len(loggers); i++ { retrievedRec, err := loggers[i].load() - assert.NoError(t, err) - assert.Equal(t, records[i], retrievedRec) + require.NoError(t, err) + require.Equal(t, records[i], retrievedRec) } } @@ -37,8 +37,8 @@ func TestRedoLogger(t *testing.T) { for i := 0; i < 10; i++ { logger := provider.newRedoLogger(fmt.Sprintf("channel-%d", i)) rec, err := logger.load() - assert.NoError(t, err) - assert.Nil(t, rec) + require.NoError(t, err) + require.Nil(t, rec) loggers = append(loggers, logger) batch := statedb.NewUpdateBatch() blkNum := uint64(i) @@ -51,14 +51,14 @@ func TestRedoLogger(t *testing.T) { Version: version.NewHeight(blkNum, 10), } records = append(records, rec) - assert.NoError(t, logger.persist(rec)) + require.NoError(t, logger.persist(rec)) } verifyLogRecords() // overwrite logrecord for one channel records[5].UpdateBatch = statedb.NewUpdateBatch() records[5].Version = version.NewHeight(5, 5) - assert.NoError(t, loggers[5].persist(records[5])) + require.NoError(t, loggers[5].persist(records[5])) verifyLogRecords() } @@ -71,9 +71,9 @@ func TestCouchdbRedoLogger(t *testing.T) { batch := statedb.NewUpdateBatch() batch.Put("ns1", "key1", []byte(newVal), version) db, err := vdbEnv.DBProvider.GetDBHandle("testcouchdbredologger", nil) - assert.NoError(t, err) + require.NoError(t, err) vdb := db.(*VersionedDB) - assert.NoError(t, + require.NoError(t, vdb.redoLogger.persist( &redoRecord{ UpdateBatch: batch, @@ -86,14 +86,14 @@ func TestCouchdbRedoLogger(t *testing.T) { // verifyExpectedVal - a helper function that verifies the statedb contents verifyExpectedVal := func(expectedVal string, expectedSavepoint *version.Height) { db, err := vdbEnv.DBProvider.GetDBHandle("testcouchdbredologger", nil) - assert.NoError(t, err) + require.NoError(t, err) vdb := db.(*VersionedDB) vv, err := vdb.GetState("ns1", "key1") - assert.NoError(t, err) - assert.Equal(t, expectedVal, string(vv.Value)) + require.NoError(t, err) + require.Equal(t, expectedVal, string(vv.Value)) savepoint, err := vdb.GetLatestSavePoint() - assert.NoError(t, err) - assert.Equal(t, expectedSavepoint, savepoint) + require.NoError(t, err) + require.Equal(t, expectedSavepoint, savepoint) } // initialize statedb with initial set of writes @@ -123,9 +123,9 @@ func TestCouchdbRedoLogger(t *testing.T) { vdb = db.(*VersionedDB) vdb.ApplyUpdates(batch1, nil) record, err := vdb.redoLogger.load() - assert.NoError(t, err) - assert.Equal(t, version.NewHeight(1, 5), record.Version) - assert.Equal(t, []byte("value3"), record.UpdateBatch.Get("ns1", "key1").Value) + require.NoError(t, err) + require.Equal(t, version.NewHeight(1, 5), record.Version) + require.Equal(t, []byte("value3"), record.UpdateBatch.Get("ns1", "key1").Value) // A batch that does not contain PostOrderWrites should cause skipping the writing of redo-record db, _ = vdbEnv.DBProvider.GetDBHandle("testcouchdbredologger", nil) @@ -134,9 +134,9 @@ func TestCouchdbRedoLogger(t *testing.T) { batchWithNoGeneratedWrites.ContainsPostOrderWrites = false vdb.ApplyUpdates(batchWithNoGeneratedWrites, version.NewHeight(2, 5)) record, err = vdb.redoLogger.load() - assert.NoError(t, err) - assert.Equal(t, version.NewHeight(1, 5), record.Version) - assert.Equal(t, []byte("value3"), record.UpdateBatch.Get("ns1", "key1").Value) + require.NoError(t, err) + require.Equal(t, version.NewHeight(1, 5), record.Version) + require.Equal(t, []byte("value3"), record.UpdateBatch.Get("ns1", "key1").Value) // A batch that contains PostOrderWrites should cause writing of redo-record db, _ = vdbEnv.DBProvider.GetDBHandle("testcouchdbredologger", nil) @@ -145,9 +145,9 @@ func TestCouchdbRedoLogger(t *testing.T) { batchWithGeneratedWrites.ContainsPostOrderWrites = true vdb.ApplyUpdates(batchWithNoGeneratedWrites, version.NewHeight(3, 4)) record, err = vdb.redoLogger.load() - assert.NoError(t, err) - assert.Equal(t, version.NewHeight(3, 4), record.Version) - assert.Equal(t, []byte("value1"), record.UpdateBatch.Get("ns1", "key1").Value) + require.NoError(t, err) + require.Equal(t, version.NewHeight(3, 4), record.Version) + require.Equal(t, []byte("value1"), record.UpdateBatch.Get("ns1", "key1").Value) } func redologTestSetup(t *testing.T) (p *redoLoggerProvider, cleanup func()) { @@ -156,10 +156,10 @@ func redologTestSetup(t *testing.T) (p *redoLoggerProvider, cleanup func()) { t.Fatalf("Failed to create redo log directory: %s", err) } p, err = newRedoLoggerProvider(dbPath) - assert.NoError(t, err) + require.NoError(t, err) cleanup = func() { p.close() - assert.NoError(t, os.RemoveAll(dbPath)) + require.NoError(t, os.RemoveAll(dbPath)) } return } @@ -175,17 +175,17 @@ func redologTestSetup(t *testing.T) (p *redoLoggerProvider, cleanup func()) { // uppercase "T" so that execution of go test will generate the test file. func testGenerareRedoRecord(t *testing.T) { val, err := encodeRedologVal(constructSampleRedoRecord()) - assert.NoError(t, err) - assert.NoError(t, ioutil.WriteFile("testdata/persisted_redo_record", val, 0644)) + require.NoError(t, err) + require.NoError(t, ioutil.WriteFile("testdata/persisted_redo_record", val, 0644)) } func TestReadExistingRedoRecord(t *testing.T) { b, err := ioutil.ReadFile("testdata/persisted_redo_record") - assert.NoError(t, err) + require.NoError(t, err) rec, err := decodeRedologVal(b) - assert.NoError(t, err) + require.NoError(t, err) t.Logf("rec = %s", spew.Sdump(rec)) - assert.Equal(t, constructSampleRedoRecord(), rec) + require.Equal(t, constructSampleRedoRecord(), rec) } func constructSampleRedoRecord() *redoRecord { diff --git a/core/ledger/kvledger/txmgmt/statedb/statecouchdb/statecouchdb_test.go b/core/ledger/kvledger/txmgmt/statedb/statecouchdb/statecouchdb_test.go index 0a04e04c980..9bb734297c0 100644 --- a/core/ledger/kvledger/txmgmt/statedb/statecouchdb/statecouchdb_test.go +++ b/core/ledger/kvledger/txmgmt/statedb/statecouchdb/statecouchdb_test.go @@ -7,6 +7,7 @@ SPDX-License-Identifier: Apache-2.0 package statecouchdb import ( + "errors" "fmt" "io/ioutil" "os" @@ -23,8 +24,6 @@ import ( "github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/statedb" "github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/statedb/commontests" "github.com/hyperledger/fabric/core/ledger/kvledger/txmgmt/statedb/mock" - "github.com/pkg/errors" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -509,22 +508,22 @@ func TestUtilityFunctions(t *testing.T) { defer vdbEnv.cleanup() db, err := vdbEnv.DBProvider.GetDBHandle("testutilityfunctions", nil) - assert.NoError(t, err) + require.NoError(t, err) // BytesKeySupported should be false for CouchDB byteKeySupported := db.BytesKeySupported() - assert.False(t, byteKeySupported) + require.False(t, byteKeySupported) // ValidateKeyValue should return nil for a valid key and value err = db.ValidateKeyValue("testKey", []byte("Some random bytes")) - assert.Nil(t, err) + require.Nil(t, err) // ValidateKeyValue should return an error for a key that is not a utf-8 valid string err = db.ValidateKeyValue(string([]byte{0xff, 0xfe, 0xfd}), []byte("Some random bytes")) - assert.Error(t, err, "ValidateKey should have thrown an error for an invalid utf-8 string") + require.Error(t, err, "ValidateKey should have thrown an error for an invalid utf-8 string") // ValidateKeyValue should return an error for a key that is an empty string - assert.EqualError(t, db.ValidateKeyValue("", []byte("validValue")), + require.EqualError(t, db.ValidateKeyValue("", []byte("validValue")), "invalid key. Empty string is not supported as a key by couchdb") reservedFields := []string{"~version", "_id", "_test"} @@ -534,7 +533,7 @@ func TestUtilityFunctions(t *testing.T) { for _, reservedField := range reservedFields { testVal := fmt.Sprintf(`{"%s":"dummyVal"}`, reservedField) err = db.ValidateKeyValue("testKey", []byte(testVal)) - assert.Error(t, err, fmt.Sprintf( + require.Error(t, err, fmt.Sprintf( "ValidateKey should have thrown an error for a json value %s, as contains one of the reserved fields", testVal)) } @@ -543,13 +542,13 @@ func TestUtilityFunctions(t *testing.T) { for _, reservedField := range reservedFields { testVal := fmt.Sprintf(`{"data.%s":"dummyVal"}`, reservedField) err = db.ValidateKeyValue("testKey", []byte(testVal)) - assert.NoError(t, err, fmt.Sprintf( + require.NoError(t, err, fmt.Sprintf( "ValidateKey should not have thrown an error the json value %s since the reserved field was not at the top level", testVal)) } // ValidateKeyValue should return an error for a key that begins with an underscore err = db.ValidateKeyValue("_testKey", []byte("testValue")) - assert.Error(t, err, "ValidateKey should have thrown an error for a key that begins with an underscore") + require.Error(t, err, "ValidateKey should have thrown an error for a key that begins with an underscore") } @@ -559,7 +558,7 @@ func TestInvalidJSONFields(t *testing.T) { defer vdbEnv.cleanup() db, err := vdbEnv.DBProvider.GetDBHandle("testinvalidfields", nil) - assert.NoError(t, err) + require.NoError(t, err) db.Open() defer db.Close() @@ -570,7 +569,7 @@ func TestInvalidJSONFields(t *testing.T) { savePoint := version.NewHeight(1, 2) err = db.ApplyUpdates(batch, savePoint) - assert.Error(t, err, "Invalid field _id should have thrown an error") + require.Error(t, err, "Invalid field _id should have thrown an error") batch = statedb.NewUpdateBatch() jsonValue1 = `{"_rev":"rev1","asset_name":"marble1","color":"blue","size":1,"owner":"tom"}` @@ -578,7 +577,7 @@ func TestInvalidJSONFields(t *testing.T) { savePoint = version.NewHeight(1, 2) err = db.ApplyUpdates(batch, savePoint) - assert.Error(t, err, "Invalid field _rev should have thrown an error") + require.Error(t, err, "Invalid field _rev should have thrown an error") batch = statedb.NewUpdateBatch() jsonValue1 = `{"_deleted":"true","asset_name":"marble1","color":"blue","size":1,"owner":"tom"}` @@ -586,7 +585,7 @@ func TestInvalidJSONFields(t *testing.T) { savePoint = version.NewHeight(1, 2) err = db.ApplyUpdates(batch, savePoint) - assert.Error(t, err, "Invalid field _deleted should have thrown an error") + require.Error(t, err, "Invalid field _deleted should have thrown an error") batch = statedb.NewUpdateBatch() jsonValue1 = `{"~version":"v1","asset_name":"marble1","color":"blue","size":1,"owner":"tom"}` @@ -594,7 +593,7 @@ func TestInvalidJSONFields(t *testing.T) { savePoint = version.NewHeight(1, 2) err = db.ApplyUpdates(batch, savePoint) - assert.Error(t, err, "Invalid field ~version should have thrown an error") + require.Error(t, err, "Invalid field ~version should have thrown an error") } func TestDebugFunctions(t *testing.T) { @@ -606,7 +605,7 @@ func TestDebugFunctions(t *testing.T) { loadKeys = append(loadKeys, &compositeKey3) compositeKey4 := statedb.CompositeKey{Namespace: "ns", Key: "key4"} loadKeys = append(loadKeys, &compositeKey4) - assert.Equal(t, "[ns,key3],[ns,key4]", printCompositeKeys(loadKeys)) + require.Equal(t, "[ns,key3],[ns,key4]", printCompositeKeys(loadKeys)) } @@ -615,7 +614,7 @@ func TestHandleChaincodeDeploy(t *testing.T) { defer vdbEnv.cleanup() db, err := vdbEnv.DBProvider.GetDBHandle("testinit", nil) - assert.NoError(t, err) + require.NoError(t, err) db.Open() defer db.Close() batch := statedb.NewUpdateBatch() @@ -669,43 +668,43 @@ func TestHandleChaincodeDeploy(t *testing.T) { queryString := `{"selector":{"owner":"fred"}}` _, err = db.ExecuteQuery("ns1", queryString) - assert.NoError(t, err) + require.NoError(t, err) //Create a query with a sort queryString = `{"selector":{"owner":"fred"}, "sort": [{"size": "desc"}]}` _, err = db.ExecuteQuery("ns1", queryString) - assert.Error(t, err, "Error should have been thrown for a missing index") + require.Error(t, err, "Error should have been thrown for a missing index") indexCapable, ok := db.(statedb.IndexCapable) if !ok { t.Fatalf("Couchdb state impl is expected to implement interface `statedb.IndexCapable`") } - assert.NoError(t, indexCapable.ProcessIndexesForChaincodeDeploy("ns1", indexData)) + require.NoError(t, indexCapable.ProcessIndexesForChaincodeDeploy("ns1", indexData)) queryString = `{"selector":{"owner":"fred"}, "sort": [{"size": "desc"}]}` queryUsingIndex := func() bool { _, err = db.ExecuteQuery("ns1", queryString) return err == nil } - assert.Eventually(t, queryUsingIndex, 2*time.Second, 100*time.Millisecond, "error executing query with sort") + require.Eventually(t, queryUsingIndex, 2*time.Second, 100*time.Millisecond, "error executing query with sort") //Query namespace "ns2", index is only created in "ns1". This should return an error. _, err = db.ExecuteQuery("ns2", queryString) - assert.Error(t, err, "Error should have been thrown for a missing index") + require.Error(t, err, "Error should have been thrown for a missing index") } func TestTryCastingToJSON(t *testing.T) { sampleJSON := []byte(`{"a":"A", "b":"B"}`) isJSON, jsonVal := tryCastingToJSON(sampleJSON) - assert.True(t, isJSON) - assert.Equal(t, "A", jsonVal["a"]) - assert.Equal(t, "B", jsonVal["b"]) + require.True(t, isJSON) + require.Equal(t, "A", jsonVal["a"]) + require.Equal(t, "B", jsonVal["b"]) sampleNonJSON := []byte(`This is not a json`) isJSON, _ = tryCastingToJSON(sampleNonJSON) - assert.False(t, isJSON) + require.False(t, isJSON) } func TestIndexDeploymentWithOrderAndBadSyntax(t *testing.T) { @@ -713,7 +712,7 @@ func TestIndexDeploymentWithOrderAndBadSyntax(t *testing.T) { vdbEnv.init(t, nil) defer vdbEnv.cleanup() db, err := vdbEnv.DBProvider.GetDBHandle(channelName, nil) - assert.NoError(t, err) + require.NoError(t, err) db.Open() defer db.Close() @@ -740,21 +739,21 @@ func TestIndexDeploymentWithOrderAndBadSyntax(t *testing.T) { // index fields, the later would replace the former, i.e., index would be created on size field // rather than the color field. Further, the index with a bad syntax would not stop the processing // of other valid indexes. - assert.NoError(t, indexCapable.ProcessIndexesForChaincodeDeploy("ns1", indexData)) + require.NoError(t, indexCapable.ProcessIndexesForChaincodeDeploy("ns1", indexData)) queryString := `{"selector":{"owner":"fred"}, "sort": [{"docType": "desc"}]}` queryUsingIndex := func() bool { _, err = db.ExecuteQuery("ns1", queryString) return err == nil } - assert.Eventually(t, queryUsingIndex, 2*time.Second, 100*time.Millisecond, "error executing query with sort") + require.Eventually(t, queryUsingIndex, 2*time.Second, 100*time.Millisecond, "error executing query with sort") queryString = `{"selector":{"owner":"fred"}, "sort": [{"size": "desc"}]}` queryUsingIndex = func() bool { _, err = db.ExecuteQuery("ns1", queryString) return err == nil } - assert.Eventually(t, queryUsingIndex, 2*time.Second, 100*time.Millisecond, "error executing query with sort") + require.Eventually(t, queryUsingIndex, 2*time.Second, 100*time.Millisecond, "error executing query with sort") // though the indexColorSortName.json is processed before indexSizeSortName.json as per the order, // the later would replace the former as the index names are the same. Hence, a query using the color @@ -764,7 +763,7 @@ func TestIndexDeploymentWithOrderAndBadSyntax(t *testing.T) { _, err = db.ExecuteQuery("ns1", queryString) return err == nil } - assert.Never(t, queryUsingIndex, 2*time.Second, 100*time.Millisecond, "error should have occurred as there is no index on color field") + require.Never(t, queryUsingIndex, 2*time.Second, 100*time.Millisecond, "error should have occurred as there is no index on color field") } func TestIsBulkOptimizable(t *testing.T) { @@ -789,7 +788,7 @@ func TestPaginatedQuery(t *testing.T) { defer vdbEnv.cleanup() db, err := vdbEnv.DBProvider.GetDBHandle("testpaginatedquery", nil) - assert.NoError(t, err) + require.NoError(t, err) db.Open() defer db.Close() @@ -889,7 +888,7 @@ func TestPaginatedQuery(t *testing.T) { queryString := `{"selector":{"color":"red"}}` _, err = db.ExecuteQuery("ns1", queryString) - assert.NoError(t, err) + require.NoError(t, err) indexCapable, ok := db.(statedb.IndexCapable) if !ok { @@ -904,20 +903,20 @@ func TestPaginatedQuery(t *testing.T) { // Query should complete without error _, err = db.ExecuteQuery("ns1", queryString) - assert.NoError(t, err) + require.NoError(t, err) // Test explicit paging // Execute 3 page queries, there are 28 records with color red, use page size 10 returnKeys := []string{"key2", "key3", "key4", "key6", "key8", "key12", "key13", "key14", "key15", "key16"} bookmark, err := executeQuery(t, db, "ns1", queryString, "", int32(10), returnKeys) - assert.NoError(t, err) + require.NoError(t, err) returnKeys = []string{"key17", "key18", "key19", "key20", "key22", "key24", "key25", "key26", "key28", "key29"} bookmark, err = executeQuery(t, db, "ns1", queryString, bookmark, int32(10), returnKeys) - assert.NoError(t, err) + require.NoError(t, err) returnKeys = []string{"key30", "key32", "key33", "key34", "key35", "key37", "key39", "key40"} _, err = executeQuery(t, db, "ns1", queryString, bookmark, int32(10), returnKeys) - assert.NoError(t, err) + require.NoError(t, err) // Test explicit paging // Increase pagesize to 50, should return all values @@ -925,31 +924,31 @@ func TestPaginatedQuery(t *testing.T) { "key16", "key17", "key18", "key19", "key20", "key22", "key24", "key25", "key26", "key28", "key29", "key30", "key32", "key33", "key34", "key35", "key37", "key39", "key40"} _, err = executeQuery(t, db, "ns1", queryString, "", int32(50), returnKeys) - assert.NoError(t, err) + require.NoError(t, err) // Test explicit paging // Pagesize is 10, so all 28 records should be return in 3 "pages" returnKeys = []string{"key2", "key3", "key4", "key6", "key8", "key12", "key13", "key14", "key15", "key16"} bookmark, err = executeQuery(t, db, "ns1", queryString, "", int32(10), returnKeys) - assert.NoError(t, err) + require.NoError(t, err) returnKeys = []string{"key17", "key18", "key19", "key20", "key22", "key24", "key25", "key26", "key28", "key29"} bookmark, err = executeQuery(t, db, "ns1", queryString, bookmark, int32(10), returnKeys) - assert.NoError(t, err) + require.NoError(t, err) returnKeys = []string{"key30", "key32", "key33", "key34", "key35", "key37", "key39", "key40"} _, err = executeQuery(t, db, "ns1", queryString, bookmark, int32(10), returnKeys) - assert.NoError(t, err) + require.NoError(t, err) // Test implicit paging returnKeys = []string{"key2", "key3", "key4", "key6", "key8", "key12", "key13", "key14", "key15", "key16", "key17", "key18", "key19", "key20", "key22", "key24", "key25", "key26", "key28", "key29", "key30", "key32", "key33", "key34", "key35", "key37", "key39", "key40"} _, err = executeQuery(t, db, "ns1", queryString, "", int32(0), returnKeys) - assert.NoError(t, err) + require.NoError(t, err) // pagesize greater than querysize will execute with implicit paging returnKeys = []string{"key2", "key3", "key4", "key6", "key8", "key12", "key13", "key14", "key15", "key16"} _, err = executeQuery(t, db, "ns1", queryString, "", int32(10), returnKeys) - assert.NoError(t, err) + require.NoError(t, err) } func executeQuery(t *testing.T, db statedb.VersionedDB, namespace, query, bookmark string, pageSize int32, returnKeys []string) (string, error) { @@ -989,9 +988,9 @@ func TestRangeScanWithCouchInternalDocsPresent(t *testing.T) { vdbEnv.init(t, nil) defer vdbEnv.cleanup() db, err := vdbEnv.DBProvider.GetDBHandle("testrangescanfiltercouchinternaldocs", nil) - assert.NoError(t, err) + require.NoError(t, err) couchDatabse, err := db.(*VersionedDB).getNamespaceDBHandle("ns") - assert.NoError(t, err) + require.NoError(t, err) db.Open() defer db.Close() _, err = couchDatabse.createIndex(`{ @@ -1000,7 +999,7 @@ func TestRangeScanWithCouchInternalDocsPresent(t *testing.T) { "name" : "indexAssetName", "type" : "json" }`) - assert.NoError(t, err) + require.NoError(t, err) _, err = couchDatabse.createIndex(`{ "index" : {"fields" : ["assetValue"]}, @@ -1008,7 +1007,7 @@ func TestRangeScanWithCouchInternalDocsPresent(t *testing.T) { "name" : "indexAssetValue", "type" : "json" }`) - assert.NoError(t, err) + require.NoError(t, err) batch := statedb.NewUpdateBatch() for i := 1; i <= 3; i++ { @@ -1019,33 +1018,33 @@ func TestRangeScanWithCouchInternalDocsPresent(t *testing.T) { batch.Put("ns", keyGreaterThanDesignDoc, []byte(jsonValue), version.NewHeight(1, uint64(i))) } db.ApplyUpdates(batch, version.NewHeight(2, 2)) - assert.NoError(t, err) + require.NoError(t, err) // The Keys in db are in this order // Key-1, Key-2, Key-3,_design/indexAssetNam, _design/indexAssetValue, key-1, key-2, key-3 // query different ranges and verify results s, err := newQueryScanner("ns", couchDatabse, "", 3, 3, "", "", "") - assert.NoError(t, err) + require.NoError(t, err) assertQueryResults(t, s.resultsInfo.results, []string{"Key-1", "Key-2", "Key-3"}) - assert.Equal(t, "key-1", s.queryDefinition.startKey) + require.Equal(t, "key-1", s.queryDefinition.startKey) s, err = newQueryScanner("ns", couchDatabse, "", 4, 4, "", "", "") - assert.NoError(t, err) + require.NoError(t, err) assertQueryResults(t, s.resultsInfo.results, []string{"Key-1", "Key-2", "Key-3", "key-1"}) - assert.Equal(t, "key-2", s.queryDefinition.startKey) + require.Equal(t, "key-2", s.queryDefinition.startKey) s, err = newQueryScanner("ns", couchDatabse, "", 2, 2, "", "", "") - assert.NoError(t, err) + require.NoError(t, err) assertQueryResults(t, s.resultsInfo.results, []string{"Key-1", "Key-2"}) - assert.Equal(t, "Key-3", s.queryDefinition.startKey) + require.Equal(t, "Key-3", s.queryDefinition.startKey) s.getNextStateRangeScanResults() assertQueryResults(t, s.resultsInfo.results, []string{"Key-3", "key-1"}) - assert.Equal(t, "key-2", s.queryDefinition.startKey) + require.Equal(t, "key-2", s.queryDefinition.startKey) s, err = newQueryScanner("ns", couchDatabse, "", 2, 2, "", "_", "") - assert.NoError(t, err) + require.NoError(t, err) assertQueryResults(t, s.resultsInfo.results, []string{"key-1", "key-2"}) - assert.Equal(t, "key-3", s.queryDefinition.startKey) + require.Equal(t, "key-3", s.queryDefinition.startKey) } func assertQueryResults(t *testing.T, results []*queryResult, expectedIds []string) { @@ -1053,7 +1052,7 @@ func assertQueryResults(t *testing.T, results []*queryResult, expectedIds []stri for _, res := range results { actualIds = append(actualIds, res.id) } - assert.Equal(t, expectedIds, actualIds) + require.Equal(t, expectedIds, actualIds) } func TestFormatCheck(t *testing.T) { diff --git a/core/ledger/kvledger/txmgmt/statedb/statecouchdb/version_cache_test.go b/core/ledger/kvledger/txmgmt/statedb/statecouchdb/version_cache_test.go index 8a811c531bb..b0bbf7ba043 100644 --- a/core/ledger/kvledger/txmgmt/statedb/statecouchdb/version_cache_test.go +++ b/core/ledger/kvledger/txmgmt/statedb/statecouchdb/version_cache_test.go @@ -10,7 +10,7 @@ import ( "testing" "github.com/hyperledger/fabric/core/ledger/internal/version" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestVersionCache(t *testing.T) { @@ -21,18 +21,18 @@ func TestVersionCache(t *testing.T) { verCache.setVerAndRev("ns2", "key2", version.NewHeight(2, 2), "rev2") ver, found := verCache.getVersion("ns1", "key1") - assert.True(t, found) - assert.Equal(t, ver1, ver) + require.True(t, found) + require.Equal(t, ver1, ver) ver, found = verCache.getVersion("ns2", "key2") - assert.True(t, found) - assert.Equal(t, ver2, ver) + require.True(t, found) + require.Equal(t, ver2, ver) ver, found = verCache.getVersion("ns1", "key3") - assert.False(t, found) - assert.Nil(t, ver) + require.False(t, found) + require.Nil(t, ver) ver, found = verCache.getVersion("ns3", "key4") - assert.False(t, found) - assert.Nil(t, ver) + require.False(t, found) + require.Nil(t, ver) }