How to use Save method of config Package

Best Testkube code snippet using config.Save

couchdb_test.go

Source:couchdb_test.go Github

copy

Full Screen

...153 //Test deleteIndex with bad connection154 err = badDB.deleteIndex("", "")155 require.Error(t, err, "Error should have been thrown with deleteIndex and invalid connection")156}157func TestDBCreateSaveWithoutRevision(t *testing.T) {158 config := testConfig()159 couchDBEnv.startCouchDB(t)160 config.Address = couchDBEnv.couchAddress161 defer couchDBEnv.cleanup(config)162 database := "testdbcreatesavewithoutrevision"163 //create a new instance and database object164 couchInstance, err := createCouchInstance(config, &disabled.Provider{})165 require.NoError(t, err, "Error when trying to create couch instance")166 db := couchDatabase{couchInstance: couchInstance, dbName: database}167 //create a new database168 errdb := db.createDatabaseIfNotExist()169 require.NoError(t, errdb, "Error when trying to create database")170 //Save the test document171 _, saveerr := db.saveDoc("2", "", &couchDoc{jsonValue: assetJSON, attachments: nil})172 require.NoError(t, saveerr, "Error when trying to save a document")173}174func TestDBCreateEnsureFullCommit(t *testing.T) {175 config := testConfig()176 couchDBEnv.startCouchDB(t)177 config.Address = couchDBEnv.couchAddress178 defer couchDBEnv.cleanup(config)179 database := "testdbensurefullcommit"180 //create a new instance and database object181 couchInstance, err := createCouchInstance(config, &disabled.Provider{})182 require.NoError(t, err, "Error when trying to create couch instance")183 db := couchDatabase{couchInstance: couchInstance, dbName: database}184 //create a new database185 errdb := db.createDatabaseIfNotExist()186 require.NoError(t, errdb, "Error when trying to create database")187 //Save the test document188 _, saveerr := db.saveDoc("2", "", &couchDoc{jsonValue: assetJSON, attachments: nil})189 require.NoError(t, saveerr, "Error when trying to save a document")190}191func TestIsEmpty(t *testing.T) {192 config := testConfig()193 couchDBEnv.startCouchDB(t)194 config.Address = couchDBEnv.couchAddress195 defer couchDBEnv.cleanup(config)196 couchInstance, err := createCouchInstance(config, &disabled.Provider{})197 require.NoError(t, err)198 ignore := []string{"_global_changes", "_replicator", "_users", "fabric__internal"}199 isEmpty, err := couchInstance.isEmpty(ignore)200 require.NoError(t, err)201 require.True(t, isEmpty)202 testdbs := []string{"testdb1", "testdb2"}203 couchDBEnv.cleanup(config)204 for _, d := range testdbs {205 db := couchDatabase{couchInstance: couchInstance, dbName: d}206 require.NoError(t, db.createDatabaseIfNotExist())207 }208 isEmpty, err = couchInstance.isEmpty(ignore)209 require.NoError(t, err)210 require.False(t, isEmpty)211 ignore = append(ignore, "testdb1")212 isEmpty, err = couchInstance.isEmpty(ignore)213 require.NoError(t, err)214 require.False(t, isEmpty)215 ignore = append(ignore, "testdb2")216 isEmpty, err = couchInstance.isEmpty(ignore)217 require.NoError(t, err)218 require.True(t, isEmpty)219 configCopy := *config220 configCopy.Address = "junk"221 configCopy.MaxRetries = 0222 couchInstance.conf = &configCopy223 _, err = couchInstance.isEmpty(ignore)224 require.Error(t, err)225 require.Regexp(t, `unable to connect to CouchDB, check the hostname and port: http error calling couchdb: Get "?http://junk/_all_dbs"?`, err.Error())226}227func TestDBBadDatabaseName(t *testing.T) {228 config := testConfig()229 couchDBEnv.startCouchDB(t)230 config.Address = couchDBEnv.couchAddress231 defer couchDBEnv.cleanup(config)232 //create a new instance and database object using a valid database name mixed case233 couchInstance, err := createCouchInstance(config, &disabled.Provider{})234 require.NoError(t, err, "Error when trying to create couch instance")235 _, dberr := createCouchDatabase(couchInstance, "testDB")236 require.Error(t, dberr, "Error should have been thrown for an invalid db name")237 //create a new instance and database object using a valid database name letters and numbers238 couchInstance, err = createCouchInstance(config, &disabled.Provider{})239 require.NoError(t, err, "Error when trying to create couch instance")240 _, dberr = createCouchDatabase(couchInstance, "test132")241 require.NoError(t, dberr, "Error when testing a valid database name")242 //create a new instance and database object using a valid database name - special characters243 couchInstance, err = createCouchInstance(config, &disabled.Provider{})244 require.NoError(t, err, "Error when trying to create couch instance")245 _, dberr = createCouchDatabase(couchInstance, "test1234~!@#$%^&*()[]{}.")246 require.Error(t, dberr, "Error should have been thrown for an invalid db name")247 //create a new instance and database object using a invalid database name - too long /*248 couchInstance, err = createCouchInstance(config, &disabled.Provider{})249 require.NoError(t, err, "Error when trying to create couch instance")250 _, dberr = createCouchDatabase(couchInstance, "a12345678901234567890123456789012345678901234"+251 "56789012345678901234567890123456789012345678901234567890123456789012345678901234567890"+252 "12345678901234567890123456789012345678901234567890123456789012345678901234567890123456"+253 "78901234567890123456789012345678901234567890")254 require.Error(t, dberr, "Error should have been thrown for invalid database name")255}256func TestDBBadConnection(t *testing.T) {257 //create a new instance and database object258 //Limit the maxRetriesOnStartup to 3 in order to reduce time for the failure259 config := &ledger.CouchDBConfig{260 Address: badConnectURL,261 Username: "admin",262 Password: "adminpw",263 MaxRetries: 3,264 MaxRetriesOnStartup: 3,265 RequestTimeout: 35 * time.Second,266 }267 _, err := createCouchInstance(config, &disabled.Provider{})268 require.Error(t, err, "Error should have been thrown for a bad connection")269}270func TestBadDBCredentials(t *testing.T) {271 config := testConfig()272 couchDBEnv.startCouchDB(t)273 config.Address = couchDBEnv.couchAddress274 defer couchDBEnv.cleanup(config)275 badConfig := testConfig()276 badConfig.Address = config.Address277 badConfig.Username = "fred"278 badConfig.Password = "fred"279 //create a new instance and database object280 _, err := createCouchInstance(badConfig, &disabled.Provider{})281 require.Error(t, err, "Error should have been thrown for bad credentials")282}283func TestDBCreateDatabaseAndPersist(t *testing.T) {284 config := testConfig()285 couchDBEnv.startCouchDB(t)286 config.Address = couchDBEnv.couchAddress287 defer couchDBEnv.cleanup(config)288 //Test create and persist with default configured maxRetries289 testDBCreateDatabaseAndPersist(t, config)290 couchDBEnv.cleanup(config)291 //Test create and persist with 0 retries292 configCopy := *config293 configCopy.MaxRetries = 0294 testDBCreateDatabaseAndPersist(t, &configCopy)295 couchDBEnv.cleanup(config)296 //Test batch operations with default configured maxRetries297 testBatchBatchOperations(t, config)298 couchDBEnv.cleanup(config)299 //Test batch operations with 0 retries300 testBatchBatchOperations(t, config)301}302func testDBCreateDatabaseAndPersist(t *testing.T, config *ledger.CouchDBConfig) {303 database := "testdbcreatedatabaseandpersist"304 //create a new instance and database object305 couchInstance, err := createCouchInstance(config, &disabled.Provider{})306 require.NoError(t, err, "Error when trying to create couch instance")307 db := couchDatabase{couchInstance: couchInstance, dbName: database}308 //create a new database309 errdb := db.createDatabaseIfNotExist()310 require.NoError(t, errdb, "Error when trying to create database")311 //Retrieve the info for the new database and make sure the name matches312 dbResp, _, errdb := db.getDatabaseInfo()313 require.NoError(t, errdb, "Error when trying to retrieve database information")314 require.Equal(t, database, dbResp.DbName)315 //Save the test document316 _, saveerr := db.saveDoc("idWith/slash", "", &couchDoc{jsonValue: assetJSON, attachments: nil})317 require.NoError(t, saveerr, "Error when trying to save a document")318 //Retrieve the test document319 dbGetResp, _, geterr := db.readDoc("idWith/slash")320 require.NoError(t, geterr, "Error when trying to retrieve a document")321 //Unmarshal the document to Asset structure322 assetResp := &Asset{}323 geterr = json.Unmarshal(dbGetResp.jsonValue, &assetResp)324 require.NoError(t, geterr, "Error when trying to retrieve a document")325 //Verify the owner retrieved matches326 require.Equal(t, "jerry", assetResp.Owner)327 //Save the test document328 _, saveerr = db.saveDoc("1", "", &couchDoc{jsonValue: assetJSON, attachments: nil})329 require.NoError(t, saveerr, "Error when trying to save a document")330 //Retrieve the test document331 dbGetResp, _, geterr = db.readDoc("1")332 require.NoError(t, geterr, "Error when trying to retrieve a document")333 //Unmarshal the document to Asset structure334 assetResp = &Asset{}335 geterr = json.Unmarshal(dbGetResp.jsonValue, &assetResp)336 require.NoError(t, geterr, "Error when trying to retrieve a document")337 //Verify the owner retrieved matches338 require.Equal(t, "jerry", assetResp.Owner)339 //Change owner to bob340 assetResp.Owner = "bob"341 //create a byte array of the JSON342 assetDocUpdated, _ := json.Marshal(assetResp)343 //Save the updated test document344 _, saveerr = db.saveDoc("1", "", &couchDoc{jsonValue: assetDocUpdated, attachments: nil})345 require.NoError(t, saveerr, "Error when trying to save the updated document")346 //Retrieve the updated test document347 dbGetResp, _, geterr = db.readDoc("1")348 require.NoError(t, geterr, "Error when trying to retrieve a document")349 //Unmarshal the document to Asset structure350 assetResp = &Asset{}351 require.NoError(t, json.Unmarshal(dbGetResp.jsonValue, &assetResp))352 //Assert that the update was saved and retrieved353 require.Equal(t, "bob", assetResp.Owner)354 testBytes2 := []byte(`test attachment 2`)355 attachment2 := &attachmentInfo{}356 attachment2.AttachmentBytes = testBytes2357 attachment2.ContentType = "application/octet-stream"358 attachment2.Name = "data"359 attachments2 := []*attachmentInfo{}360 attachments2 = append(attachments2, attachment2)361 //Save the test document with an attachment362 _, saveerr = db.saveDoc("2", "", &couchDoc{jsonValue: nil, attachments: attachments2})363 require.NoError(t, saveerr, "Error when trying to save a document")364 //Retrieve the test document with attachments365 dbGetResp, _, geterr = db.readDoc("2")366 require.NoError(t, geterr, "Error when trying to retrieve a document")367 //verify the text from the attachment is correct368 testattach := dbGetResp.attachments[0].AttachmentBytes369 require.Equal(t, testBytes2, testattach)370 testBytes3 := []byte{}371 attachment3 := &attachmentInfo{}372 attachment3.AttachmentBytes = testBytes3373 attachment3.ContentType = "application/octet-stream"374 attachment3.Name = "data"375 attachments3 := []*attachmentInfo{}376 attachments3 = append(attachments3, attachment3)377 //Save the test document with a zero length attachment378 _, saveerr = db.saveDoc("3", "", &couchDoc{jsonValue: nil, attachments: attachments3})379 require.NoError(t, saveerr, "Error when trying to save a document")380 //Retrieve the test document with attachments381 dbGetResp, _, geterr = db.readDoc("3")382 require.NoError(t, geterr, "Error when trying to retrieve a document")383 //verify the text from the attachment is correct, zero bytes384 testattach = dbGetResp.attachments[0].AttachmentBytes385 require.Equal(t, testBytes3, testattach)386 testBytes4a := []byte(`test attachment 4a`)387 attachment4a := &attachmentInfo{}388 attachment4a.AttachmentBytes = testBytes4a389 attachment4a.ContentType = "application/octet-stream"390 attachment4a.Name = "data1"391 testBytes4b := []byte(`test attachment 4b`)392 attachment4b := &attachmentInfo{}393 attachment4b.AttachmentBytes = testBytes4b394 attachment4b.ContentType = "application/octet-stream"395 attachment4b.Name = "data2"396 attachments4 := []*attachmentInfo{}397 attachments4 = append(attachments4, attachment4a)398 attachments4 = append(attachments4, attachment4b)399 //Save the updated test document with multiple attachments400 _, saveerr = db.saveDoc("4", "", &couchDoc{jsonValue: assetJSON, attachments: attachments4})401 require.NoError(t, saveerr, "Error when trying to save the updated document")402 //Retrieve the test document with attachments403 dbGetResp, _, geterr = db.readDoc("4")404 require.NoError(t, geterr, "Error when trying to retrieve a document")405 for _, attach4 := range dbGetResp.attachments {406 currentName := attach4.Name407 if currentName == "data1" {408 require.Equal(t, testBytes4a, attach4.AttachmentBytes)409 }410 if currentName == "data2" {411 require.Equal(t, testBytes4b, attach4.AttachmentBytes)412 }413 }414 testBytes5a := []byte(`test attachment 5a`)415 attachment5a := &attachmentInfo{}416 attachment5a.AttachmentBytes = testBytes5a417 attachment5a.ContentType = "application/octet-stream"418 attachment5a.Name = "data1"419 testBytes5b := []byte{}420 attachment5b := &attachmentInfo{}421 attachment5b.AttachmentBytes = testBytes5b422 attachment5b.ContentType = "application/octet-stream"423 attachment5b.Name = "data2"424 attachments5 := []*attachmentInfo{}425 attachments5 = append(attachments5, attachment5a)426 attachments5 = append(attachments5, attachment5b)427 //Save the updated test document with multiple attachments and zero length attachments428 _, saveerr = db.saveDoc("5", "", &couchDoc{jsonValue: assetJSON, attachments: attachments5})429 require.NoError(t, saveerr, "Error when trying to save the updated document")430 //Retrieve the test document with attachments431 dbGetResp, _, geterr = db.readDoc("5")432 require.NoError(t, geterr, "Error when trying to retrieve a document")433 for _, attach5 := range dbGetResp.attachments {434 currentName := attach5.Name435 if currentName == "data1" {436 require.Equal(t, testBytes5a, attach5.AttachmentBytes)437 }438 if currentName == "data2" {439 require.Equal(t, testBytes5b, attach5.AttachmentBytes)440 }441 }442 //Attempt to save the document with an invalid id443 _, saveerr = db.saveDoc(string([]byte{0xff, 0xfe, 0xfd}), "", &couchDoc{jsonValue: assetJSON, attachments: nil})444 require.Error(t, saveerr, "Error should have been thrown when saving a document with an invalid ID")445 //Attempt to read a document with an invalid id446 _, _, readerr := db.readDoc(string([]byte{0xff, 0xfe, 0xfd}))447 require.Error(t, readerr, "Error should have been thrown when reading a document with an invalid ID")448 //Drop the database449 errdbdrop := db.dropDatabase()450 require.NoError(t, errdbdrop, "Error dropping database")451 //Make sure an error is thrown for getting info for a missing database452 _, _, errdbinfo := db.getDatabaseInfo()453 require.Error(t, errdbinfo, "Error should have been thrown for missing database")454 //Attempt to save a document to a deleted database455 _, saveerr = db.saveDoc("6", "", &couchDoc{jsonValue: assetJSON, attachments: nil})456 require.Error(t, saveerr, "Error should have been thrown while attempting to save to a deleted database")457 //Attempt to read from a deleted database458 _, _, geterr = db.readDoc("6")459 require.NoError(t, geterr, "Error should not have been thrown for a missing database, nil value is returned")460}461func TestDBRequestTimeout(t *testing.T) {462 config := testConfig()463 couchDBEnv.startCouchDB(t)464 config.Address = couchDBEnv.couchAddress465 defer couchDBEnv.cleanup(config)466 //create a new instance and database object with a timeout that will fail467 //Also use a maxRetriesOnStartup=3 to reduce the number of retries468 configCopy := *config469 configCopy.MaxRetriesOnStartup = 3470 //create an impossibly short timeout471 impossibleTimeout := time.Nanosecond472 configCopy.RequestTimeout = impossibleTimeout473 _, err := createCouchInstance(&configCopy, &disabled.Provider{})474 require.Error(t, err, "Error should have been thown while trying to create a couchdb instance with a connection timeout")475 //create a new instance and database object476 configCopy.MaxRetries = -1477 configCopy.MaxRetriesOnStartup = 3478 _, err = createCouchInstance(&configCopy, &disabled.Provider{})479 require.Error(t, err, "Error should have been thrown while attempting to create a database")480}481func TestDBTimeoutConflictRetry(t *testing.T) {482 config := testConfig()483 couchDBEnv.startCouchDB(t)484 config.Address = couchDBEnv.couchAddress485 defer couchDBEnv.cleanup(config)486 database := "testdbtimeoutretry"487 //create a new instance and database object488 configCopy := *config489 configCopy.MaxRetriesOnStartup = 3490 couchInstance, err := createCouchInstance(&configCopy, &disabled.Provider{})491 require.NoError(t, err, "Error when trying to create couch instance")492 db := couchDatabase{couchInstance: couchInstance, dbName: database}493 //create a new database494 errdb := db.createDatabaseIfNotExist()495 require.NoError(t, errdb, "Error when trying to create database")496 //Retrieve the info for the new database and make sure the name matches497 dbResp, _, errdb := db.getDatabaseInfo()498 require.NoError(t, errdb, "Error when trying to retrieve database information")499 require.Equal(t, database, dbResp.DbName)500 //Save the test document501 _, saveerr := db.saveDoc("1", "", &couchDoc{jsonValue: assetJSON, attachments: nil})502 require.NoError(t, saveerr, "Error when trying to save a document")503 //Retrieve the test document504 _, _, geterr := db.readDoc("1")505 require.NoError(t, geterr, "Error when trying to retrieve a document")506 //Save the test document with an invalid rev. This should cause a retry507 _, saveerr = db.saveDoc("1", "1-11111111111111111111111111111111", &couchDoc{jsonValue: assetJSON, attachments: nil})508 require.NoError(t, saveerr, "Error when trying to save a document with a revision conflict")509 //Delete the test document with an invalid rev. This should cause a retry510 deleteerr := db.deleteDoc("1", "1-11111111111111111111111111111111")511 require.NoError(t, deleteerr, "Error when trying to delete a document with a revision conflict")512}513func TestDBBadNumberOfRetries(t *testing.T) {514 config := testConfig()515 couchDBEnv.startCouchDB(t)516 config.Address = couchDBEnv.couchAddress517 defer couchDBEnv.cleanup(config)518 //create a new instance and database object519 configCopy := *config520 configCopy.MaxRetries = -1521 configCopy.MaxRetriesOnStartup = 3522 _, err := createCouchInstance(&configCopy, &disabled.Provider{})523 require.Error(t, err, "Error should have been thrown while attempting to create a database")524}525func TestDBBadJSON(t *testing.T) {526 config := testConfig()527 couchDBEnv.startCouchDB(t)528 config.Address = couchDBEnv.couchAddress529 defer couchDBEnv.cleanup(config)530 database := "testdbbadjson"531 //create a new instance and database object532 couchInstance, err := createCouchInstance(config, &disabled.Provider{})533 require.NoError(t, err, "Error when trying to create couch instance")534 db := couchDatabase{couchInstance: couchInstance, dbName: database}535 //create a new database536 errdb := db.createDatabaseIfNotExist()537 require.NoError(t, errdb, "Error when trying to create database")538 //Retrieve the info for the new database and make sure the name matches539 dbResp, _, errdb := db.getDatabaseInfo()540 require.NoError(t, errdb, "Error when trying to retrieve database information")541 require.Equal(t, database, dbResp.DbName)542 badJSON := []byte(`{"asset_name"}`)543 //Save the test document544 _, saveerr := db.saveDoc("1", "", &couchDoc{jsonValue: badJSON, attachments: nil})545 require.Error(t, saveerr, "Error should have been thrown for a bad JSON")546}547func TestPrefixScan(t *testing.T) {548 config := testConfig()549 couchDBEnv.startCouchDB(t)550 config.Address = couchDBEnv.couchAddress551 defer couchDBEnv.cleanup(config)552 database := "testprefixscan"553 //create a new instance and database object554 couchInstance, err := createCouchInstance(config, &disabled.Provider{})555 require.NoError(t, err, "Error when trying to create couch instance")556 db := couchDatabase{couchInstance: couchInstance, dbName: database}557 //create a new database558 errdb := db.createDatabaseIfNotExist()559 require.NoError(t, errdb, "Error when trying to create database")560 //Retrieve the info for the new database and make sure the name matches561 dbResp, _, errdb := db.getDatabaseInfo()562 require.NoError(t, errdb, "Error when trying to retrieve database information")563 require.Equal(t, database, dbResp.DbName)564 //Save documents565 for i := rune(0); i < 20; i++ {566 id1 := string([]rune{0, i, 0})567 id2 := string([]rune{0, i, 1})568 id3 := string([]rune{0, i, utf8.MaxRune - 1})569 _, saveerr := db.saveDoc(id1, "", &couchDoc{jsonValue: assetJSON, attachments: nil})570 require.NoError(t, saveerr, "Error when trying to save a document")571 _, saveerr = db.saveDoc(id2, "", &couchDoc{jsonValue: assetJSON, attachments: nil})572 require.NoError(t, saveerr, "Error when trying to save a document")573 _, saveerr = db.saveDoc(id3, "", &couchDoc{jsonValue: assetJSON, attachments: nil})574 require.NoError(t, saveerr, "Error when trying to save a document")575 }576 startKey := string([]rune{0, 10})577 endKey := startKey + string(utf8.MaxRune)578 _, _, geterr := db.readDoc(endKey)579 require.NoError(t, geterr, "Error when trying to get lastkey")580 resultsPtr, _, geterr := db.readDocRange(startKey, endKey, 1000)581 require.NoError(t, geterr, "Error when trying to perform a range scan")582 require.NotNil(t, resultsPtr)583 results := resultsPtr584 require.Equal(t, 3, len(results))585 require.Equal(t, string([]rune{0, 10, 0}), results[0].id)586 require.Equal(t, string([]rune{0, 10, 1}), results[1].id)587 require.Equal(t, string([]rune{0, 10, utf8.MaxRune - 1}), results[2].id)588 //Drop the database589 errdbdrop := db.dropDatabase()590 require.NoError(t, errdbdrop, "Error dropping database")591 // Drop again is not an error592 require.NoError(t, db.dropDatabase())593 //Retrieve the info for the new database and make sure the name matches594 _, _, errdbinfo := db.getDatabaseInfo()595 require.Error(t, errdbinfo, "Error should have been thrown for missing database")596}597func TestDBSaveAttachment(t *testing.T) {598 config := testConfig()599 couchDBEnv.startCouchDB(t)600 config.Address = couchDBEnv.couchAddress601 defer couchDBEnv.cleanup(config)602 database := "testdbsaveattachment"603 byteText := []byte(`This is a test document. This is only a test`)604 attachment := &attachmentInfo{}605 attachment.AttachmentBytes = byteText606 attachment.ContentType = "text/plain"607 attachment.Length = uint64(len(byteText))608 attachment.Name = "valueBytes"609 attachments := []*attachmentInfo{}610 attachments = append(attachments, attachment)611 //create a new instance and database object612 couchInstance, err := createCouchInstance(config, &disabled.Provider{})613 require.NoError(t, err, "Error when trying to create couch instance")614 db := couchDatabase{couchInstance: couchInstance, dbName: database}615 //create a new database616 errdb := db.createDatabaseIfNotExist()617 require.NoError(t, errdb, "Error when trying to create database")618 //Save the test document619 _, saveerr := db.saveDoc("10", "", &couchDoc{jsonValue: nil, attachments: attachments})620 require.NoError(t, saveerr, "Error when trying to save a document")621 //Attempt to retrieve the updated test document with attachments622 couchDoc, _, geterr2 := db.readDoc("10")623 require.NoError(t, geterr2, "Error when trying to retrieve a document with attachment")624 require.NotNil(t, couchDoc.attachments)625 require.Equal(t, byteText, couchDoc.attachments[0].AttachmentBytes)626 require.Equal(t, attachment.Length, couchDoc.attachments[0].Length)627}628func TestDBDeleteDocument(t *testing.T) {629 config := testConfig()630 couchDBEnv.startCouchDB(t)631 config.Address = couchDBEnv.couchAddress632 defer couchDBEnv.cleanup(config)633 database := "testdbdeletedocument"634 //create a new instance and database object635 couchInstance, err := createCouchInstance(config, &disabled.Provider{})636 require.NoError(t, err, "Error when trying to create couch instance")637 db := couchDatabase{couchInstance: couchInstance, dbName: database}638 //create a new database639 errdb := db.createDatabaseIfNotExist()640 require.NoError(t, errdb, "Error when trying to create database")641 //Save the test document642 _, saveerr := db.saveDoc("2", "", &couchDoc{jsonValue: assetJSON, attachments: nil})643 require.NoError(t, saveerr, "Error when trying to save a document")644 //Attempt to retrieve the test document645 _, _, readErr := db.readDoc("2")646 require.NoError(t, readErr, "Error when trying to retrieve a document with attachment")647 //Delete the test document648 deleteErr := db.deleteDoc("2", "")649 require.NoError(t, deleteErr, "Error when trying to delete a document")650 //Attempt to retrieve the test document651 readValue, _, _ := db.readDoc("2")652 require.Nil(t, readValue)653}654func TestDBDeleteNonExistingDocument(t *testing.T) {655 config := testConfig()656 couchDBEnv.startCouchDB(t)657 config.Address = couchDBEnv.couchAddress658 defer couchDBEnv.cleanup(config)659 database := "testdbdeletenonexistingdocument"660 //create a new instance and database object661 couchInstance, err := createCouchInstance(config, &disabled.Provider{})662 require.NoError(t, err, "Error when trying to create couch instance")663 db := couchDatabase{couchInstance: couchInstance, dbName: database}664 //create a new database665 errdb := db.createDatabaseIfNotExist()666 require.NoError(t, errdb, "Error when trying to create database")667 //Save the test document668 deleteErr := db.deleteDoc("2", "")669 require.NoError(t, deleteErr, "Error when trying to delete a non existing document")670}671func TestCouchDBVersion(t *testing.T) {672 config := testConfig()673 couchDBEnv.startCouchDB(t)674 config.Address = couchDBEnv.couchAddress675 defer couchDBEnv.cleanup(config)676 err := checkCouchDBVersion("2.0.0")677 require.NoError(t, err, "Error should not have been thrown for valid version")678 err = checkCouchDBVersion("4.5.0")679 require.NoError(t, err, "Error should not have been thrown for valid version")680 err = checkCouchDBVersion("1.6.5.4")681 require.Error(t, err, "Error should have been thrown for invalid version")682 err = checkCouchDBVersion("0.0.0.0")683 require.Error(t, err, "Error should have been thrown for invalid version")684}685func TestIndexOperations(t *testing.T) {686 config := testConfig()687 couchDBEnv.startCouchDB(t)688 config.Address = couchDBEnv.couchAddress689 defer couchDBEnv.cleanup(config)690 database := "testindexoperations"691 byteJSON1 := []byte(`{"_id":"1", "asset_name":"marble1","color":"blue","size":1,"owner":"jerry"}`)692 byteJSON2 := []byte(`{"_id":"2", "asset_name":"marble2","color":"red","size":2,"owner":"tom"}`)693 byteJSON3 := []byte(`{"_id":"3", "asset_name":"marble3","color":"green","size":3,"owner":"jerry"}`)694 byteJSON4 := []byte(`{"_id":"4", "asset_name":"marble4","color":"purple","size":4,"owner":"tom"}`)695 byteJSON5 := []byte(`{"_id":"5", "asset_name":"marble5","color":"blue","size":5,"owner":"jerry"}`)696 byteJSON6 := []byte(`{"_id":"6", "asset_name":"marble6","color":"white","size":6,"owner":"tom"}`)697 byteJSON7 := []byte(`{"_id":"7", "asset_name":"marble7","color":"white","size":7,"owner":"tom"}`)698 byteJSON8 := []byte(`{"_id":"8", "asset_name":"marble8","color":"white","size":8,"owner":"tom"}`)699 byteJSON9 := []byte(`{"_id":"9", "asset_name":"marble9","color":"white","size":9,"owner":"tom"}`)700 byteJSON10 := []byte(`{"_id":"10", "asset_name":"marble10","color":"white","size":10,"owner":"tom"}`)701 //create a new instance and database object --------------------------------------------------------702 couchInstance, err := createCouchInstance(config, &disabled.Provider{})703 require.NoError(t, err, "Error when trying to create couch instance")704 db := couchDatabase{couchInstance: couchInstance, dbName: database}705 //create a new database706 errdb := db.createDatabaseIfNotExist()707 require.NoError(t, errdb, "Error when trying to create database")708 batchUpdateDocs := []*couchDoc{}709 batchUpdateDocs = append(batchUpdateDocs, &couchDoc{jsonValue: byteJSON1, attachments: nil})710 batchUpdateDocs = append(batchUpdateDocs, &couchDoc{jsonValue: byteJSON2, attachments: nil})711 batchUpdateDocs = append(batchUpdateDocs, &couchDoc{jsonValue: byteJSON3, attachments: nil})712 batchUpdateDocs = append(batchUpdateDocs, &couchDoc{jsonValue: byteJSON4, attachments: nil})713 batchUpdateDocs = append(batchUpdateDocs, &couchDoc{jsonValue: byteJSON5, attachments: nil})714 batchUpdateDocs = append(batchUpdateDocs, &couchDoc{jsonValue: byteJSON6, attachments: nil})715 batchUpdateDocs = append(batchUpdateDocs, &couchDoc{jsonValue: byteJSON7, attachments: nil})716 batchUpdateDocs = append(batchUpdateDocs, &couchDoc{jsonValue: byteJSON8, attachments: nil})717 batchUpdateDocs = append(batchUpdateDocs, &couchDoc{jsonValue: byteJSON9, attachments: nil})718 batchUpdateDocs = append(batchUpdateDocs, &couchDoc{jsonValue: byteJSON10, attachments: nil})719 _, err = db.batchUpdateDocuments(batchUpdateDocs)720 require.NoError(t, err, "Error adding batch of documents")721 //Create an index definition722 indexDefSize := `{"index":{"fields":[{"size":"desc"}]},"ddoc":"indexSizeSortDoc", "name":"indexSizeSortName","type":"json"}`723 //Create the index724 _, err = db.createIndex(indexDefSize)725 require.NoError(t, err, "Error thrown while creating an index")726 //Retrieve the list of indexes727 //Delay for 100ms since CouchDB index list is updated async after index create/drop728 time.Sleep(100 * time.Millisecond)729 listResult, err := db.listIndex()730 require.NoError(t, err, "Error thrown while retrieving indexes")731 //There should only be one item returned732 require.Equal(t, 1, len(listResult))733 //Verify the returned definition734 for _, elem := range listResult {735 require.Equal(t, "indexSizeSortDoc", elem.DesignDocument)736 require.Equal(t, "indexSizeSortName", elem.Name)737 //ensure the index definition is correct, CouchDB 2.1.1 will also return "partial_filter_selector":{}738 require.Equal(t, true, strings.Contains(elem.Definition, `"fields":[{"size":"desc"}]`))739 }740 //Create an index definition with no DesignDocument or name741 indexDefColor := `{"index":{"fields":[{"color":"desc"}]}}`742 //Create the index743 _, err = db.createIndex(indexDefColor)744 require.NoError(t, err, "Error thrown while creating an index")745 //Retrieve the list of indexes746 //Delay for 100ms since CouchDB index list is updated async after index create/drop747 time.Sleep(100 * time.Millisecond)748 listResult, err = db.listIndex()749 require.NoError(t, err, "Error thrown while retrieving indexes")750 //There should be two indexes returned751 require.Equal(t, 2, len(listResult))752 //Delete the named index753 err = db.deleteIndex("indexSizeSortDoc", "indexSizeSortName")754 require.NoError(t, err, "Error thrown while deleting an index")755 //Retrieve the list of indexes756 //Delay for 100ms since CouchDB index list is updated async after index create/drop757 time.Sleep(100 * time.Millisecond)758 listResult, err = db.listIndex()759 require.NoError(t, err, "Error thrown while retrieving indexes")760 //There should be one index returned761 require.Equal(t, 1, len(listResult))762 //Delete the unnamed index763 for _, elem := range listResult {764 err = db.deleteIndex(elem.DesignDocument, elem.Name)765 require.NoError(t, err, "Error thrown while deleting an index")766 }767 //Retrieve the list of indexes768 //Delay for 100ms since CouchDB index list is updated async after index create/drop769 time.Sleep(100 * time.Millisecond)770 listResult, err = db.listIndex()771 require.NoError(t, err, "Error thrown while retrieving indexes")772 require.Equal(t, 0, len(listResult))773 //Create a query string with a descending sort, this will require an index774 queryString := `{"selector":{"size": {"$gt": 0}},"fields": ["_id", "_rev", "owner", "asset_name", "color", "size"], "sort":[{"size":"desc"}], "limit": 10,"skip": 0}`775 //Execute a query with a sort, this should throw the exception776 _, _, err = db.queryDocuments(queryString)777 require.Error(t, err, "Error should have thrown while querying without a valid index")778 //Create the index779 _, err = db.createIndex(indexDefSize)780 require.NoError(t, err, "Error thrown while creating an index")781 //Delay for 100ms since CouchDB index list is updated async after index create/drop782 time.Sleep(100 * time.Millisecond)783 //Execute a query with an index, this should succeed784 _, _, err = db.queryDocuments(queryString)785 require.NoError(t, err, "Error thrown while querying with an index")786 //Create another index definition787 indexDefSize = `{"index":{"fields":[{"data.size":"desc"},{"data.owner":"desc"}]},"ddoc":"indexSizeOwnerSortDoc", "name":"indexSizeOwnerSortName","type":"json"}`788 //Create the index789 dbResp, err := db.createIndex(indexDefSize)790 require.NoError(t, err, "Error thrown while creating an index")791 //verify the response is "created" for an index creation792 require.Equal(t, "created", dbResp.Result)793 //Delay for 100ms since CouchDB index list is updated async after index create/drop794 time.Sleep(100 * time.Millisecond)795 //Update the index796 dbResp, err = db.createIndex(indexDefSize)797 require.NoError(t, err, "Error thrown while creating an index")798 //verify the response is "exists" for an update799 require.Equal(t, "exists", dbResp.Result)800 //Retrieve the list of indexes801 //Delay for 100ms since CouchDB index list is updated async after index create/drop802 time.Sleep(100 * time.Millisecond)803 listResult, err = db.listIndex()804 require.NoError(t, err, "Error thrown while retrieving indexes")805 //There should only be two definitions806 require.Equal(t, 2, len(listResult))807 //Create an invalid index definition with an invalid JSON808 indexDefSize = `{"index"{"fields":[{"data.size":"desc"},{"data.owner":"desc"}]},"ddoc":"indexSizeOwnerSortDoc", "name":"indexSizeOwnerSortName","type":"json"}`809 //Create the index810 _, err = db.createIndex(indexDefSize)811 require.Error(t, err, "Error should have been thrown for an invalid index JSON")812 //Create an invalid index definition with a valid JSON and an invalid index definition813 indexDefSize = `{"index":{"fields2":[{"data.size":"desc"},{"data.owner":"desc"}]},"ddoc":"indexSizeOwnerSortDoc", "name":"indexSizeOwnerSortName","type":"json"}`814 //Create the index815 _, err = db.createIndex(indexDefSize)816 require.Error(t, err, "Error should have been thrown for an invalid index definition")817}818func TestRichQuery(t *testing.T) {819 config := testConfig()820 couchDBEnv.startCouchDB(t)821 config.Address = couchDBEnv.couchAddress822 defer couchDBEnv.cleanup(config)823 byteJSON01 := []byte(`{"asset_name":"marble01","color":"blue","size":1,"owner":"jerry"}`)824 byteJSON02 := []byte(`{"asset_name":"marble02","color":"red","size":2,"owner":"tom"}`)825 byteJSON03 := []byte(`{"asset_name":"marble03","color":"green","size":3,"owner":"jerry"}`)826 byteJSON04 := []byte(`{"asset_name":"marble04","color":"purple","size":4,"owner":"tom"}`)827 byteJSON05 := []byte(`{"asset_name":"marble05","color":"blue","size":5,"owner":"jerry"}`)828 byteJSON06 := []byte(`{"asset_name":"marble06","color":"white","size":6,"owner":"tom"}`)829 byteJSON07 := []byte(`{"asset_name":"marble07","color":"white","size":7,"owner":"tom"}`)830 byteJSON08 := []byte(`{"asset_name":"marble08","color":"white","size":8,"owner":"tom"}`)831 byteJSON09 := []byte(`{"asset_name":"marble09","color":"white","size":9,"owner":"tom"}`)832 byteJSON10 := []byte(`{"asset_name":"marble10","color":"white","size":10,"owner":"tom"}`)833 byteJSON11 := []byte(`{"asset_name":"marble11","color":"green","size":11,"owner":"tom"}`)834 byteJSON12 := []byte(`{"asset_name":"marble12","color":"green","size":12,"owner":"frank"}`)835 attachment1 := &attachmentInfo{}836 attachment1.AttachmentBytes = []byte(`marble01 - test attachment`)837 attachment1.ContentType = "application/octet-stream"838 attachment1.Name = "data"839 attachments1 := []*attachmentInfo{}840 attachments1 = append(attachments1, attachment1)841 attachment2 := &attachmentInfo{}842 attachment2.AttachmentBytes = []byte(`marble02 - test attachment`)843 attachment2.ContentType = "application/octet-stream"844 attachment2.Name = "data"845 attachments2 := []*attachmentInfo{}846 attachments2 = append(attachments2, attachment2)847 attachment3 := &attachmentInfo{}848 attachment3.AttachmentBytes = []byte(`marble03 - test attachment`)849 attachment3.ContentType = "application/octet-stream"850 attachment3.Name = "data"851 attachments3 := []*attachmentInfo{}852 attachments3 = append(attachments3, attachment3)853 attachment4 := &attachmentInfo{}854 attachment4.AttachmentBytes = []byte(`marble04 - test attachment`)855 attachment4.ContentType = "application/octet-stream"856 attachment4.Name = "data"857 attachments4 := []*attachmentInfo{}858 attachments4 = append(attachments4, attachment4)859 attachment5 := &attachmentInfo{}860 attachment5.AttachmentBytes = []byte(`marble05 - test attachment`)861 attachment5.ContentType = "application/octet-stream"862 attachment5.Name = "data"863 attachments5 := []*attachmentInfo{}864 attachments5 = append(attachments5, attachment5)865 attachment6 := &attachmentInfo{}866 attachment6.AttachmentBytes = []byte(`marble06 - test attachment`)867 attachment6.ContentType = "application/octet-stream"868 attachment6.Name = "data"869 attachments6 := []*attachmentInfo{}870 attachments6 = append(attachments6, attachment6)871 attachment7 := &attachmentInfo{}872 attachment7.AttachmentBytes = []byte(`marble07 - test attachment`)873 attachment7.ContentType = "application/octet-stream"874 attachment7.Name = "data"875 attachments7 := []*attachmentInfo{}876 attachments7 = append(attachments7, attachment7)877 attachment8 := &attachmentInfo{}878 attachment8.AttachmentBytes = []byte(`marble08 - test attachment`)879 attachment8.ContentType = "application/octet-stream"880 attachment7.Name = "data"881 attachments8 := []*attachmentInfo{}882 attachments8 = append(attachments8, attachment8)883 attachment9 := &attachmentInfo{}884 attachment9.AttachmentBytes = []byte(`marble09 - test attachment`)885 attachment9.ContentType = "application/octet-stream"886 attachment9.Name = "data"887 attachments9 := []*attachmentInfo{}888 attachments9 = append(attachments9, attachment9)889 attachment10 := &attachmentInfo{}890 attachment10.AttachmentBytes = []byte(`marble10 - test attachment`)891 attachment10.ContentType = "application/octet-stream"892 attachment10.Name = "data"893 attachments10 := []*attachmentInfo{}894 attachments10 = append(attachments10, attachment10)895 attachment11 := &attachmentInfo{}896 attachment11.AttachmentBytes = []byte(`marble11 - test attachment`)897 attachment11.ContentType = "application/octet-stream"898 attachment11.Name = "data"899 attachments11 := []*attachmentInfo{}900 attachments11 = append(attachments11, attachment11)901 attachment12 := &attachmentInfo{}902 attachment12.AttachmentBytes = []byte(`marble12 - test attachment`)903 attachment12.ContentType = "application/octet-stream"904 attachment12.Name = "data"905 attachments12 := []*attachmentInfo{}906 attachments12 = append(attachments12, attachment12)907 database := "testrichquery"908 //create a new instance and database object --------------------------------------------------------909 couchInstance, err := createCouchInstance(config, &disabled.Provider{})910 require.NoError(t, err, "Error when trying to create couch instance")911 db := couchDatabase{couchInstance: couchInstance, dbName: database}912 //create a new database913 errdb := db.createDatabaseIfNotExist()914 require.NoError(t, errdb, "Error when trying to create database")915 //Save the test document916 _, saveerr := db.saveDoc("marble01", "", &couchDoc{jsonValue: byteJSON01, attachments: attachments1})917 require.NoError(t, saveerr, "Error when trying to save a document")918 //Save the test document919 _, saveerr = db.saveDoc("marble02", "", &couchDoc{jsonValue: byteJSON02, attachments: attachments2})920 require.NoError(t, saveerr, "Error when trying to save a document")921 //Save the test document922 _, saveerr = db.saveDoc("marble03", "", &couchDoc{jsonValue: byteJSON03, attachments: attachments3})923 require.NoError(t, saveerr, "Error when trying to save a document")924 //Save the test document925 _, saveerr = db.saveDoc("marble04", "", &couchDoc{jsonValue: byteJSON04, attachments: attachments4})926 require.NoError(t, saveerr, "Error when trying to save a document")927 //Save the test document928 _, saveerr = db.saveDoc("marble05", "", &couchDoc{jsonValue: byteJSON05, attachments: attachments5})929 require.NoError(t, saveerr, "Error when trying to save a document")930 //Save the test document931 _, saveerr = db.saveDoc("marble06", "", &couchDoc{jsonValue: byteJSON06, attachments: attachments6})932 require.NoError(t, saveerr, "Error when trying to save a document")933 //Save the test document934 _, saveerr = db.saveDoc("marble07", "", &couchDoc{jsonValue: byteJSON07, attachments: attachments7})935 require.NoError(t, saveerr, "Error when trying to save a document")936 //Save the test document937 _, saveerr = db.saveDoc("marble08", "", &couchDoc{jsonValue: byteJSON08, attachments: attachments8})938 require.NoError(t, saveerr, "Error when trying to save a document")939 //Save the test document940 _, saveerr = db.saveDoc("marble09", "", &couchDoc{jsonValue: byteJSON09, attachments: attachments9})941 require.NoError(t, saveerr, "Error when trying to save a document")942 //Save the test document943 _, saveerr = db.saveDoc("marble10", "", &couchDoc{jsonValue: byteJSON10, attachments: attachments10})944 require.NoError(t, saveerr, "Error when trying to save a document")945 //Save the test document946 _, saveerr = db.saveDoc("marble11", "", &couchDoc{jsonValue: byteJSON11, attachments: attachments11})947 require.NoError(t, saveerr, "Error when trying to save a document")948 //Save the test document949 _, saveerr = db.saveDoc("marble12", "", &couchDoc{jsonValue: byteJSON12, attachments: attachments12})950 require.NoError(t, saveerr, "Error when trying to save a document")951 //Test query with invalid JSON -------------------------------------------------------------------952 queryString := `{"selector":{"owner":}}`953 _, _, err = db.queryDocuments(queryString)954 require.Error(t, err, "Error should have been thrown for bad json")955 //Test query with object -------------------------------------------------------------------956 queryString = `{"selector":{"owner":{"$eq":"jerry"}}}`957 queryResult, _, err := db.queryDocuments(queryString)958 require.NoError(t, err, "Error when attempting to execute a query")959 //There should be 3 results for owner="jerry"960 require.Equal(t, 3, len(queryResult))961 //Test query with implicit operator --------------------------------------------------------------962 queryString = `{"selector":{"owner":"jerry"}}`...

