Best Got code snippet using got.err
mongo_test.go
Source:mongo_test.go
...38var adp adapter.Adapter39var db *mdb.Database40var ctx context.Context41func TestCreateDb(t *testing.T) {42 if err := adp.CreateDb(config.Reset); err != nil {43 t.Fatal(err)44 }45}46// ================== Create tests ================================47func TestUserCreate(t *testing.T) {48 for _, user := range users {49 if err := adp.UserCreate(user); err != nil {50 t.Error(err)51 }52 }53 count, err := db.Collection("users").CountDocuments(ctx, b.M{})54 if err != nil {55 t.Error(err)56 }57 if count == 0 {58 t.Error("No users created!")59 }60}61func TestCredUpsert(t *testing.T) {62 // Test just inserts:63 for i := 0; i < 2; i++ {64 inserted, err := adp.CredUpsert(creds[i])65 if err != nil {66 t.Fatal(err)67 }68 if !inserted {69 t.Error("Should be inserted, but updated")70 }71 }72 // Test duplicate:73 _, err := adp.CredUpsert(creds[1])74 if err != types.ErrDuplicate {75 t.Error("Should return duplicate error but got", err)76 }77 _, err = adp.CredUpsert(creds[2])78 if err != types.ErrDuplicate {79 t.Error("Should return duplicate error but got", err)80 }81 // Test add new unvalidated credentials82 inserted, err := adp.CredUpsert(creds[3])83 if err != nil {84 t.Fatal(err)85 }86 if !inserted {87 t.Error("Should be inserted, but updated")88 }89 inserted, err = adp.CredUpsert(creds[3])90 if err != nil {91 t.Fatal(err)92 }93 if inserted {94 t.Error("Should be updated, but inserted")95 }96 // Just insert other creds (used in other tests)97 for _, cred := range creds[4:] {98 _, err = adp.CredUpsert(cred)99 if err != nil {100 t.Fatal(err)101 }102 }103}104func TestAuthAddRecord(t *testing.T) {105 for _, rec := range recs {106 err := adp.AuthAddRecord(types.ParseUserId("usr"+rec.UserId), rec.Scheme, rec.Id,107 rec.AuthLvl, rec.Secret, rec.Expires)108 if err != nil {109 t.Fatal(err)110 }111 }112 //Test duplicate113 err := adp.AuthAddRecord(types.ParseUserId("usr"+users[0].Id), recs[0].Scheme, recs[0].Id,114 recs[0].AuthLvl, recs[0].Secret, recs[0].Expires)115 if err != types.ErrDuplicate {116 t.Fatal("Should be duplicate error but got", err)117 }118}119func TestTopicCreate(t *testing.T) {120 err := adp.TopicCreate(topics[0])121 if err != nil {122 t.Error(err)123 }124 for _, tpc := range topics[3:] {125 err = adp.TopicCreate(tpc)126 if err != nil {127 t.Error(err)128 }129 }130}131func TestTopicCreateP2P(t *testing.T) {132 err := adp.TopicCreateP2P(subs[2], subs[3])133 if err != nil {134 t.Fatal(err)135 }136 oldModeGiven := subs[2].ModeGiven137 subs[2].ModeGiven = 255138 err = adp.TopicCreateP2P(subs[4], subs[2])139 if err != nil {140 t.Fatal(err)141 }142 var got types.Subscription143 err = db.Collection("subscriptions").FindOne(ctx, b.M{"_id": subs[2].Id}).Decode(&got)144 if err != nil {145 t.Fatal(err)146 }147 if got.ModeGiven == oldModeGiven {148 t.Error("ModeGiven update failed")149 }150}151func TestTopicShare(t *testing.T) {152 err := adp.TopicShare(subs)153 if err != nil {154 t.Fatal(err)155 }156}157func TestMessageSave(t *testing.T) {158 for _, msg := range msgs {159 err := adp.MessageSave(msg)160 if err != nil {161 t.Fatal(err)162 }163 }164}165func TestFileStartUpload(t *testing.T) {166 for _, f := range files {167 err := adp.FileStartUpload(f)168 if err != nil {169 t.Fatal(err)170 }171 }172}173// ================== Read tests ==================================174func TestUserGet(t *testing.T) {175 // Test not found176 got, err := adp.UserGet(types.ParseUserId("dummyuserid"))177 if err == nil && got != nil {178 t.Error("user should be nil.")179 }180 got, err = adp.UserGet(types.ParseUserId("usr" + users[0].Id))181 if err != nil {182 t.Fatal(err)183 }184 if !reflect.DeepEqual(got, users[0]) {185 t.Errorf(mismatchErrorString("User", got, users[0]))186 }187}188func TestUserGetAll(t *testing.T) {189 // Test not found190 got, err := adp.UserGetAll(types.ParseUserId("dummyuserid"), types.ParseUserId("otherdummyid"))191 if err == nil && got != nil {192 t.Error("result users should be nil.")193 }194 got, err = adp.UserGetAll(types.ParseUserId("usr"+users[0].Id), types.ParseUserId("usr"+users[1].Id))195 if err != nil {196 t.Fatal(err)197 }198 if len(got) != 2 {199 t.Fatal(mismatchErrorString("resultUsers length", len(got), 2))200 }201 for i, usr := range got {202 if !reflect.DeepEqual(&usr, users[i]) {203 t.Error(mismatchErrorString("User", &usr, users[i]))204 }205 }206}207func TestUserGetDisabled(t *testing.T) {208 // Test before deletion date209 got, err := adp.UserGetDisabled(users[2].DeletedAt.Add(-10 * time.Hour))210 if err != nil {211 t.Fatal(err)212 }213 if len(got) != 1 {214 t.Fatal(mismatchErrorString("uids length", len(got), 1))215 }216 if got[0].String() != users[2].Id {217 t.Error(mismatchErrorString("userId", got[0].String(), users[2].Id))218 }219 // Test after deletion date220 got, err = adp.UserGetDisabled(users[2].DeletedAt.Add(10 * time.Hour))221 if err != nil {222 t.Fatal(err)223 }224 if got != nil {225 t.Fatal(mismatchErrorString("result", got, nil))226 }227}228func TestUserGetByCred(t *testing.T) {229 // Test not found230 got, err := adp.UserGetByCred("foo", "bar")231 if err != nil {232 t.Fatal(err)233 }234 if got != types.ZeroUid {235 t.Error("result uid should be ZeroUid")236 }237 got, _ = adp.UserGetByCred(creds[0].Method, creds[0].Value)238 if got != types.ParseUserId("usr"+creds[0].User) {239 t.Error(mismatchErrorString("Uid", got, types.ParseUserId("usr"+creds[0].User)))240 }241}242func TestCredGetActive(t *testing.T) {243 got, err := adp.CredGetActive(types.ParseUserId("usr"+users[2].Id), "tel")244 if err != nil {245 t.Error(err)246 }247 if !reflect.DeepEqual(got, creds[3]) {248 t.Errorf(mismatchErrorString("Credential", got, creds[3]))249 }250 // Test not found251 _, err = adp.CredGetActive(types.ParseUserId("dummyusrid"), "")252 if err != types.ErrNotFound {253 t.Error("Err should be types.ErrNotFound, but got", err)254 }255}256func TestCredGetAll(t *testing.T) {257 got, err := adp.CredGetAll(types.ParseUserId("usr"+users[2].Id), "", false)258 if err != nil {259 t.Fatal(err)260 }261 if len(got) != 3 {262 t.Errorf(mismatchErrorString("Credentials length", len(got), 3))263 }264 got, _ = adp.CredGetAll(types.ParseUserId("usr"+users[2].Id), "tel", false)265 if len(got) != 2 {266 t.Errorf(mismatchErrorString("Credentials length", len(got), 2))267 }268 got, _ = adp.CredGetAll(types.ParseUserId("usr"+users[2].Id), "", true)269 if len(got) != 1 {270 t.Errorf(mismatchErrorString("Credentials length", len(got), 1))271 }272 got, _ = adp.CredGetAll(types.ParseUserId("usr"+users[2].Id), "tel", true)273 if len(got) != 1 {274 t.Errorf(mismatchErrorString("Credentials length", len(got), 1))275 }276}277func TestUserUnreadCount(t *testing.T) {278 count, err := adp.UserUnreadCount(types.ParseUserId("usr" + users[2].Id))279 if err != nil {280 t.Fatal(err)281 }282 if count != 100 {283 t.Error(mismatchErrorString("UnreadCount", count, 100))284 }285 // Test not found286 count, err = adp.UserUnreadCount(types.ParseUserId("dummyuserid"))287 if err != nil {288 t.Fatal(err)289 }290 if count != 0 {291 t.Error(mismatchErrorString("UnreadCount", count, 0))292 }293}294func TestAuthGetUniqueRecord(t *testing.T) {295 uid, authLvl, secret, expires, err := adp.AuthGetUniqueRecord("basic:alice")296 if err != nil {297 t.Fatal(err)298 }299 if uid != types.ParseUserId("usr"+recs[0].UserId) ||300 authLvl != recs[0].AuthLvl ||301 bytes.Compare(secret, recs[0].Secret) != 0 ||302 expires != recs[0].Expires {303 got := fmt.Sprintf("%v %v %v %v", uid, authLvl, secret, expires)304 want := fmt.Sprintf("%v %v %v %v", recs[0].UserId, recs[0].AuthLvl, recs[0].Secret, recs[0].Expires)305 t.Errorf(mismatchErrorString("Auth record", got, want))306 }307 // Test not found308 uid, _, _, _, err = adp.AuthGetUniqueRecord("qwert:asdfg")309 if err == nil && !uid.IsZero() {310 t.Error("Auth record found but shouldn't. Uid:", uid.String())311 }312}313func TestAuthGetRecord(t *testing.T) {314 recId, authLvl, secret, expires, err := adp.AuthGetRecord(types.ParseUserId("usr"+recs[0].UserId), "basic")315 if err != nil {316 t.Fatal(err)317 }318 if recId != recs[0].Id ||319 authLvl != recs[0].AuthLvl ||320 bytes.Compare(secret, recs[0].Secret) != 0 ||321 expires != recs[0].Expires {322 got := fmt.Sprintf("%v %v %v %v", recId, authLvl, secret, expires)323 want := fmt.Sprintf("%v %v %v %v", recs[0].Id, recs[0].AuthLvl, recs[0].Secret, recs[0].Expires)324 t.Errorf(mismatchErrorString("Auth record", got, want))325 }326 // Test not found327 recId, _, _, _, err = adp.AuthGetRecord(types.ParseUserId("dummyuserid"), "scheme")328 if err != types.ErrNotFound {329 t.Error("Auth record found but shouldn't. recId:", recId)330 }331}332func TestTopicGet(t *testing.T) {333 got, err := adp.TopicGet(topics[0].Id)334 if err != nil {335 t.Fatal(err)336 }337 if !reflect.DeepEqual(got, topics[0]) {338 t.Errorf(mismatchErrorString("Topic", got, topics[0]))339 }340 // Test not found341 got, err = adp.TopicGet("asdfasdfasdf")342 if err != nil {343 t.Fatal(err)344 }345 if got != nil {346 t.Error("Topic should be nil but got:", got)347 }348}349func TestTopicsForUser(t *testing.T) {350 qOpts := types.QueryOpt{351 Topic: "p2p9AVDamaNCRbfKzGSh3mE0w",352 Limit: 999,353 }354 gotSubs, err := adp.TopicsForUser(types.ParseUserId("usr"+users[0].Id), false, &qOpts)355 if err != nil {356 t.Fatal(err)357 }358 if len(gotSubs) != 1 {359 t.Errorf(mismatchErrorString("Subs length", len(gotSubs), 1))360 }361 gotSubs, err = adp.TopicsForUser(types.ParseUserId("usr"+users[1].Id), true, nil)362 if err != nil {363 t.Fatal(err)364 }365 if len(gotSubs) != 2 {366 t.Errorf(mismatchErrorString("Subs length", len(gotSubs), 2))367 }368}369func TestUsersForTopic(t *testing.T) {370 qOpts := types.QueryOpt{371 User: types.ParseUserId("usr" + users[0].Id),372 Limit: 999,373 }374 gotSubs, err := adp.UsersForTopic("grpgRXf0rU4uR4", false, &qOpts)375 if err != nil {376 t.Fatal(err)377 }378 if len(gotSubs) != 1 {379 t.Errorf(mismatchErrorString("Subs length", len(gotSubs), 1))380 }381 gotSubs, err = adp.UsersForTopic("grpgRXf0rU4uR4", true, nil)382 if err != nil {383 t.Fatal(err)384 }385 if len(gotSubs) != 2 {386 t.Errorf(mismatchErrorString("Subs length", len(gotSubs), 2))387 }388 gotSubs, err = adp.UsersForTopic("p2p9AVDamaNCRbfKzGSh3mE0w", false, nil)389 if err != nil {390 t.Fatal(err)391 }392 if len(gotSubs) != 2 {393 t.Errorf(mismatchErrorString("Subs length", len(gotSubs), 2))394 }395}396func TestOwnTopics(t *testing.T) {397 gotSubs, err := adp.OwnTopics(types.ParseUserId("usr" + users[0].Id))398 if err != nil {399 t.Fatal(err)400 }401 if len(gotSubs) != 1 {402 t.Fatalf("Got topic length %v instead of %v", len(gotSubs), 1)403 }404 if gotSubs[0] != topics[0].Id {405 t.Errorf("Got topic %v instead of %v", gotSubs[0], topics[0].Id)406 }407}408func TestSubscriptionGet(t *testing.T) {409 got, err := adp.SubscriptionGet(topics[0].Id, types.ParseUserId("usr"+users[0].Id))410 if err != nil {411 t.Error(err)412 }413 opts := cmpopts.IgnoreUnexported(types.Subscription{}, types.ObjHeader{})414 if !cmp.Equal(got, subs[0], opts) {415 t.Errorf(mismatchErrorString("Subs", got, subs[0]))416 }417 // Test not found418 got, err = adp.SubscriptionGet("dummytopic", types.ParseUserId("dummyuserid"))419 if err != nil {420 t.Error(err)421 }422 if got != nil {423 t.Error("result sub should be nil.")424 }425}426func TestSubsForUser(t *testing.T) {427 qOpts := types.QueryOpt{428 Topic: topics[0].Id,429 Limit: 999,430 }431 gotSubs, err := adp.SubsForUser(types.ParseUserId("usr"+users[0].Id), false, &qOpts)432 if err != nil {433 t.Error(err)434 }435 if len(gotSubs) != 1 {436 t.Errorf(mismatchErrorString("Subs length", len(gotSubs), 1))437 }438 // Test not found439 gotSubs, err = adp.SubsForUser(types.ParseUserId("dummyuserid"), false, nil)440 if err != nil {441 t.Error(err)442 }443 if len(gotSubs) != 0 {444 t.Errorf(mismatchErrorString("Subs length", len(gotSubs), 0))445 }446}447func TestSubsForTopic(t *testing.T) {448 qOpts := types.QueryOpt{449 User: types.ParseUserId("usr" + users[0].Id),450 Limit: 999,451 }452 gotSubs, err := adp.SubsForTopic(topics[0].Id, false, &qOpts)453 if err != nil {454 t.Error(err)455 }456 if len(gotSubs) != 1 {457 t.Errorf(mismatchErrorString("Subs length", len(gotSubs), 1))458 }459 // Test not found460 gotSubs, err = adp.SubsForTopic("dummytopicid", false, nil)461 if err != nil {462 t.Error(err)463 }464 if len(gotSubs) != 0 {465 t.Errorf(mismatchErrorString("Subs length", len(gotSubs), 0))466 }467}468func TestFindUsers(t *testing.T) {469 reqTags := []string{"alice", "bob", "carol"}470 gotSubs, err := adp.FindUsers(types.ParseUserId("usr"+users[2].Id), reqTags, nil)471 if err != nil {472 t.Error(err)473 }474 if len(gotSubs) != 2 {475 t.Errorf(mismatchErrorString("result length", len(gotSubs), 3))476 }477}478func TestFindTopics(t *testing.T) {479 reqTags := []string{"travel", "qwer", "asdf", "zxcv"}480 gotSubs, err := adp.FindTopics(reqTags, nil)481 if err != nil {482 t.Error(err)483 }484 if len(gotSubs) != 3 {485 t.Fatal(mismatchErrorString("result length", len(gotSubs), 3))486 }487}488func TestMessageGetAll(t *testing.T) {489 opts := types.QueryOpt{490 Since: 1,491 Before: 2,492 Limit: 999,493 }494 gotMsgs, err := adp.MessageGetAll(topics[0].Id, types.ParseUserId("usr"+users[0].Id), &opts)495 if err != nil {496 t.Fatal(err)497 }498 if len(gotMsgs) != 1 {499 t.Error(mismatchErrorString("Messages length", len(gotMsgs), 1))500 }501 gotMsgs, _ = adp.MessageGetAll(topics[0].Id, types.ParseUserId("usr"+users[0].Id), nil)502 if len(gotMsgs) != 2 {503 t.Error(mismatchErrorString("Messages length", len(gotMsgs), 2))504 }505 gotMsgs, _ = adp.MessageGetAll(topics[0].Id, types.ZeroUid, nil)506 if len(gotMsgs) != 3 {507 t.Error(mismatchErrorString("Messages length", len(gotMsgs), 3))508 }509}510func TestFileGet(t *testing.T) {511 // General test done during TestFileFinishUpload().512 // Test not found513 got, err := adp.FileGet("dummyfileid")514 if err != nil {515 if got != nil {516 t.Error("File found but shouldn't:", got)517 }518 }519}520// ================== Update tests ================================521func TestUserUpdate(t *testing.T) {522 update := map[string]interface{}{523 "UserAgent": "Test Agent v0.11",524 "UpdatedAt": now.Add(30 * time.Minute),525 }526 err := adp.UserUpdate(types.ParseUserId("usr"+users[0].Id), update)527 if err != nil {528 t.Fatal(err)529 }530 var got types.User531 err = db.Collection("users").FindOne(ctx, b.M{"_id": users[0].Id}).Decode(&got)532 if err != nil {533 t.Fatal(err)534 }535 if got.UserAgent != "Test Agent v0.11" {536 t.Errorf(mismatchErrorString("UserAgent", got.UserAgent, "Test Agent v0.11"))537 }538 if got.UpdatedAt == got.CreatedAt {539 t.Error("UpdatedAt field not updated")540 }541}542func TestUserUpdateTags(t *testing.T) {543 addTags := []string{"tag1", "Alice"}544 removeTags := []string{"alice", "tag1", "tag2"}545 resetTags := []string{"Alice", "tag111", "tag333"}546 got, err := adp.UserUpdateTags(types.ParseUserId("usr"+users[0].Id), addTags, nil, nil)547 if err != nil {548 t.Fatal(err)549 }550 want := []string{"alice", "tag1", "Alice"}551 if !reflect.DeepEqual(got, want) {552 t.Errorf(mismatchErrorString("Tags", got, want))553 }554 got, _ = adp.UserUpdateTags(types.ParseUserId("usr"+users[0].Id), nil, removeTags, nil)555 want = []string{"Alice"}556 if !reflect.DeepEqual(got, want) {557 t.Errorf(mismatchErrorString("Tags", got, want))558 }559 got, _ = adp.UserUpdateTags(types.ParseUserId("usr"+users[0].Id), nil, nil, resetTags)560 want = []string{"Alice", "tag111", "tag333"}561 if !reflect.DeepEqual(got, want) {562 t.Errorf(mismatchErrorString("Tags", got, want))563 }564 got, _ = adp.UserUpdateTags(types.ParseUserId("usr"+users[0].Id), addTags, removeTags, nil)565 want = []string{"Alice", "tag111", "tag333"}566 if !reflect.DeepEqual(got, want) {567 t.Errorf(mismatchErrorString("Tags", got, want))568 }569 got, _ = adp.UserUpdateTags(types.ParseUserId("usr"+users[0].Id), addTags, removeTags, nil)570 want = []string{"Alice", "tag111", "tag333"}571 if !reflect.DeepEqual(got, want) {572 t.Errorf(mismatchErrorString("Tags", got, want))573 }574}575func TestCredFail(t *testing.T) {576 err := adp.CredFail(types.ParseUserId("usr"+creds[3].User), "tel")577 if err != nil {578 t.Error(err)579 }580 // Check if fields updated581 var got types.Credential582 _ = db.Collection("credentials").FindOne(ctx, b.M{583 "user": creds[3].User,584 "method": "tel",585 "value": creds[3].Value}).Decode(&got)586 if got.Retries != 1 {587 t.Errorf(mismatchErrorString("Retries count", got.Retries, 1))588 }589 if got.UpdatedAt == got.CreatedAt {590 t.Error("UpdatedAt field not updated")591 }592}593func TestCredConfirm(t *testing.T) {594 err := adp.CredConfirm(types.ParseUserId("usr"+creds[3].User), "tel")595 if err != nil {596 t.Fatal(err)597 }598 // Test fields are updated599 var got types.Credential600 err = db.Collection("credentials").FindOne(ctx, b.M{601 "user": creds[3].User,602 "method": "tel",603 "value": creds[3].Value}).Decode(&got)604 if err != nil {605 t.Fatal(err)606 }607 if got.UpdatedAt == got.CreatedAt {608 t.Error("Credential not updated correctly")609 }610 // and uncomfirmed credential deleted611 err = db.Collection("credentials").FindOne(ctx, b.M{"_id": creds[3].User + ":" + got.Method + ":" + got.Value}).Decode(&got)612 if err != mdb.ErrNoDocuments {613 t.Error("Uncomfirmed credential not deleted")614 }615}616func TestAuthUpdRecord(t *testing.T) {617 rec := recs[1]618 newSecret := []byte{'s', 'e', 'c', 'r', 'e', 't'}619 err := adp.AuthUpdRecord(types.ParseUserId("usr"+rec.UserId), rec.Scheme, rec.Id,620 rec.AuthLvl, newSecret, rec.Expires)621 if err != nil {622 t.Fatal(err)623 }624 var got AuthRecord625 err = db.Collection("auth").FindOne(ctx, b.M{"_id": rec.Id}).Decode(&got)626 if err != nil {627 t.Fatal(err)628 }629 if bytes.Equal(got.Secret, rec.Secret) {630 t.Errorf(mismatchErrorString("Secret", got.Secret, rec.Secret))631 }632 // Test with auth ID (unique) change633 newId := "basic:bob12345"634 err = adp.AuthUpdRecord(types.ParseUserId("usr"+rec.UserId), rec.Scheme, newId,635 rec.AuthLvl, newSecret, rec.Expires)636 if err != nil {637 t.Fatal(err)638 }639 // Test if old ID deleted640 err = db.Collection("auth").FindOne(ctx, b.M{"_id": rec.Id}).Decode(&got)641 if err == nil || err != mdb.ErrNoDocuments {642 t.Errorf("Unique not changed. Got error: %v; ID: %v", err, got.Id)643 }644 if bytes.Equal(got.Secret, rec.Secret) {645 t.Errorf(mismatchErrorString("Secret", got.Secret, rec.Secret))646 }647 if bytes.Equal(got.Secret, rec.Secret) {648 t.Errorf(mismatchErrorString("Secret", got.Secret, rec.Secret))649 }650}651func TestTopicUpdateOnMessage(t *testing.T) {652 msg := types.Message{653 ObjHeader: types.ObjHeader{654 CreatedAt: now.Add(33 * time.Minute),655 },656 SeqId: 66,657 }658 err := adp.TopicUpdateOnMessage(topics[2].Id, &msg)659 if err != nil {660 t.Fatal(err)661 }662 var got types.Topic663 err = db.Collection("topics").FindOne(ctx, b.M{"_id": topics[2].Id}).Decode(&got)664 if err != nil {665 t.Fatal(err)666 }667 if got.TouchedAt != msg.CreatedAt || got.SeqId != msg.SeqId {668 t.Errorf(mismatchErrorString("TouchedAt", got.TouchedAt, msg.CreatedAt))669 t.Errorf(mismatchErrorString("SeqId", got.SeqId, msg.SeqId))670 }671}672func TestTopicUpdate(t *testing.T) {673 update := map[string]interface{}{674 "UpdatedAt": now.Add(55 * time.Minute),675 }676 err := adp.TopicUpdate(topics[0].Id, update)677 if err != nil {678 t.Fatal(err)679 }680 var got types.Topic681 _ = db.Collection("topics").FindOne(ctx, b.M{"_id": topics[0].Id}).Decode(&got)682 if got.UpdatedAt != update["UpdatedAt"] {683 t.Errorf(mismatchErrorString("UpdatedAt", got.UpdatedAt, update["UpdatedAt"]))684 }685}686func TestTopicOwnerChange(t *testing.T) {687 err := adp.TopicOwnerChange(topics[0].Id, types.ParseUserId("usr"+users[1].Id))688 if err != nil {689 t.Fatal(err)690 }691 var got types.Topic692 _ = db.Collection("topics").FindOne(ctx, b.M{"_id": topics[0].Id}).Decode(&got)693 if got.Owner != users[1].Id {694 t.Errorf(mismatchErrorString("Owner", got.Owner, users[1].Id))695 }696}697func TestSubsUpdate(t *testing.T) {698 update := map[string]interface{}{699 "UpdatedAt": now.Add(22 * time.Minute),700 }701 err := adp.SubsUpdate(topics[0].Id, types.ParseUserId("usr"+users[0].Id), update)702 if err != nil {703 t.Fatal(err)704 }705 var got types.Subscription706 _ = db.Collection("subscriptions").FindOne(ctx, b.M{"_id": topics[0].Id + ":" + users[0].Id}).Decode(&got)707 if got.UpdatedAt != update["UpdatedAt"] {708 t.Errorf(mismatchErrorString("UpdatedAt", got.UpdatedAt, update["UpdatedAt"]))709 }710 err = adp.SubsUpdate(topics[1].Id, types.ZeroUid, update)711 if err != nil {712 t.Fatal(err)713 }714 _ = db.Collection("subscriptions").FindOne(ctx, b.M{"topic": topics[1].Id}).Decode(&got)715 if got.UpdatedAt != update["UpdatedAt"] {716 t.Errorf(mismatchErrorString("UpdatedAt", got.UpdatedAt, update["UpdatedAt"]))717 }718}719func TestSubsDelete(t *testing.T) {720 err := adp.SubsDelete(topics[1].Id, types.ParseUserId("usr"+users[0].Id))721 if err != nil {722 t.Fatal(err)723 }724 var got types.Subscription725 _ = db.Collection("subscriptions").FindOne(ctx, b.M{"_id": topics[1].Id + ":" + users[0].Id}).Decode(&got)726 if got.DeletedAt == nil {727 t.Errorf(mismatchErrorString("DeletedAt", got.DeletedAt, nil))728 }729}730func TestDeviceUpsert(t *testing.T) {731 err := adp.DeviceUpsert(types.ParseUserId("usr"+users[0].Id), devs[0])732 if err != nil {733 t.Fatal(err)734 }735 var got types.User736 err = db.Collection("users").FindOne(ctx, b.M{"_id": users[0].Id}).Decode(&got)737 if err != nil {738 t.Error(err)739 }740 if !reflect.DeepEqual(got.DeviceArray[0], devs[0]) {741 t.Error(mismatchErrorString("Device", got.DeviceArray[0], devs[0]))742 }743 // Test update744 devs[0].Platform = "Web"745 err = adp.DeviceUpsert(types.ParseUserId("usr"+users[0].Id), devs[0])746 if err != nil {747 t.Fatal(err)748 }749 err = db.Collection("users").FindOne(ctx, b.M{"_id": users[0].Id}).Decode(&got)750 if err != nil {751 t.Error(err)752 }753 if got.DeviceArray[0].Platform != "Web" {754 t.Error("Device not updated.", got.DeviceArray[0])755 }756 // Test add same device to another user757 err = adp.DeviceUpsert(types.ParseUserId("usr"+users[1].Id), devs[0])758 if err != nil {759 t.Fatal(err)760 }761 err = db.Collection("users").FindOne(ctx, b.M{"_id": users[1].Id}).Decode(&got)762 if err != nil {763 t.Error(err)764 }765 if got.DeviceArray[0].Platform != "Web" {766 t.Error("Device not updated.", got.DeviceArray[0])767 }768 err = adp.DeviceUpsert(types.ParseUserId("usr"+users[2].Id), devs[1])769 if err != nil {770 t.Error(err)771 }772}773func TestMessageAttachments(t *testing.T) {774 fids := []string{files[0].Id, files[1].Id}775 err := adp.MessageAttachments(types.ParseUid(msgs[1].Id), fids)776 if err != nil {777 t.Fatal(err)778 }779 var got map[string][]string780 findOpts := mdbopts.FindOne().SetProjection(b.M{"attachments": 1, "_id": 0})781 err = db.Collection("messages").FindOne(ctx, b.M{"_id": msgs[1].Id}, findOpts).Decode(&got)782 if err != nil {783 t.Fatal(err)784 }785 if !reflect.DeepEqual(got["attachments"], fids) {786 t.Error(mismatchErrorString("Attachments", got["attachments"], fids))787 }788 var got2 map[string]int789 findOpts = mdbopts.FindOne().SetProjection(b.M{"usecount": 1, "_id": 0})790 err = db.Collection("fileuploads").FindOne(ctx, b.M{"_id": files[0].Id}, findOpts).Decode(&got2)791 if err != nil {792 t.Fatal(err)793 }794 if got2["usecount"] != 1 {795 t.Error(mismatchErrorString("UseCount", got2["usecount"], 1))796 }797}798func TestFileFinishUpload(t *testing.T) {799 got, err := adp.FileFinishUpload(files[0].Id, types.UploadCompleted, 22222)800 if err != nil {801 t.Fatal(err)802 }803 if got.Status != types.UploadCompleted {804 t.Error(mismatchErrorString("Status", got.Status, types.UploadCompleted))805 }806 if got.Size != 22222 {807 t.Error(mismatchErrorString("Size", got.Size, 22222))808 }809}810// ================== Other tests =================================811func TestDeviceGetAll(t *testing.T) {812 uid0 := types.ParseUserId("usr" + users[0].Id)813 uid1 := types.ParseUserId("usr" + users[1].Id)814 uid2 := types.ParseUserId("usr" + users[2].Id)815 gotDevs, count, err := adp.DeviceGetAll(uid0, uid1, uid2)816 if err != nil {817 t.Fatal(err)818 }819 if count != 2 {820 t.Fatal(mismatchErrorString("count", count, 2))821 }822 if !reflect.DeepEqual(gotDevs[uid1][0], *devs[0]) {823 t.Error(mismatchErrorString("Device", gotDevs[uid1][0], *devs[0]))824 }825 if !reflect.DeepEqual(gotDevs[uid2][0], *devs[1]) {826 t.Error(mismatchErrorString("Device", gotDevs[uid2][0], *devs[1]))827 }828}829func TestDeviceDelete(t *testing.T) {830 err := adp.DeviceDelete(types.ParseUserId("usr"+users[1].Id), devs[0].DeviceId)831 if err != nil {832 t.Fatal(err)833 }834 var got types.User835 err = db.Collection("users").FindOne(ctx, b.M{"_id": users[1].Id}).Decode(&got)836 if err != nil {837 t.Fatal(err)838 }839 if len(got.DeviceArray) != 0 {840 t.Error("Device not deleted:", got.DeviceArray)841 }842 err = adp.DeviceDelete(types.ParseUserId("usr"+users[2].Id), "")843 if err != nil {844 t.Fatal(err)845 }846 err = db.Collection("users").FindOne(ctx, b.M{"_id": users[2].Id}).Decode(&got)847 if err != nil {848 t.Fatal(err)849 }850 if len(got.DeviceArray) != 0 {851 t.Error("Device not deleted:", got.DeviceArray)852 }853}854// ================== Delete tests ================================855func TestCredDel(t *testing.T) {856 err := adp.CredDel(types.ParseUserId("usr"+users[0].Id), "email", "alice@test.example.com")857 if err != nil {858 t.Fatal(err)859 }860 var got []map[string]interface{}861 cur, err := db.Collection("credentials").Find(ctx, b.M{"method": "email", "value": "alice@test.example.com"})862 if err != nil {863 t.Fatal(err)864 }865 if err = cur.All(ctx, &got); err != nil {866 t.Fatal(err)867 }868 if len(got) != 0 {869 t.Error("Got result but shouldn't", got)870 }871 err = adp.CredDel(types.ParseUserId("usr"+users[1].Id), "", "")872 if err != nil {873 t.Fatal(err)874 }875 cur, err = db.Collection("credentials").Find(ctx, b.M{"user": users[1].Id})876 if err != nil {877 t.Fatal(err)878 }879 if err = cur.All(ctx, &got); err != nil {880 t.Fatal(err)881 }882 if len(got) != 0 {883 t.Error("Got result but shouldn't", got)884 }885}886func TestAuthDelScheme(t *testing.T) {887 // tested during TestAuthUpdRecord888}889func TestAuthDelAllRecords(t *testing.T) {890 delCount, err := adp.AuthDelAllRecords(types.ParseUserId("usr" + recs[0].UserId))891 if err != nil {892 t.Fatal(err)893 }894 if delCount != 1 {895 t.Errorf(mismatchErrorString("delCount", delCount, 1))896 }897 // With dummy user898 delCount, _ = adp.AuthDelAllRecords(types.ParseUserId("dummyuserid"))899 if delCount != 0 {900 t.Errorf(mismatchErrorString("delCount", delCount, 0))901 }902}903func TestSubsDelForTopic(t *testing.T) {904 // Soft905 err := adp.SubsDelForTopic(topics[1].Id, false)906 if err != nil {907 t.Fatal(err)908 }909 var got types.Subscription910 _ = db.Collection("subscriptions").FindOne(ctx, b.M{"topic": topics[1].Id}).Decode(&got)911 if got.DeletedAt == nil {912 t.Errorf(mismatchErrorString("DeletedAt", got.DeletedAt, nil))913 }914 // Hard915 err = adp.SubsDelForTopic(topics[1].Id, true)916 if err != nil {917 t.Fatal(err)918 }919 err = db.Collection("subscriptions").FindOne(ctx, b.M{"topic": topics[1].Id}).Decode(&got)920 if err != mdb.ErrNoDocuments {921 t.Error("Sub not deleted. Err:", err)922 }923}924func TestSubsDelForUser(t *testing.T) {925 // Tested during TestUserDelete (both hard and soft deletions)926}927func TestMessageDeleteList(t *testing.T) {928 toDel := types.DelMessage{929 ObjHeader: types.ObjHeader{930 Id: uGen.GetStr(),931 CreatedAt: now,932 UpdatedAt: now,933 },934 Topic: topics[1].Id,935 DeletedFor: users[2].Id,936 DelId: 1,937 SeqIdRanges: []types.Range{{Low: 9}, {Low: 3, Hi: 7}},938 }939 err := adp.MessageDeleteList(toDel.Topic, &toDel)940 if err != nil {941 t.Fatal(err)942 }943 var got []types.Message944 cur, err := db.Collection("messages").Find(ctx, b.M{"topic": toDel.Topic})945 if err != nil {946 t.Fatal(err)947 }948 if err = cur.All(ctx, &got); err != nil {949 t.Fatal(err)950 }951 for _, msg := range got {952 if msg.SeqId == 1 && msg.DeletedFor != nil {953 t.Error("Message with SeqID=1 should not be deleted")954 }955 if msg.SeqId == 5 && msg.DeletedFor == nil {956 t.Error("Message with SeqID=5 should be deleted")957 }958 if msg.SeqId == 11 && msg.DeletedFor == nil {959 t.Error("Message with SeqID=5 should be deleted")960 }961 }962 //963 toDel = types.DelMessage{964 ObjHeader: types.ObjHeader{965 Id: uGen.GetStr(),966 CreatedAt: now,967 UpdatedAt: now,968 },969 Topic: topics[0].Id,970 DelId: 3,971 SeqIdRanges: []types.Range{{Low: 1, Hi: 3}},972 }973 err = adp.MessageDeleteList(toDel.Topic, &toDel)974 if err != nil {975 t.Fatal(err)976 }977 cur, err = db.Collection("messages").Find(ctx, b.M{"topic": toDel.Topic})978 if err != nil {979 t.Fatal(err)980 }981 if err = cur.All(ctx, &got); err != nil {982 t.Fatal(err)983 }984 for _, msg := range got {985 if msg.Content != nil {986 t.Error("Message not deleted:", msg)987 }988 }989 err = adp.MessageDeleteList(topics[0].Id, nil)990 if err != nil {991 t.Fatal(err)992 }993 cur, err = db.Collection("messages").Find(ctx, b.M{"topic": topics[0].Id})994 if err != nil {995 t.Fatal(err)996 }997 if err = cur.All(ctx, &got); err != nil {998 t.Fatal(err)999 }1000 if len(got) != 0 {1001 t.Error("Result should be empty:", got)1002 }1003}1004func TestTopicDelete(t *testing.T) {1005 err := adp.TopicDelete(topics[1].Id, false)1006 if err != nil {1007 t.Fatal()1008 }1009 var got types.Topic1010 cur, err := db.Collection("topics").Find(ctx, b.M{"topic": topics[1].Id})1011 if err != nil {1012 t.Fatal(err)1013 }1014 for cur.Next(ctx) {1015 if err = cur.Decode(&got); err != nil {1016 t.Error(err)1017 }1018 if got.DeletedAt == nil {1019 t.Error("Soft delete failed:", got)1020 }1021 }1022 err = adp.TopicDelete(topics[0].Id, true)1023 if err != nil {1024 t.Fatal()1025 }1026 var got2 []types.Topic1027 cur, err = db.Collection("topics").Find(ctx, b.M{"topic": topics[0].Id})1028 if err != nil {1029 t.Fatal(err)1030 }1031 if err = cur.All(ctx, &got2); err != nil {1032 t.Fatal(err)1033 }1034 if len(got2) != 0 {1035 t.Error("Hard delete failed:", got2)1036 }1037}1038func TestFileDeleteUnused(t *testing.T) {1039 locs, err := adp.FileDeleteUnused(now.Add(1*time.Minute), 999)1040 if err != nil {1041 t.Fatal(err)1042 }1043 if len(locs) == 0 {1044 t.Error(mismatchErrorString("Locations length", len(locs), 0))1045 }1046}1047func TestUserDelete(t *testing.T) {1048 err := adp.UserDelete(types.ParseUserId("usr"+users[0].Id), false)1049 if err != nil {1050 t.Fatal(err)1051 }1052 var got types.User1053 err = db.Collection("users").FindOne(ctx, b.M{"_id": users[0].Id}).Decode(&got)1054 if err != nil {1055 t.Fatal(err)1056 }1057 if got.DeletedAt == nil {1058 t.Error("User soft delete failed", got)1059 }1060 err = adp.UserDelete(types.ParseUserId("usr"+users[1].Id), true)1061 if err != nil {1062 t.Fatal(err)1063 }1064 err = db.Collection("users").FindOne(ctx, b.M{"_id": users[1].Id}).Decode(&got)1065 if err != mdb.ErrNoDocuments {1066 t.Error("User hard delete failed", err)1067 }1068}1069// ================== Other tests =================================1070func TestMessageGetDeleted(t *testing.T) {1071 qOpts := types.QueryOpt{1072 Since: 1,1073 Before: 10,1074 Limit: 999,1075 }1076 got, err := adp.MessageGetDeleted(topics[1].Id, types.ParseUserId("usr"+users[2].Id), &qOpts)1077 if err != nil {1078 t.Fatal(err)1079 }1080 if len(got) != 1 {1081 t.Error(mismatchErrorString("result length", len(got), 1))1082 }1083}1084// ================================================================1085func mismatchErrorString(key string, got, want interface{}) string {1086 return fmt.Sprintf("%v mismatch:\nGot = %v\nWant = %v", key, got, want)1087}1088func initConnectionToDb() {1089 var adpConfig struct {1090 Addresses interface{} `json:"addresses,omitempty"`1091 Database string `json:"database,omitempty"`1092 }1093 if err := json.Unmarshal(config.Adapters[adp.GetName()], &adpConfig); err != nil {1094 log.Fatal("adapter mongodb failed to parse config: " + err.Error())1095 }1096 var opts mdbopts.ClientOptions1097 if adpConfig.Addresses == nil {1098 opts.SetHosts([]string{"localhost:27017"})1099 } else if host, ok := adpConfig.Addresses.(string); ok {1100 opts.SetHosts([]string{host})1101 } else if hosts, ok := adpConfig.Addresses.([]string); ok {1102 opts.SetHosts(hosts)1103 } else {1104 log.Fatal("adapter mongodb failed to parse config.Addresses")1105 }1106 if adpConfig.Database == "" {1107 adpConfig.Database = "tinode_test"1108 }1109 ctx = context.Background()1110 conn, err := mdb.Connect(ctx, &opts)1111 if err != nil {1112 log.Fatal(err)1113 }1114 db = conn.Database(adpConfig.Database)1115}1116func init() {1117 adp = backend.GetAdapter()1118 conffile := flag.String("config", "./test.conf", "config of the database connection")1119 if file, err := os.Open(*conffile); err != nil {1120 log.Fatal("Failed to read config file:", err)1121 } else if err = json.NewDecoder(jcr.New(file)).Decode(&config); err != nil {1122 log.Fatal("Failed to parse config file:", err)1123 }1124 if adp == nil {1125 log.Fatal("Database adapter is missing")1126 }1127 if adp.IsOpen() {1128 log.Print("Connection is already opened")1129 }1130 err := adp.Open(config.Adapters[adp.GetName()])1131 if err != nil {1132 log.Fatal(err)1133 }1134 if err := uGen.Init(11, []byte("testtesttesttest")); err != nil {1135 log.Fatal(err)1136 }1137 initConnectionToDb()1138 initData()1139}...
array_test.go
Source:array_test.go
...24 {"test string", mockJArray(`["non-value", "test"]`), args{0}, 0, true},25 }26 for _, tt := range tests {27 t.Run(tt.name, func(t *testing.T) {28 got, err := tt.a.GetFloat32(tt.args.i)29 if (err != nil) != tt.wantErr {30 t.Errorf("GetFloat32() error = %v, wantErr %v", err, tt.wantErr)31 return32 }33 if got != tt.want {34 t.Errorf("GetFloat32() got = %v, want %v", got, tt.want)35 }36 })37 }38}39func TestJArray_GetFloat64(t *testing.T) {40 type args struct {41 i int42 }43 tests := []struct {44 name string45 a JArray46 args args47 want float6448 wantErr bool49 }{50 {"test float value", mockJArray(`[3.5, 4.5]`), args{1}, 4.5, false},51 {"test int value", mockJArray(`[3, 4]`), args{0}, 3.0, false},52 {"test string int value", mockJArray(`["3", "4"]`), args{0}, 3.0, false},53 {"test string", mockJArray(`["non-value", "test"]`), args{0}, 0, true},54 }55 for _, tt := range tests {56 t.Run(tt.name, func(t *testing.T) {57 got, err := tt.a.GetFloat64(tt.args.i)58 if (err != nil) != tt.wantErr {59 t.Errorf("GetFloat64() error = %v, wantErr %v", err, tt.wantErr)60 return61 }62 if got != tt.want {63 t.Errorf("GetFloat64() got = %v, want %v", got, tt.want)64 }65 })66 }67}68func TestJArray_GetInt(t *testing.T) {69 type args struct {70 i int71 }72 tests := []struct {73 name string74 a JArray75 args args76 want int77 wantErr bool78 }{79 {"test float value", mockJArray(`[3.5, 4.5]`), args{1}, 0, true},80 {"test int value", mockJArray(`[3, 4]`), args{0}, 3, false},81 {"test string int value", mockJArray(`["3", "4"]`), args{0}, 3, false},82 {"test string", mockJArray(`["non-value", "test"]`), args{0}, 0, true},83 }84 for _, tt := range tests {85 t.Run(tt.name, func(t *testing.T) {86 got, err := tt.a.GetInt(tt.args.i)87 if (err != nil) != tt.wantErr {88 t.Errorf("GetInt() error = %v, wantErr %v", err, tt.wantErr)89 return90 }91 if got != tt.want {92 t.Errorf("GetInt() got = %v, want %v", got, tt.want)93 }94 })95 }96}97func TestJArray_GetInt16(t *testing.T) {98 type args struct {99 i int100 }101 tests := []struct {102 name string103 a JArray104 args args105 want int16106 wantErr bool107 }{108 {"test float value", mockJArray(`[3.5, 4.5]`), args{1}, 0, true},109 {"test int value", mockJArray(`[3, 4]`), args{0}, 3, false},110 {"test big int value", mockJArray(`[3000000000, 4]`), args{0}, 0, true},111 {"test string int value", mockJArray(`["3", "4"]`), args{0}, 3, false},112 {"test string big int value", mockJArray(`["3000000000", "4"]`), args{0}, 0, true},113 {"test string", mockJArray(`["non-value", "test"]`), args{0}, 0, true},114 }115 for _, tt := range tests {116 t.Run(tt.name, func(t *testing.T) {117 got, err := tt.a.GetInt16(tt.args.i)118 if (err != nil) != tt.wantErr {119 t.Errorf("GetInt16() error = %v, wantErr %v", err, tt.wantErr)120 return121 }122 if got != tt.want {123 t.Errorf("GetInt16() got = %v, want %v", got, tt.want)124 }125 })126 }127}128func TestJArray_GetInt32(t *testing.T) {129 type args struct {130 i int131 }132 tests := []struct {133 name string134 a JArray135 args args136 want int32137 wantErr bool138 }{139 {"test float value", mockJArray(`[3.5, 4.5]`), args{1}, 0, true},140 {"test int value", mockJArray(`[3, 4]`), args{0}, 3, false},141 {"test big int value", mockJArray(`[3000000000, 4]`), args{0}, 0, true},142 {"test string int value", mockJArray(`["3", "4"]`), args{0}, 3, false},143 {"test string big int value", mockJArray(`["3000000000", "4"]`), args{0}, 0, true},144 {"test string", mockJArray(`["non-value", "test"]`), args{0}, 0, true},145 }146 for _, tt := range tests {147 t.Run(tt.name, func(t *testing.T) {148 got, err := tt.a.GetInt32(tt.args.i)149 if (err != nil) != tt.wantErr {150 t.Errorf("GetInt32() error = %v, wantErr %v", err, tt.wantErr)151 return152 }153 if got != tt.want {154 t.Errorf("GetInt32() got = %v, want %v", got, tt.want)155 }156 })157 }158}159func TestJArray_GetInt64(t *testing.T) {160 type args struct {161 i int162 }163 tests := []struct {164 name string165 a JArray166 args args167 want int64168 wantErr bool169 }{170 {"test float value", mockJArray(`[3.5, 4.5]`), args{1}, 0, true},171 {"test int value", mockJArray(`[3, 4]`), args{0}, 3, false},172 {"test big int value", mockJArray(`[30000000000000000000000000000000000, 4]`), args{0}, 0, true},173 {"test string int value", mockJArray(`["3", "4"]`), args{0}, 3, false},174 {"test string big int value", mockJArray(`["30000000000000000000000000000000000", "4"]`), args{0}, 0, true},175 {"test string", mockJArray(`["non-value", "test"]`), args{0}, 0, true},176 }177 for _, tt := range tests {178 t.Run(tt.name, func(t *testing.T) {179 got, err := tt.a.GetInt64(tt.args.i)180 if (err != nil) != tt.wantErr {181 t.Errorf("GetInt64() error = %v, wantErr %v", err, tt.wantErr)182 return183 }184 if got != tt.want {185 t.Errorf("GetInt64() got = %v, want %v", got, tt.want)186 }187 })188 }189}190func TestJArray_GetInt8(t *testing.T) {191 type args struct {192 i int193 }194 tests := []struct {195 name string196 a JArray197 args args198 want int8199 wantErr bool200 }{201 {"test float value", mockJArray(`[3.5, 4.5]`), args{1}, 0, true},202 {"test int value", mockJArray(`[3, 4]`), args{0}, 3, false},203 {"test big int value", mockJArray(`[3000000000, 4]`), args{0}, 0, true},204 {"test string int value", mockJArray(`["3", "4"]`), args{0}, 3, false},205 {"test string big int value", mockJArray(`["3000000000", "4"]`), args{0}, 0, true},206 {"test string", mockJArray(`["non-value", "test"]`), args{0}, 0, true},207 }208 for _, tt := range tests {209 t.Run(tt.name, func(t *testing.T) {210 got, err := tt.a.GetInt8(tt.args.i)211 if (err != nil) != tt.wantErr {212 t.Errorf("GetInt8() error = %v, wantErr %v", err, tt.wantErr)213 return214 }215 if got != tt.want {216 t.Errorf("GetInt8() got = %v, want %v", got, tt.want)217 }218 })219 }220}221func TestJArray_GetJArray(t *testing.T) {222 type args struct {223 i int224 }225 tests := []struct {226 name string227 a JArray228 args args229 want JArray230 wantErr bool231 }{232 {"test value slice", mockJArray(`[1, 2, 3]`), args{0}, nil, true},233 {"test int slice", mockJArray(`[[1, 2, 3], [4, 5, 6]]`), args{0}, mockJArray(`[1, 2, 3]`), false},234 {"test float slice", mockJArray(`[[1.1, 2.2, 3.3], [4.4, 5.5, 6.6]]`), args{0}, mockJArray(`[1.1, 2.2, 3.3]`), false},235 {"test string slice", mockJArray(`[["hello", "world"], ["this", "is", "json"]]`), args{0}, mockJArray(`["hello", "world"]`), false},236 }237 for _, tt := range tests {238 t.Run(tt.name, func(t *testing.T) {239 got, err := tt.a.GetJArray(tt.args.i)240 if (err != nil) != tt.wantErr {241 t.Errorf("GetJArray() error = %v, wantErr %v", err, tt.wantErr)242 return243 }244 if !reflect.DeepEqual(got, tt.want) {245 t.Errorf("GetJArray() got = %v, want %v", got, tt.want)246 }247 })248 }249}250func TestJArray_GetJObject(t *testing.T) {251 type args struct {252 i int253 }254 tests := []struct {255 name string256 a JArray257 args args258 want JObject259 wantErr bool260 }{261 {"test obj slice", mockJArray(`[{"k": 1}]`), args{0}, mockJObject(`{"k": 1}`), false},262 {"test int slice", mockJArray(`[1, 2, 3]`), args{0}, nil, true},263 }264 for _, tt := range tests {265 t.Run(tt.name, func(t *testing.T) {266 got, err := tt.a.GetJObject(tt.args.i)267 if (err != nil) != tt.wantErr {268 t.Errorf("GetJObject() error = %v, wantErr %v", err, tt.wantErr)269 return270 }271 if !reflect.DeepEqual(got, tt.want) {272 t.Errorf("GetJObject() got = %v, want %v", got, tt.want)273 }274 })275 }276}277func TestJArray_GetString(t *testing.T) {278 type args struct {279 i int280 }281 tests := []struct {282 name string283 a JArray284 args args285 want string286 wantErr bool287 }{288 {"test obj slice", mockJArray(`[{"k": 1}]`), args{0}, `{"k":1}`, false},289 {"test int slice", mockJArray(`[1, 2, 3]`), args{0}, "1", false},290 {"test float slice", mockJArray(`[1.1, 2.2, 3.3]`), args{0}, "1.1", false},291 {"test string slice", mockJArray(`["this", "is", "json"]`), args{2}, "json", false},292 }293 for _, tt := range tests {294 t.Run(tt.name, func(t *testing.T) {295 got, err := tt.a.GetString(tt.args.i)296 if (err != nil) != tt.wantErr {297 t.Errorf("GetString() error = %v, wantErr %v", err, tt.wantErr)298 return299 }300 if got != tt.want {301 t.Errorf("GetString() got = %v, want %v", got, tt.want)302 }303 })304 }305}306func TestJArray_GetUint16(t *testing.T) {307 type args struct {308 i int309 }310 tests := []struct {311 name string312 a JArray313 args args314 want uint16315 wantErr bool316 }{317 {"test float value", mockJArray(`[3.5, 4.5]`), args{1}, 0, true},318 {"test int value", mockJArray(`[3, 4]`), args{0}, 3, false},319 {"test big int value", mockJArray(`[3000000000, 4]`), args{0}, 0, true},320 {"test string int value", mockJArray(`["3", "4"]`), args{0}, 3, false},321 {"test string big int value", mockJArray(`["3000000000", "4"]`), args{0}, 0, true},322 {"test string", mockJArray(`["non-value", "test"]`), args{0}, 0, true},323 }324 for _, tt := range tests {325 t.Run(tt.name, func(t *testing.T) {326 got, err := tt.a.GetUint16(tt.args.i)327 if (err != nil) != tt.wantErr {328 t.Errorf("GetUint16() error = %v, wantErr %v", err, tt.wantErr)329 return330 }331 if got != tt.want {332 t.Errorf("GetUint16() got = %v, want %v", got, tt.want)333 }334 })335 }336}337func TestJArray_GetUint32(t *testing.T) {338 type args struct {339 i int340 }341 tests := []struct {342 name string343 a JArray344 args args345 want uint32346 wantErr bool347 }{348 {"test float value", mockJArray(`[3.5, 4.5]`), args{1}, 0, true},349 {"test int value", mockJArray(`[3, 4]`), args{0}, 3, false},350 {"test big int value", mockJArray(`[8000000000, 4]`), args{0}, 0, true},351 {"test string int value", mockJArray(`["3", "4"]`), args{0}, 3, false},352 {"test string big int value", mockJArray(`["8000000000", "4"]`), args{0}, 0, true},353 {"test string", mockJArray(`["non-value", "test"]`), args{0}, 0, true},354 }355 for _, tt := range tests {356 t.Run(tt.name, func(t *testing.T) {357 got, err := tt.a.GetUint32(tt.args.i)358 if (err != nil) != tt.wantErr {359 t.Errorf("GetUint32() error = %v, wantErr %v", err, tt.wantErr)360 return361 }362 if got != tt.want {363 t.Errorf("GetUint32() got = %v, want %v", got, tt.want)364 }365 })366 }367}368func TestJArray_GetUint64(t *testing.T) {369 type args struct {370 i int371 }372 tests := []struct {373 name string374 a JArray375 args args376 want uint64377 wantErr bool378 }{379 {"test float value", mockJArray(`[3.5, 4.5]`), args{1}, 0, true},380 {"test int value", mockJArray(`[3, 4]`), args{0}, 3, false},381 {"test big int value", mockJArray(`[30000000000000000000000, 4]`), args{0}, 0, true},382 {"test string int value", mockJArray(`["3", "4"]`), args{0}, 3, false},383 {"test string big int value", mockJArray(`["30000000000000000000000", "4"]`), args{0}, 0, true},384 {"test string", mockJArray(`["non-value", "test"]`), args{0}, 0, true},385 }386 for _, tt := range tests {387 t.Run(tt.name, func(t *testing.T) {388 got, err := tt.a.GetUint64(tt.args.i)389 if (err != nil) != tt.wantErr {390 t.Errorf("GetUint64() error = %v, wantErr %v", err, tt.wantErr)391 return392 }393 if got != tt.want {394 t.Errorf("GetUint64() got = %v, want %v", got, tt.want)395 }396 })397 }398}399func TestJArray_GetUint8(t *testing.T) {400 type args struct {401 i int402 }403 tests := []struct {404 name string405 a JArray406 args args407 want uint8408 wantErr bool409 }{410 {"test float value", mockJArray(`[3.5, 4.5]`), args{1}, 0, true},411 {"test int value", mockJArray(`[3, 4]`), args{0}, 3, false},412 {"test big int value", mockJArray(`[3000000000, 4]`), args{0}, 0, true},413 {"test string int value", mockJArray(`["3", "4"]`), args{0}, 3, false},414 {"test string big int value", mockJArray(`["3000000000", "4"]`), args{0}, 0, true},415 {"test string", mockJArray(`["non-value", "test"]`), args{0}, 0, true},416 }417 for _, tt := range tests {418 t.Run(tt.name, func(t *testing.T) {419 got, err := tt.a.GetUint8(tt.args.i)420 if (err != nil) != tt.wantErr {421 t.Errorf("GetUint8() error = %v, wantErr %v", err, tt.wantErr)422 return423 }424 if got != tt.want {425 t.Errorf("GetUint8() got = %v, want %v", got, tt.want)426 }427 })428 }429}430func TestJArray_ToFloat32Slice(t *testing.T) {431 tests := []struct {432 name string433 a JArray434 want []float32435 wantErr bool436 }{437 {"test string value", mockJArray(`["3.5", "4.5"]`), []float32{3.5, 4.5}, false},438 {"test float value", mockJArray(`[3.5, 4.5]`), []float32{3.5, 4.5}, false},439 {"test int value", mockJArray(`[1, 2, 3]`), []float32{1, 2, 3}, false},440 }441 for _, tt := range tests {442 t.Run(tt.name, func(t *testing.T) {443 got, err := tt.a.ToFloat32Slice()444 if (err != nil) != tt.wantErr {445 t.Errorf("ToFloat32Slice() error = %v, wantErr %v", err, tt.wantErr)446 return447 }448 if !reflect.DeepEqual(got, tt.want) {449 t.Errorf("ToFloat32Slice() got = %v, want %v", got, tt.want)450 }451 })452 }453}454func TestJArray_ToFloat64Slice(t *testing.T) {455 tests := []struct {456 name string457 a JArray458 want []float64459 wantErr bool460 }{461 {"test string value", mockJArray(`["3.5", "4.5"]`), []float64{3.5, 4.5}, false},462 {"test float value", mockJArray(`[3.5, 4.5]`), []float64{3.5, 4.5}, false},463 {"test int value", mockJArray(`[1, 2, 3]`), []float64{1, 2, 3}, false},464 }465 for _, tt := range tests {466 t.Run(tt.name, func(t *testing.T) {467 got, err := tt.a.ToFloat64Slice()468 if (err != nil) != tt.wantErr {469 t.Errorf("ToFloat64Slice() error = %v, wantErr %v", err, tt.wantErr)470 return471 }472 if !reflect.DeepEqual(got, tt.want) {473 t.Errorf("ToFloat64Slice() got = %v, want %v", got, tt.want)474 }475 })476 }477}478func TestJArray_ToInt16Slice(t *testing.T) {479 tests := []struct {480 name string481 a JArray482 want []int16483 wantErr bool484 }{485 {"test string value", mockJArray(`["3", "4"]`), []int16{3, 4}, false},486 {"test float value", mockJArray(`[3.5, 4.5]`), nil, true},487 {"test int value", mockJArray(`[1, 2, 3]`), []int16{1, 2, 3}, false},488 }489 for _, tt := range tests {490 t.Run(tt.name, func(t *testing.T) {491 got, err := tt.a.ToInt16Slice()492 if (err != nil) != tt.wantErr {493 t.Errorf("ToInt16Slice() error = %v, wantErr %v", err, tt.wantErr)494 return495 }496 if !reflect.DeepEqual(got, tt.want) {497 t.Errorf("ToInt16Slice() got = %v, want %v", got, tt.want)498 }499 })500 }501}502func TestJArray_ToInt32Slice(t *testing.T) {503 tests := []struct {504 name string505 a JArray506 want []int32507 wantErr bool508 }{509 {"test string value", mockJArray(`["3", "4"]`), []int32{3, 4}, false},510 {"test float value", mockJArray(`[3.5, 4.5]`), nil, true},511 {"test int value", mockJArray(`[1, 2, 3]`), []int32{1, 2, 3}, false},512 }513 for _, tt := range tests {514 t.Run(tt.name, func(t *testing.T) {515 got, err := tt.a.ToInt32Slice()516 if (err != nil) != tt.wantErr {517 t.Errorf("ToInt32Slice() error = %v, wantErr %v", err, tt.wantErr)518 return519 }520 if !reflect.DeepEqual(got, tt.want) {521 t.Errorf("ToInt32Slice() got = %v, want %v", got, tt.want)522 }523 })524 }525}526func TestJArray_ToInt64Slice(t *testing.T) {527 tests := []struct {528 name string529 a JArray530 want []int64531 wantErr bool532 }{533 {"test string value", mockJArray(`["3", "4"]`), []int64{3, 4}, false},534 {"test float value", mockJArray(`[3.5, 4.5]`), nil, true},535 {"test int value", mockJArray(`[1, 2, 3]`), []int64{1, 2, 3}, false},536 }537 for _, tt := range tests {538 t.Run(tt.name, func(t *testing.T) {539 got, err := tt.a.ToInt64Slice()540 if (err != nil) != tt.wantErr {541 t.Errorf("ToInt64Slice() error = %v, wantErr %v", err, tt.wantErr)542 return543 }544 if !reflect.DeepEqual(got, tt.want) {545 t.Errorf("ToInt64Slice() got = %v, want %v", got, tt.want)546 }547 })548 }549}550func TestJArray_ToInt8Slice(t *testing.T) {551 tests := []struct {552 name string553 a JArray554 want []int8555 wantErr bool556 }{557 {"test string value", mockJArray(`["3", "4"]`), []int8{3, 4}, false},558 {"test float value", mockJArray(`[3.5, 4.5]`), nil, true},559 {"test int value", mockJArray(`[1, 2, 3]`), []int8{1, 2, 3}, false},560 }561 for _, tt := range tests {562 t.Run(tt.name, func(t *testing.T) {563 got, err := tt.a.ToInt8Slice()564 if (err != nil) != tt.wantErr {565 t.Errorf("ToInt8Slice() error = %v, wantErr %v", err, tt.wantErr)566 return567 }568 if !reflect.DeepEqual(got, tt.want) {569 t.Errorf("ToInt8Slice() got = %v, want %v", got, tt.want)570 }571 })572 }573}574func TestJArray_ToIntSlice(t *testing.T) {575 tests := []struct {576 name string577 a JArray578 want []int579 wantErr bool580 }{581 {"test string value", mockJArray(`["3", "4"]`), []int{3, 4}, false},582 {"test float value", mockJArray(`[3.5, 4.5]`), nil, true},583 {"test int value", mockJArray(`[1, 2, 3]`), []int{1, 2, 3}, false},584 }585 for _, tt := range tests {586 t.Run(tt.name, func(t *testing.T) {587 got, err := tt.a.ToIntSlice()588 if (err != nil) != tt.wantErr {589 t.Errorf("ToIntSlice() error = %v, wantErr %v", err, tt.wantErr)590 return591 }592 if !reflect.DeepEqual(got, tt.want) {593 t.Errorf("ToIntSlice() got = %v, want %v", got, tt.want)594 }595 })596 }597}598func TestJArray_ToJArraySlice(t *testing.T) {599 tests := []struct {600 name string601 a JArray602 want []JArray603 wantErr bool604 }{605 {"test string value", mockJArray(`[["3", "4"]]`), []JArray{[]interface{}{"3", "4"}}, false},606 {"test float value", mockJArray(`[[3.5, 4.5]]`), []JArray{[]interface{}{3.5, 4.5}}, false},607 {"test int value", mockJArray(`[[1, 2, 3]]`), []JArray{[]interface{}{1.0, 2.0, 3.0}}, false},608 }609 for _, tt := range tests {610 t.Run(tt.name, func(t *testing.T) {611 got, err := tt.a.ToJArraySlice()612 if (err != nil) != tt.wantErr {613 t.Errorf("ToJArraySlice() error = %v, wantErr %v", err, tt.wantErr)614 return615 }616 if !reflect.DeepEqual(got, tt.want) {617 t.Errorf("ToJArraySlice() got = %v, want %v", got, tt.want)618 }619 })620 }621}622func TestJArray_ToJObjectSlice(t *testing.T) {623 tests := []struct {624 name string625 a JArray626 want []JObject627 wantErr bool628 }{629 {"test JObject", mockJArray(`[{"k": 1}]`), []JObject{map[string]interface{}{"k": 1.0}}, false},630 }631 for _, tt := range tests {632 t.Run(tt.name, func(t *testing.T) {633 got, err := tt.a.ToJObjectSlice()634 if (err != nil) != tt.wantErr {635 t.Errorf("ToJObjectSlice() error = %v, wantErr %v", err, tt.wantErr)636 return637 }638 if !reflect.DeepEqual(got, tt.want) {639 t.Errorf("ToJObjectSlice() got = %v, want %v", got, tt.want)640 }641 })642 }643}644func TestJArray_ToStringSlice(t *testing.T) {645 tests := []struct {646 name string647 a JArray648 want []string649 wantErr bool650 }{651 {"test string value", mockJArray(`["3", "4"]`), []string{"3", "4"}, false},652 {"test float value", mockJArray(`[3.5, 4.5]`), []string{"3.5", "4.5"}, false},653 {"test int value", mockJArray(`[1, 2, 3]`), []string{"1", "2", "3"}, false},654 }655 for _, tt := range tests {656 t.Run(tt.name, func(t *testing.T) {657 got, err := tt.a.ToStringSlice()658 if (err != nil) != tt.wantErr {659 t.Errorf("ToStringSlice() error = %v, wantErr %v", err, tt.wantErr)660 return661 }662 if !reflect.DeepEqual(got, tt.want) {663 t.Errorf("ToStringSlice() got = %v, want %v", got, tt.want)664 }665 })666 }667}668func TestJArray_ToUint16Slice(t *testing.T) {669 tests := []struct {670 name string671 a JArray672 want []uint16673 wantErr bool674 }{675 {"test string value", mockJArray(`["3", "4"]`), []uint16{3, 4}, false},676 {"test float value", mockJArray(`[3.5, 4.5]`), nil, true},677 {"test int value", mockJArray(`[1, 2, 3]`), []uint16{1, 2, 3}, false},678 }679 for _, tt := range tests {680 t.Run(tt.name, func(t *testing.T) {681 got, err := tt.a.ToUint16Slice()682 if (err != nil) != tt.wantErr {683 t.Errorf("ToUint16Slice() error = %v, wantErr %v", err, tt.wantErr)684 return685 }686 if !reflect.DeepEqual(got, tt.want) {687 t.Errorf("ToUint16Slice() got = %v, want %v", got, tt.want)688 }689 })690 }691}692func TestJArray_ToUint32Slice(t *testing.T) {693 tests := []struct {694 name string695 a JArray696 want []uint32697 wantErr bool698 }{699 {"test string value", mockJArray(`["3", "4"]`), []uint32{3, 4}, false},700 {"test float value", mockJArray(`[3.5, 4.5]`), nil, true},701 {"test int value", mockJArray(`[1, 2, 3]`), []uint32{1, 2, 3}, false},702 }703 for _, tt := range tests {704 t.Run(tt.name, func(t *testing.T) {705 got, err := tt.a.ToUint32Slice()706 if (err != nil) != tt.wantErr {707 t.Errorf("ToUint32Slice() error = %v, wantErr %v", err, tt.wantErr)708 return709 }710 if !reflect.DeepEqual(got, tt.want) {711 t.Errorf("ToUint32Slice() got = %v, want %v", got, tt.want)712 }713 })714 }715}716func TestJArray_ToUint64Slice(t *testing.T) {717 tests := []struct {718 name string719 a JArray720 want []uint64721 wantErr bool722 }{723 {"test string value", mockJArray(`["3", "4"]`), []uint64{3, 4}, false},724 {"test float value", mockJArray(`[3.5, 4.5]`), nil, true},725 {"test int value", mockJArray(`[1, 2, 3]`), []uint64{1, 2, 3}, false},726 }727 for _, tt := range tests {728 t.Run(tt.name, func(t *testing.T) {729 got, err := tt.a.ToUint64Slice()730 if (err != nil) != tt.wantErr {731 t.Errorf("ToUint64Slice() error = %v, wantErr %v", err, tt.wantErr)732 return733 }734 if !reflect.DeepEqual(got, tt.want) {735 t.Errorf("ToUint64Slice() got = %v, want %v", got, tt.want)736 }737 })738 }739}740func TestJArray_ToUint8Slice(t *testing.T) {741 tests := []struct {742 name string743 a JArray744 want []uint8745 wantErr bool746 }{747 {"test string value", mockJArray(`["3", "4"]`), []uint8{3, 4}, false},748 {"test float value", mockJArray(`[3.5, 4.5]`), nil, true},749 {"test int value", mockJArray(`[1, 2, 3]`), []uint8{1, 2, 3}, false},750 }751 for _, tt := range tests {752 t.Run(tt.name, func(t *testing.T) {753 got, err := tt.a.ToUint8Slice()754 if (err != nil) != tt.wantErr {755 t.Errorf("ToUint8Slice() error = %v, wantErr %v", err, tt.wantErr)756 return757 }758 if !reflect.DeepEqual(got, tt.want) {759 t.Errorf("ToUint8Slice() got = %v, want %v", got, tt.want)760 }761 })762 }763}764func TestJArray_checkIndex(t *testing.T) {765 type args struct {766 i int767 }768 tests := []struct {769 name string770 a JArray771 args args772 want bool773 }{774 {"success", []interface{}{1, 2, 3}, args{0}, true},775 {"failed", []interface{}{1, 2, 3}, args{3}, false},776 }777 for _, tt := range tests {778 t.Run(tt.name, func(t *testing.T) {779 if got := tt.a.checkIndex(tt.args.i); got != tt.want {780 t.Errorf("checkIndex() = %v, want %v", got, tt.want)781 }782 })783 }784}785func TestNewJArray(t *testing.T) {786 type args struct {787 b []byte788 }789 tests := []struct {790 name string791 args args792 want JArray793 wantErr bool794 }{795 {"json array", args{[]byte(`[1, 2, 3]`)}, []interface{}{1.0, 2.0, 3.0}, false},796 {"json object", args{[]byte(`{"k": 123}`)}, nil, true},797 {"non-json", args{[]byte(`"non-json string"`)}, nil, true},798 }799 for _, tt := range tests {800 t.Run(tt.name, func(t *testing.T) {801 got, err := NewJArray(tt.args.b)802 if (err != nil) != tt.wantErr {803 t.Errorf("NewJArray() error = %v, wantErr %v", err, tt.wantErr)804 return805 }806 if !reflect.DeepEqual(got, tt.want) {807 t.Errorf("NewJArray() got = %v, want %v", got, tt.want)808 }809 })810 }811}...
repos_test.go
Source:repos_test.go
...15 "github.com/google/go-cmp/cmp/cmpopts"16)17var noContext = context.TODO()18func TestRepo(t *testing.T) {19 conn, err := dbtest.Connect()20 if err != nil {21 t.Error(err)22 return23 }24 defer func() {25 dbtest.Reset(conn)26 dbtest.Disconnect(conn)27 }()28 store := New(conn).(*repoStore)29 t.Run("Create", testRepoCreate(store))30 t.Run("Count", testRepoCount(store))31 t.Run("Find", testRepoFind(store))32 t.Run("FindName", testRepoFindName(store))33 t.Run("List", testRepoList(store))34 t.Run("ListLatest", testRepoListLatest(store))35 t.Run("Update", testRepoUpdate(store))36 t.Run("Activate", testRepoActivate(store))37 t.Run("Locking", testRepoLocking(store))38 t.Run("Increment", testRepoIncrement(store))39 t.Run("Delete", testRepoDelete(store))40}41func testRepoCreate(repos *repoStore) func(t *testing.T) {42 return func(t *testing.T) {43 out, err := ioutil.ReadFile("testdata/repo.json")44 if err != nil {45 t.Error(err)46 return47 }48 repo := &core.Repository{}49 err = json.Unmarshal(out, repo)50 if err != nil {51 t.Error(err)52 return53 }54 err = repos.Create(noContext, repo)55 if err != nil {56 t.Error(err)57 }58 if got := repo.ID; got == 0 {59 t.Errorf("Want non-zero ID")60 }61 if got, want := repo.Version, int64(1); got != want {62 t.Errorf("Want Version %d, got %d", want, got)63 }64 err = repos.db.Update(func(execer db.Execer, binder db.Binder) error {65 query, args, _ := binder.BindNamed(stmtPermInsert, map[string]interface{}{66 "perm_user_id": 1,67 "perm_repo_uid": repo.UID,68 "perm_read": true,69 "perm_write": true,70 "perm_admin": true,71 "perm_synced": 0,72 "perm_created": 0,73 "perm_updated": 0,74 })75 _, err = execer.Exec(query, args...)76 return err77 })78 if err != nil {79 t.Error(err)80 }81 }82}83func testRepoCount(repos *repoStore) func(t *testing.T) {84 return func(t *testing.T) {85 count, err := repos.Count(noContext)86 if err != nil {87 t.Error(err)88 }89 if got, want := count, int64(1); got != want {90 t.Errorf("Want count %d, got %d", want, got)91 }92 }93}94func testRepoFind(repos *repoStore) func(t *testing.T) {95 return func(t *testing.T) {96 named, err := repos.FindName(noContext, "octocat", "hello-world")97 if err != nil {98 t.Error(err)99 return100 }101 got, err := repos.Find(noContext, named.ID)102 if err != nil {103 t.Error(err)104 return105 }106 want := &core.Repository{}107 raw, err := ioutil.ReadFile("testdata/repo.json.golden")108 if err != nil {109 t.Error(err)110 return111 }112 err = json.Unmarshal(raw, want)113 if err != nil {114 t.Error(err)115 return116 }117 ignore := cmpopts.IgnoreFields(core.Repository{}, "ID")118 if diff := cmp.Diff(got, want, ignore); len(diff) != 0 {119 t.Errorf(diff)120 }121 }122}123func testRepoFindName(repos *repoStore) func(t *testing.T) {124 return func(t *testing.T) {125 got, err := repos.FindName(noContext, "octocat", "hello-world")126 if err != nil {127 t.Error(err)128 return129 }130 want := &core.Repository{}131 raw, err := ioutil.ReadFile("testdata/repo.json.golden")132 if err != nil {133 t.Error(err)134 return135 }136 err = json.Unmarshal(raw, want)137 if err != nil {138 t.Error(err)139 return140 }141 ignore := cmpopts.IgnoreFields(core.Repository{}, "ID")142 if diff := cmp.Diff(got, want, ignore); len(diff) != 0 {143 t.Errorf(diff)144 }145 }146}147func testRepoList(repos *repoStore) func(t *testing.T) {148 return func(t *testing.T) {149 repos, err := repos.List(noContext, 1)150 if err != nil {151 t.Error(err)152 return153 }154 if got, want := len(repos), 1; got != want {155 t.Errorf("Want Repo count %d, got %d", want, got)156 return157 }158 if err != nil {159 t.Error(err)160 return161 }162 got, want := repos[0], &core.Repository{}163 raw, err := ioutil.ReadFile("testdata/repo.json.golden")164 if err != nil {165 t.Error(err)166 return167 }168 err = json.Unmarshal(raw, want)169 if err != nil {170 t.Error(err)171 return172 }173 ignore := cmpopts.IgnoreFields(core.Repository{}, "ID")174 if diff := cmp.Diff(got, want, ignore); len(diff) != 0 {175 t.Errorf(diff)176 }177 }178}179func testRepoListLatest(repos *repoStore) func(t *testing.T) {180 return func(t *testing.T) {181 repos, err := repos.ListLatest(noContext, 1)182 if err != nil {183 t.Error(err)184 return185 }186 if got, want := len(repos), 1; got != want {187 t.Errorf("Want Repo count %d, got %d", want, got)188 } else if repos[0].Build != nil {189 t.Errorf("Expect nil build")190 } else {191 t.Run("Fields", testRepo(repos[0]))192 }193 }194}195func testRepoUpdate(repos *repoStore) func(t *testing.T) {196 return func(t *testing.T) {197 before, err := repos.FindName(noContext, "octocat", "hello-world")198 if err != nil {199 t.Error(err)200 return201 }202 version := before.Version203 before.Private = true204 err = repos.Update(noContext, before)205 if err != nil {206 t.Error(err)207 return208 }209 after, err := repos.Find(noContext, before.ID)210 if err != nil {211 t.Error(err)212 return213 }214 if got, want := after.Version, version+1; got != want {215 t.Errorf("Want version incremented on update")216 }217 if got, want := before.Private, after.Private; got != want {218 t.Errorf("Want updated Repo private %v, got %v", want, got)219 }220 }221}222func testRepoActivate(repos *repoStore) func(t *testing.T) {223 return func(t *testing.T) {224 before, err := repos.FindName(noContext, "octocat", "hello-world")225 if err != nil {226 t.Error(err)227 return228 }229 before.Active = true230 err = repos.Activate(noContext, before)231 if err != nil {232 t.Error(err)233 return234 }235 after, err := repos.Find(noContext, before.ID)236 if err != nil {237 t.Error(err)238 return239 }240 if got, want := before.Active, after.Active; got != want {241 t.Errorf("Want updated Repo Active %v, got %v", want, got)242 }243 }244}245func testRepoLocking(repos *repoStore) func(t *testing.T) {246 return func(t *testing.T) {247 repo, err := repos.FindName(noContext, "octocat", "hello-world")248 if err != nil {249 t.Error(err)250 return251 }252 repo.Version = 1253 err = repos.Update(noContext, repo)254 if err == nil {255 t.Errorf("Want Optimistic Lock Error, got nil")256 } else if err != db.ErrOptimisticLock {257 t.Errorf("Want Optimistic Lock Error")258 }259 }260}261func testRepoIncrement(repos *repoStore) func(t *testing.T) {262 return func(t *testing.T) {263 repo, err := repos.FindName(noContext, "octocat", "hello-world")264 if err != nil {265 t.Error(err)266 return267 }268 before := repo.Counter269 repo.Version--270 repo, err = repos.Increment(noContext, repo)271 if err != nil {272 t.Error(err)273 return274 }275 if got, want := repo.Counter, before+1; got != want {276 t.Errorf("Want count incremented to %d, got %d", want, got)277 }278 }279}280func testRepoDelete(repos *repoStore) func(t *testing.T) {281 return func(t *testing.T) {282 count, _ := repos.Count(noContext)283 if got, want := count, int64(1); got != want {284 t.Errorf("Want Repo table count %d, got %d", want, got)285 return286 }287 repo, err := repos.FindName(noContext, "octocat", "hello-world")288 if err != nil {289 return290 }291 err = repos.Delete(noContext, repo)292 if err != nil {293 t.Error(err)294 }295 count, _ = repos.Count(noContext)296 if got, want := count, int64(0); got != want {297 t.Errorf("Want Repo table count %d, got %d", want, got)298 return299 }300 }301}302func testRepo(repo *core.Repository) func(t *testing.T) {303 return func(t *testing.T) {304 if got, want := repo.UserID, int64(1); got != want {305 t.Errorf("Want UserID %d, got %d", want, got)306 }307 if got, want := repo.Namespace, "octocat"; got != want {...
err
Using AI Code Generation
1import "fmt"2func (e ErrNegativeSqrt) Error() string {3return fmt.Sprintf("cannot Sqrt negative number: %v", float64(e))4}5func Sqrt(x float64) (float64, error) {6if x < 0 {7return 0, ErrNegativeSqrt(x)8}9for i := 0; i < 10; i++ {10z -= (z*z - x) / (2 * z)11}12}13func main() {14fmt.Println(Sqrt(2))15fmt.Println(Sqrt(-2))16}17import (18func (e ErrNegativeSqrt) Error() string {19return fmt.Sprintf("cannot Sqrt negative number: %v", float64(e))20}21func Sqrt(x float64) (float64, error) {22if x < 0 {23return 0, ErrNegativeSqrt(x)24}25for i := 0; i < 10; i++ {26z -= (z*z - x) / (2 * z)27}28}29func main() {30fmt.Println(Sqrt(2))31fmt.Println(Sqrt(-2))32}33import (34func (e ErrNegativeSqrt) Error() string {35return fmt.Sprintf("cannot Sqrt negative number: %v", float64(e))36}37func Sqrt(x float64) (float64, error) {38if x < 0 {39return 0, ErrNegativeSqrt(x)40}41for i := 0; i < 10; i++ {42z -= (z*z - x) / (2 * z)43}44}45func main() {46fmt.Println(Sqrt(2))47fmt.Println(Sqrt(-2))48}
err
Using AI Code Generation
1import "fmt"2func main() {3 fmt.Println("Hello, World!")4}5import "fmt"6func main() {7 fmt.Println("Hello, World!")8}9import "fmt"10func main() {11 fmt.Println("Hello, World!")12}13import "fmt"14func main() {15 fmt.Println("Hello, World!")16}17import "fmt"18func main() {19 fmt.Println("Hello, World!")20}21import "fmt"22func main() {23 fmt.Println("Hello, World!")24}25import "fmt"26func main() {27 fmt.Println("Hello, World!")28}29import "fmt"30func main() {31 fmt.Println("Hello, World!")32}33import "fmt"34func main() {35 fmt.Println("Hello, World!")36}37import "fmt"38func main() {39 fmt.Println("Hello, World!")40}41import "fmt"42func main() {43 fmt.Println("Hello, World!")44}45import "fmt"46func main() {47 fmt.Println("Hello, World!")48}49import "fmt"50func main() {51 fmt.Println("Hello, World!")52}53import "fmt"54func main() {55 fmt.Println("Hello,
err
Using AI Code Generation
1import (2func main() {3 err := errors.New("error message")4 fmt.Println(err)5}6import (7func main() {8 err := errors.New("error message")9 fmt.Println(err.Error())10}11import (12func main() {13 err := errors.New("error message")14 fmt.Println(err.Error())15}16import (17func main() {18 err := errors.New("error message")19 fmt.Println(err.Error())20}21import (22func main() {23 err := errors.New("error message")24 fmt.Println(err.Error())25}26import (27func main() {28 err := errors.New("error message")29 fmt.Println(err.Error())30}31import (32func main() {33 err := errors.New("error message")34 fmt.Println(err.Error())35}36import (37func main() {38 err := errors.New("error message")39 fmt.Println(err.Error())40}41import (42func main() {43 err := errors.New("error message")44 fmt.Println(err.Error())45}46import (47func main() {48 err := errors.New("error message")49 fmt.Println(err.Error())50}
err
Using AI Code Generation
1import "fmt"2func main() {3 if b == 0 {4 fmt.Println("Cannot divide by 0")5 } else {6 fmt.Println(a / b)7 }8}9import "fmt"10func main() {11 if b == 0 {12 fmt.Println("Cannot divide by 0")13 } else {14 fmt.Println(a / b)15 }16}17import "fmt"18func main() {19 if b == 0 {20 fmt.Println("Cannot divide by 0")21 } else {22 fmt.Println(a / b)23 }24}25import "fmt"26func main() {27 if b == 0 {28 fmt.Println("Cannot divide by 0")29 } else {30 fmt.Println(a / b)31 }32}33import "fmt"34func main() {35 if b == 0 {36 fmt.Println("Cannot divide by 0")37 } else {38 fmt.Println(a / b)39 }40}41import "fmt"42func main() {43 if b == 0 {44 fmt.Println("Cannot divide by 0")45 } else {46 fmt.Println(a / b)47 }48}49import "fmt"50func main() {51 if b == 0 {
err
Using AI Code Generation
1import (2func main() {3 traceLog := tracelog.NewTraceLog()4 traceLog.Start("main")5 err := doSomething()6 if err != nil {7 traceLog.LogError(err)8 }9 traceLog.Stop("main")10 fmt.Println(traceLog.Output())11}12import (13func main() {14 traceLog := tracelog.NewTraceLog()15 traceLog.Start("main")16 err := doSomething()17 if err != nil {18 traceLog.LogError(err)19 }20 traceLog.Stop("main")21 fmt.Println(traceLog.Output())22}23import (24func main() {25 traceLog := tracelog.NewTraceLog()26 traceLog.Start("main")27 err := doSomething()28 if err != nil {29 traceLog.LogError(err)30 }31 traceLog.Stop("main")32 fmt.Println(traceLog.Output())33}34import (35func main() {36 traceLog := tracelog.NewTraceLog()37 traceLog.Start("main")38 err := doSomething()
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!