Full Screen

Full Screen

quick_test.go

Source:quick_test.go Github

copy

Full Screen

...34 config, err := NewConfig(&saveMe, nil)35 if err != nil {36 t.Fatal(err)37 }38 err = config.Save("test.json")39 if err != nil {40 t.Fatal(err)41 }42 version, err := GetVersion("test.json", nil)43 if err != nil {44 t.Fatal(err)45 }46 if version != "1" {47 t.Fatalf("Expected version '1', got '%v'", version)48 }49}50func TestReadVersionErr(t *testing.T) {51 type myStruct struct {52 Version int53 }54 saveMe := myStruct{1}55 _, err := NewConfig(&saveMe, nil)56 if err == nil {57 t.Fatal("Unexpected should fail in initialization for bad input")58 }59 err = ioutil.WriteFile("test.json", []byte("{ \"version\":2,"), 0644)60 if err != nil {61 t.Fatal(err)62 }63 _, err = GetVersion("test.json", nil)64 if err == nil {65 t.Fatal("Unexpected should fail to fetch version")66 }67 err = ioutil.WriteFile("test.json", []byte("{ \"version\":2 }"), 0644)68 if err != nil {69 t.Fatal(err)70 }71 _, err = GetVersion("test.json", nil)72 if err == nil {73 t.Fatal("Unexpected should fail to fetch version")74 }75}76func TestSaveFailOnDir(t *testing.T) {77 defer os.RemoveAll("test-1.json")78 err := os.MkdirAll("test-1.json", 0644)79 if err != nil {80 t.Fatal(err)81 }82 type myStruct struct {83 Version string84 }85 saveMe := myStruct{"1"}86 config, err := NewConfig(&saveMe, nil)87 if err != nil {88 t.Fatal(err)89 }90 err = config.Save("test-1.json")91 if err == nil {92 t.Fatal("Unexpected should fail to save if test-1.json is a directory")93 }94}95func TestCheckData(t *testing.T) {96 err := CheckData(nil)97 if err == nil {98 t.Fatal("Unexpected should fail")99 }100 type myStructBadNoVersion struct {101 User string102 Password string103 Directories []string104 }105 saveMeBadNoVersion := myStructBadNoVersion{"guest", "nopassword", []string{"Work", "Documents", "Music"}}106 err = CheckData(&saveMeBadNoVersion)107 if err == nil {108 t.Fatal("Unexpected should fail if Version is not set")109 }110 type myStructBadVersionInt struct {111 Version int112 User string113 Password string114 }115 saveMeBadVersionInt := myStructBadVersionInt{1, "guest", "nopassword"}116 err = CheckData(&saveMeBadVersionInt)117 if err == nil {118 t.Fatal("Unexpected should fail if Version is integer")119 }120 type myStructGood struct {121 Version string122 User string123 Password string124 Directories []string125 }126 saveMeGood := myStructGood{"1", "guest", "nopassword", []string{"Work", "Documents", "Music"}}127 err = CheckData(&saveMeGood)128 if err != nil {129 t.Fatal(err)130 }131}132func TestLoadFile(t *testing.T) {133 type myStruct struct {134 Version string135 User string136 Password string137 Directories []string138 }139 saveMe := myStruct{}140 _, err := LoadConfig("test.json", nil, &saveMe)141 if err == nil {142 t.Fatal(err)143 }144 file, err := os.Create("test.json")145 if err != nil {146 t.Fatal(err)147 }148 if err = file.Close(); err != nil {149 t.Fatal(err)150 }151 _, err = LoadConfig("test.json", nil, &saveMe)152 if err == nil {153 t.Fatal("Unexpected should fail to load empty JSON")154 }155 config, err := NewConfig(&saveMe, nil)156 if err != nil {157 t.Fatal(err)158 }159 err = config.Load("test-non-exist.json")160 if err == nil {161 t.Fatal("Unexpected should fail to Load non-existent config")162 }163 err = config.Load("test.json")164 if err == nil {165 t.Fatal("Unexpected should fail to load empty JSON")166 }167 saveMe = myStruct{"1", "guest", "nopassword", []string{"Work", "Documents", "Music"}}168 config, err = NewConfig(&saveMe, nil)169 if err != nil {170 t.Fatal(err)171 }172 err = config.Save("test.json")173 if err != nil {174 t.Fatal(err)175 }176 saveMe1 := myStruct{}177 _, err = LoadConfig("test.json", nil, &saveMe1)178 if err != nil {179 t.Fatal(err)180 }181 if !reflect.DeepEqual(saveMe1, saveMe) {182 t.Fatalf("Expected %v, got %v", saveMe1, saveMe)183 }184 saveMe2 := myStruct{}185 err = json.Unmarshal([]byte(config.String()), &saveMe2)186 if err != nil {187 t.Fatal(err)188 }189 if !reflect.DeepEqual(saveMe2, saveMe1) {190 t.Fatalf("Expected %v, got %v", saveMe2, saveMe1)191 }192}193func TestYAMLFormat(t *testing.T) {194 testYAML := "test.yaml"195 defer os.RemoveAll(testYAML)196 type myStruct struct {197 Version string198 User string199 Password string200 Directories []string201 }202 plainYAML := `version: "1"203user: guest204password: nopassword205directories:206- Work207- Documents208- Music209`210 if runtime.GOOS == "windows" {211 plainYAML = strings.Replace(plainYAML, "\n", "\r\n", -1)212 }213 saveMe := myStruct{"1", "guest", "nopassword", []string{"Work", "Documents", "Music"}}214 // Save format using215 config, err := NewConfig(&saveMe, nil)216 if err != nil {217 t.Fatal(err)218 }219 err = config.Save(testYAML)220 if err != nil {221 t.Fatal(err)222 }223 // Check if the saved structure in actually an YAML format224 b, err := ioutil.ReadFile(testYAML)225 if err != nil {226 t.Fatal(err)227 }228 if !bytes.Equal([]byte(plainYAML), b) {229 t.Fatalf("Expected %v, got %v", plainYAML, string(b))230 }231 // Check if the loaded data is the same as the saved one232 loadMe := myStruct{}233 config, err = NewConfig(&loadMe, nil)234 if err != nil {235 t.Fatal(err)236 }237 err = config.Load(testYAML)238 if err != nil {239 t.Fatal(err)240 }241 if !reflect.DeepEqual(saveMe, loadMe) {242 t.Fatalf("Expected %v, got %v", saveMe, loadMe)243 }244}245func TestJSONFormat(t *testing.T) {246 testJSON := "test.json"247 defer os.RemoveAll(testJSON)248 type myStruct struct {249 Version string250 User string251 Password string252 Directories []string253 }254 plainJSON := `{255 "Version": "1",256 "User": "guest",257 "Password": "nopassword",258 "Directories": [259 "Work",260 "Documents",261 "Music"262 ]263}`264 if runtime.GOOS == "windows" {265 plainJSON = strings.Replace(plainJSON, "\n", "\r\n", -1)266 }267 saveMe := myStruct{"1", "guest", "nopassword", []string{"Work", "Documents", "Music"}}268 // Save format using269 config, err := NewConfig(&saveMe, nil)270 if err != nil {271 t.Fatal(err)272 }273 err = config.Save(testJSON)274 if err != nil {275 t.Fatal(err)276 }277 // Check if the saved structure in actually an JSON format278 b, err := ioutil.ReadFile(testJSON)279 if err != nil {280 t.Fatal(err)281 }282 if !bytes.Equal([]byte(plainJSON), b) {283 t.Fatalf("Expected %v, got %v", plainJSON, string(b))284 }285 // Check if the loaded data is the same as the saved one286 loadMe := myStruct{}287 config, err = NewConfig(&loadMe, nil)288 if err != nil {289 t.Fatal(err)290 }291 err = config.Load(testJSON)292 if err != nil {293 t.Fatal(err)294 }295 if !reflect.DeepEqual(saveMe, loadMe) {296 t.Fatalf("Expected %v, got %v", saveMe, loadMe)297 }298}299func TestSaveLoad(t *testing.T) {300 defer os.RemoveAll("test.json")301 type myStruct struct {302 Version string303 User string304 Password string305 Directories []string306 }307 saveMe := myStruct{"1", "guest", "nopassword", []string{"Work", "Documents", "Music"}}308 config, err := NewConfig(&saveMe, nil)309 if err != nil {310 t.Fatal(err)311 }312 err = config.Save("test.json")313 if err != nil {314 t.Fatal(err)315 }316 loadMe := myStruct{Version: "1"}317 newConfig, err := NewConfig(&loadMe, nil)318 if err != nil {319 t.Fatal(err)320 }321 err = newConfig.Load("test.json")322 if err != nil {323 t.Fatal(err)324 }325 if !reflect.DeepEqual(config.Data(), newConfig.Data()) {326 t.Fatalf("Expected %v, got %v", config.Data(), newConfig.Data())327 }328 if !reflect.DeepEqual(config.Data(), &loadMe) {329 t.Fatalf("Expected %v, got %v", config.Data(), &loadMe)330 }331 mismatch := myStruct{"1.1", "guest", "nopassword", []string{"Work", "Documents", "Music"}}332 if reflect.DeepEqual(config.Data(), &mismatch) {333 t.Fatal("Expected to mismatch but succeeded instead")334 }335}336func TestSaveBackup(t *testing.T) {337 defer os.RemoveAll("test.json")338 defer os.RemoveAll("test.json.old")339 type myStruct struct {340 Version string341 User string342 Password string343 Directories []string344 }345 saveMe := myStruct{"1", "guest", "nopassword", []string{"Work", "Documents", "Music"}}346 config, err := NewConfig(&saveMe, nil)347 if err != nil {348 t.Fatal(err)349 }350 err = config.Save("test.json")351 if err != nil {352 t.Fatal(err)353 }354 loadMe := myStruct{Version: "1"}355 newConfig, err := NewConfig(&loadMe, nil)356 if err != nil {357 t.Fatal(err)358 }359 err = newConfig.Load("test.json")360 if err != nil {361 t.Fatal(err)362 }363 if !reflect.DeepEqual(config.Data(), newConfig.Data()) {364 t.Fatalf("Expected %v, got %v", config.Data(), newConfig.Data())365 }366 if !reflect.DeepEqual(config.Data(), &loadMe) {367 t.Fatalf("Expected %v, got %v", config.Data(), &loadMe)368 }369 mismatch := myStruct{"1.1", "guest", "nopassword", []string{"Work", "Documents", "Music"}}370 if reflect.DeepEqual(newConfig.Data(), &mismatch) {371 t.Fatal("Expected to mismatch but succeeded instead")372 }373 config, err = NewConfig(&mismatch, nil)374 if err != nil {375 t.Fatal(err)376 }377 err = config.Save("test.json")378 if err != nil {379 t.Fatal(err)380 }381}382func TestDiff(t *testing.T) {383 type myStruct struct {384 Version string385 User string386 Password string387 Directories []string388 }389 saveMe := myStruct{"1", "guest", "nopassword", []string{"Work", "Documents", "Music"}}390 config, err := NewConfig(&saveMe, nil)391 if err != nil {...

Full Screen

Full Screen

config_service.go

Source:config_service.go Github

copy

Full Screen

...47 return exists, nil48 }49 return false, nil50}51// SaveConfig saves the configuration to disk52func (s *AuthConfigService) SaveConfig() error {53 fileName := s.FileName54 if fileName == "" {55 return fmt.Errorf("No filename defined!")56 }57 data, err := yaml.Marshal(s.config)58 if err != nil {59 return err60 }61 return ioutil.WriteFile(fileName, data, DefaultWritePermissions)62}63// SaveUserAuth saves the given user auth for the server url64func (s *AuthConfigService) SaveUserAuth(url string, userAuth *UserAuth) error {65 config := s.config66 config.SetUserAuth(url, userAuth)67 user := userAuth.Username68 if user != "" {69 config.DefaultUsername = user70 }71 // Set Pipeline user once only.72 if config.PipeLineUsername == "" {73 config.PipeLineUsername = user74 config.PipeLineServer = url75 }76 config.CurrentServer = url77 return s.SaveConfig()78}79// DeleteServer removes the given server from the configuration80func (s *AuthConfigService) DeleteServer(url string) error {81 s.config.DeleteServer(url)82 return s.SaveConfig()83}...

Full Screen

Full Screen

Save

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 config.Load(file.NewSource(4 file.WithPath("config.json"),5 value := config.Get("foo", "bar")6 config.Set("foo", "bar", "hello")7 config.Save(file.NewSource(8 file.WithPath("config.json"),9 fmt.Println(value.String("default"))10}11import (12func main() {13 config.Load(env.NewSource())14 value := config.Get("foo", "bar")15 config.Set("foo", "bar", "hello")16 config.Save(env.NewSource())17 fmt.Println(value.String("default"))18}19import (20func main() {21 config.Load(cmd.NewSource())22 value := config.Get("foo", "bar")23 config.Set("foo", "bar", "hello")24 config.Save(cmd.NewSource())25 fmt.Println(value.String("default"))26}27import (28func main() {29 config.Load(consul.NewSource(30 consul.WithAddress("localhost:8500"),31 consul.WithPrefix("config"),32 consul.StripPrefix(true),

Full Screen

Full Screen

Save

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 config := viper.New()4 config.SetConfigFile("config.yaml")5 err := config.ReadInConfig()6 if err != nil {7 fmt.Println("Error reading config file, %s", err)8 }9 config.Set("name", "Raj")10 err = config.WriteConfig()11 if err != nil {12 fmt.Println("Error writing config file, %s", err)13 }14}15import (16func main() {17 config := viper.New()18 config.SetConfigFile("config.yaml")19 err := config.ReadInConfig()20 if err != nil {21 fmt.Println("Error reading config file, %s", err)22 }23 name := config.Get("name")24 age := config.GetString("age")25 address := config.GetInt("address")26 fmt.Println("Name: ", name)27 fmt.Println("Age: ", age)28 fmt.Println("Address: ", address)29}30import (31func main() {32 config := viper.New()33 config.SetConfigFile("config.yaml")34 err := config.ReadInConfig()35 if err != nil {36 fmt.Println("Error reading config file, %s", err)37 }38 name := config.Get("name")

Full Screen

Full Screen

Save

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 conf, err := config.NewConfig("ini", "1.conf")4 if err != nil {5 panic(err)6 }7 err = conf.SaveConfigFile("2.conf")8 if err != nil {9 panic(err)10 }11 fmt.Println("Saved")12}

Full Screen

Full Screen

Save

Using AI Code Generation

copy

Full Screen

1import (2func (l List) Save() {3 fmt.Println("Saving list of", len(l), "items")4}5func main() {6 l.Save()7}8import (9func (l List) Save() {10 fmt.Println("Saving list of", len(l), "items")11}12func main() {13 l.Save()14}

Full Screen

Full Screen

Save

Using AI Code Generation

copy

Full Screen

1func main() {2 c := config.NewConfig("config.json")3 c.Save()4}5func main() {6 c := config.NewConfig("config.json")7 c.Load()8}9* **Ankit Kumar** - *Initial work* - [ankitkumar](

Full Screen

Full Screen

Save

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 config := config.New()4 config.Save("test")5 fmt.Println("Done")6}7import (8func main() {9 config := config.New()10 fmt.Println(config.Load())11}12import (13func main() {14 config := config.New()15 config.Delete()16 fmt.Println("Done")17}18import (19func main() {20 config := config.New()21 config.Update("test")22 fmt.Println("Done")23}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful