Best Rod code snippet using main.post
service_test.go
Source:service_test.go
...175 for i := 0; i < 2; i++ {176 thread, _ := pubThread(t, service, testUser{email: "thread@example.com"})177 threads = append(threads, thread)178 }179 tu := testUser{email: "post@example.com", name: " post"}180 var posts []*entity.Post181 for i := 0; i < 10; i++ {182 post, _ := pubPost(t, service, tu, threads[i%2].ID)183 posts = append(posts, post)184 }185 user, ctx := loginUser(t, service, tu)186 type args struct {187 ctx context.Context188 obj *entity.User189 query entity.SliceQuery190 }191 tests := []struct {192 name string193 args args194 want *entity.PostSlice195 wantErr bool196 }{197 {198 name: "first 5 posts",199 args: args{200 ctx: ctx,201 obj: user,202 query: entity.SliceQuery{203 After: algo.NullString(""),204 Limit: 5,205 },206 },207 want: &entity.PostSlice{208 Posts: []*entity.Post{209 posts[9], posts[8], posts[7], posts[6], posts[5],210 },211 SliceInfo: &entity.SliceInfo{212 FirstCursor: posts[9].ID.ToBase64String(),213 LastCursor: posts[5].ID.ToBase64String(),214 HasNext: true,215 },216 },217 },218 {219 name: "next 5 posts",220 args: args{221 ctx: ctx,222 obj: user,223 query: entity.SliceQuery{224 After: algo.NullString(posts[5].ID.ToBase64String()),225 Limit: 5,226 },227 },228 want: &entity.PostSlice{229 Posts: []*entity.Post{230 posts[4], posts[3], posts[2], posts[1], posts[0],231 },232 SliceInfo: &entity.SliceInfo{233 FirstCursor: posts[4].ID.ToBase64String(),234 LastCursor: posts[0].ID.ToBase64String(),235 HasNext: false,236 },237 },238 },239 {240 name: "last 5 posts",241 args: args{242 ctx: ctx,243 obj: user,244 query: entity.SliceQuery{245 Before: algo.NullString(""),246 Limit: 5,247 },248 },249 want: &entity.PostSlice{250 Posts: []*entity.Post{251 posts[4], posts[3], posts[2], posts[1], posts[0],252 },253 SliceInfo: &entity.SliceInfo{254 FirstCursor: posts[4].ID.ToBase64String(),255 LastCursor: posts[0].ID.ToBase64String(),256 HasNext: true,257 },258 },259 },260 }261 for _, tt := range tests {262 t.Run(tt.name, func(t *testing.T) {263 got, err := service.GetUserPosts(tt.args.ctx, tt.args.obj, tt.args.query)264 if (err != nil) != tt.wantErr {265 t.Errorf("Service.GetUserPosts() error = %v, wantErr %v", err, tt.wantErr)266 return267 }268 if diff := cmp.Diff(got.SliceInfo, tt.want.SliceInfo); diff != "" {269 t.Errorf("Service.GetUserPosts().SliceInfo diff: %s", diff)270 }271 if len(got.Posts) != len(tt.want.Posts) {272 t.Errorf("Service.GetUserPosts().len(Posts) = %v, want %v", len(got.Posts), len(tt.want.Posts))273 }274 for i, post := range got.Posts {275 post.CreatedAt = tt.want.Posts[i].CreatedAt276 if diff := cmp.Diff(post, tt.want.Posts[i]); diff != "" {277 t.Errorf("Service.GetUserPosts().Posts[%v] diff: %s", i, diff)278 }279 }280 })281 }282}283func TestService_SyncUserTags(t *testing.T) {284 mainTags := []string{"MainA", "MainB", "MainC"}285 service, _ := initEnv(t, mainTags...)286 _, ctx := loginUser(t, service, testUser{name: "a", email: "a@example.com"})287 type args struct {288 ctx context.Context289 tags []string290 }291 tests := []struct {292 name string293 args args294 wantTags []string295 wantErr bool296 }{297 {298 name: "sync 3 tags",299 args: args{300 ctx: ctx,301 tags: []string{"MainA", "SubA", "SubB"},302 },303 wantTags: []string{"MainA", "SubA", "SubB"},304 wantErr: false,305 },306 {307 name: "sync tags to add and del",308 args: args{309 ctx: ctx,310 tags: []string{"SubA", "SubB", "SubC"},311 },312 wantTags: []string{"SubA", "SubB", "SubC"},313 wantErr: false,314 },315 }316 for _, tt := range tests {317 t.Run(tt.name, func(t *testing.T) {318 got, err := service.SyncUserTags(tt.args.ctx, tt.args.tags)319 if (err != nil) != tt.wantErr {320 t.Errorf("Service.SyncUserTags() error = %v, wantErr %v", err, tt.wantErr)321 return322 }323 if diff := cmp.Diff(got.Tags, tt.wantTags); diff != "" {324 t.Errorf("Service.SyncUserTags() = %v, wantTags %v", got.Tags, tt.wantTags)325 }326 })327 }328}329func TestService_AddUserSubbedTag(t *testing.T) {330 mainTags := []string{"MainA", "MainB", "MainC"}331 service, _ := initEnv(t, mainTags...)332 _, ctx := loginUser(t, service, testUser{name: "a", email: "a@example.com"})333 type args struct {334 ctx context.Context335 tag string336 }337 tests := []struct {338 name string339 args args340 wantTags []string341 wantErr bool342 }{343 {344 name: "add 1 tag",345 args: args{ctx: ctx, tag: "subA"},346 wantTags: []string{"MainA", "MainB", "MainC", "subA"},347 wantErr: false,348 },349 {350 name: "add 1 duplicated tag",351 args: args{ctx: ctx, tag: "MainB"},352 wantTags: []string{"MainA", "MainB", "MainC", "subA"},353 wantErr: false,354 },355 }356 for _, tt := range tests {357 t.Run(tt.name, func(t *testing.T) {358 got, err := service.AddUserSubbedTag(tt.args.ctx, tt.args.tag)359 if (err != nil) != tt.wantErr {360 t.Errorf("Service.AddUserSubbedTag() error = %v, wantErr %v", err, tt.wantErr)361 return362 }363 if diff := cmp.Diff(got.Tags, tt.wantTags); diff != "" {364 t.Errorf("Service.AddUserSubbedTag() = %v, wantTags %v", got.Tags, tt.wantTags)365 }366 })367 }368}369func TestService_DelUserSubbedTag(t *testing.T) {370 mainTags := []string{"MainA", "MainB", "MainC"}371 service, _ := initEnv(t, mainTags...)372 _, ctx := loginUser(t, service, testUser{name: "a", email: "a@example.com"})373 type args struct {374 ctx context.Context375 tag string376 }377 tests := []struct {378 name string379 args args380 wantTags []string381 wantErr bool382 }{383 {384 name: "del 1 tag",385 args: args{386 ctx: ctx,387 tag: "MainA",388 },389 wantTags: []string{"MainB", "MainC"},390 wantErr: false,391 },392 {393 name: "del 1 unexists tag",394 args: args{395 ctx: ctx,396 tag: "subC",397 },398 wantTags: []string{"MainB", "MainC"},399 wantErr: false,400 },401 }402 for _, tt := range tests {403 t.Run(tt.name, func(t *testing.T) {404 got, err := service.DelUserSubbedTag(tt.args.ctx, tt.args.tag)405 if (err != nil) != tt.wantErr {406 t.Errorf("Service.DelUserSubbedTag() error = %v, wantErr %v", err, tt.wantErr)407 return408 }409 if diff := cmp.Diff(got.Tags, tt.wantTags); diff != "" {410 t.Errorf("Service.DelUserSubbedTag() diff = %v", diff)411 }412 })413 }414}415func TestService_BanUser(t *testing.T) {416 mainTags := []string{"MainA", "MainB", "MainC"}417 service, ctx := initEnv(t, mainTags...)418 thread, _ := pubThread(t, service, testUser{email: "t@example.com"})419 post, _ := pubPost(t, service, testUser{email: "p@example.com"}, thread.ID)420 mod, _ := loginUser(t, service, testUser{email: "mod@example.com"})421 mod.Role = entity.RoleMod422 _, err := service.Repo.User.Update(ctx, mod)423 if err != nil {424 t.Fatal(err)425 }426 _, modCtx := loginUser(t, service, testUser{email: "mod@example.com"})427 type args struct {428 ctx context.Context429 postID *uid.UID430 threadID *uid.UID431 }432 tests := []struct {433 name string434 args args435 checkEmail string436 wantBanned bool437 wantErr bool438 }{439 {440 name: "ban user by post id",441 args: args{442 ctx: modCtx,443 postID: &post.ID,444 },445 checkEmail: "p@example.com",446 wantBanned: true,447 },448 {449 name: "ban user by thread id",450 args: args{451 ctx: modCtx,452 threadID: &thread.ID,453 },454 checkEmail: "t@example.com",455 wantBanned: true,456 },457 }458 for _, tt := range tests {459 t.Run(tt.name, func(t *testing.T) {460 _, err := service.BanUser(tt.args.ctx, tt.args.postID, tt.args.threadID)461 if (err != nil) != tt.wantErr {462 t.Errorf("Service.BanUser() error = %v, wantErr %v", err, tt.wantErr)463 return464 }465 user, _ := loginUser(t, service, testUser{email: tt.checkEmail})466 if err != nil {467 t.Error(errors.Wrap(err, "get user profile"))468 }469 if (user.Role == entity.RoleBanned) != tt.wantBanned {470 t.Errorf("user role = %v, wantBanned %v", user.Role, tt.wantBanned)471 }472 })473 }474}475func TestService_PubThread(t *testing.T) {476 mainTags := []string{"MainA", "MainB", "MainC"}477 service, _ := initEnv(t, mainTags...)478 user, ctx := loginUser(t, service, testUser{email: "a@example.com", name: "a"})479 gUser, gCtx := loginUser(t, service, testUser{})480 type args struct {481 ctx context.Context482 thread entity.ThreadInput483 }484 tests := []struct {485 name string486 args args487 want *entity.Thread488 wantErrIs error489 }{490 {491 name: "anonymous signed in user",492 args: args{493 ctx,494 entity.ThreadInput{495 Anonymous: true,496 Content: "content",497 MainTag: "MainA",498 SubTags: []string{"SubA", "SubB"},499 Title: algo.NullString("title"),500 },501 },502 want: &entity.Thread{503 Author: &entity.Author{504 Anonymous: true,505 UserID: user.ID,506 Author: user.ID.ToBase64String(),507 },508 Title: algo.NullString("title"),509 Content: "content",510 MainTag: "MainA",511 SubTags: []string{"SubA", "SubB"},512 },513 },514 {515 name: "pub thread with user name",516 args: args{517 ctx,518 entity.ThreadInput{519 Anonymous: false,520 Content: "content1",521 MainTag: "MainA",522 SubTags: []string{"SubA", "SubB", "SubC"},523 },524 },525 want: &entity.Thread{526 Author: &entity.Author{527 UserID: user.ID,528 Anonymous: false,529 Author: *user.Name,530 },531 Title: nil,532 Content: "content1",533 MainTag: "MainA",534 SubTags: []string{"SubA", "SubB", "SubC"},535 },536 },537 {538 name: "pub duplicated thread",539 args: args{540 ctx,541 entity.ThreadInput{542 Anonymous: false,543 Content: "content1",544 MainTag: "MainA",545 SubTags: []string{"SubA", "SubB", "SubC"},546 },547 },548 wantErrIs: errors.Duplicated.New(),549 },550 {551 name: "guest user",552 args: args{553 gCtx,554 entity.ThreadInput{555 Anonymous: true,556 Content: "content",557 MainTag: "MainA",558 SubTags: []string{"SubA", "SubB", "SubC"},559 },560 },561 want: &entity.Thread{562 Author: &entity.Author{563 UserID: gUser.ID,564 Guest: true,565 Anonymous: true,566 Author: gUser.ID.ToBase64String(),567 },568 Title: nil,569 Content: "content",570 MainTag: "MainA",571 SubTags: []string{"SubA", "SubB", "SubC"},572 },573 },574 }575 for _, tt := range tests {576 t.Run(tt.name, func(t *testing.T) {577 got, err := service.PubThread(tt.args.ctx, tt.args.thread)578 if (tt.wantErrIs == nil && err != nil) || (tt.wantErrIs != nil && !errors.Is(err, tt.wantErrIs)) {579 t.Errorf("Service.PubThread() error = %v, wantErr %v", err, tt.wantErrIs)580 }581 if err != nil {582 return583 }584 tt.want.ID = got.ID585 tt.want.CreatedAt = got.CreatedAt586 tt.want.LastPostID = got.LastPostID587 if tt.want.Author.Anonymous {588 tt.want.Author.Author = got.Author.Author589 }590 if diff := cmp.Diff(got, tt.want); diff != "" {591 t.Errorf("Service.PubThread() missmatch: %s", diff)592 }593 if got.LastPostID != got.ID {594 t.Errorf("New thread's last_psot_id should equal to id")595 }596 })597 }598}599func TestService_LockThread(t *testing.T) {600 mainTags := []string{"MainA", "MainB", "MainC"}601 service, ctx := initEnv(t, mainTags...)602 oriThread, _ := pubThread(t, service, testUser{email: "t@example.com"})603 mod, _ := loginUser(t, service, testUser{email: "mod@example.com"})604 mod.Role = entity.RoleMod605 _, err := service.Repo.User.Update(ctx, mod)606 if err != nil {607 t.Fatal(err)608 }609 oriThread.Locked = true610 _, modCtx := loginUser(t, service, testUser{email: "mod@example.com"})611 t.Run("check thread in memory", func(t *testing.T) {612 thread, err := service.LockThread(modCtx, oriThread.ID)613 if err != nil {614 t.Fatal(errors.Wrap(err, "LockThread"))615 }616 oriThread.CreatedAt = thread.CreatedAt617 if diff := cmp.Diff(thread, oriThread); diff != "" {618 t.Errorf("LockThread() not matched: %s", diff)619 }620 })621 t.Run("check thread in database", func(t *testing.T) {622 thread, err := service.GetThreadByID(modCtx, oriThread.ID)623 if err != nil {624 t.Fatal(errors.Wrap(err, "GetThreadByID"))625 }626 oriThread.CreatedAt = thread.CreatedAt627 if diff := cmp.Diff(thread, oriThread); diff != "" {628 t.Errorf("LockThread() not matched: %s", diff)629 }630 })631 t.Run("thread locked", func(t *testing.T) {632 _, ctx := loginUser(t, service, testUser{email: "p@example.com"})633 input := entity.PostInput{634 ThreadID: oriThread.ID,635 Anonymous: true,636 Content: uid.RandomBase64Str(50),637 }638 _, err := service.PubPost(ctx, input)639 if err == nil {640 t.Errorf("locked thread still can send new post")641 }642 })643}644func TestService_BlockThread(t *testing.T) {645 mainTags := []string{"MainA", "MainB", "MainC"}646 service, ctx := initEnv(t, mainTags...)647 oriThread, _ := pubThread(t, service, testUser{email: "t@example.com"})648 mod, _ := loginUser(t, service, testUser{email: "mod@example.com"})649 mod.Role = entity.RoleMod650 _, err := service.Repo.User.Update(ctx, mod)651 if err != nil {652 t.Fatal(err)653 }654 oriThread.Blocked = true655 oriThread.Content = entity.BlockedContent656 _, modCtx := loginUser(t, service, testUser{email: "mod@example.com"})657 t.Run("check thread in memory", func(t *testing.T) {658 thread, err := service.BlockThread(modCtx, oriThread.ID)659 if err != nil {660 t.Fatal(errors.Wrap(err, "BlockThread"))661 }662 oriThread.CreatedAt = thread.CreatedAt663 if diff := cmp.Diff(thread, oriThread); diff != "" {664 t.Errorf("LockThread() not matched: %s", diff)665 }666 })667 t.Run("check thread in database", func(t *testing.T) {668 thread, err := service.GetThreadByID(modCtx, oriThread.ID)669 if err != nil {670 t.Fatal(errors.Wrap(err, "GetThreadByID"))671 }672 oriThread.CreatedAt = thread.CreatedAt673 if diff := cmp.Diff(thread, oriThread); diff != "" {674 t.Errorf("LockThread() not matched: %s", diff)675 }676 })677}678func TestService_EditTags(t *testing.T) {679 mainTags := []string{"MainA", "MainB", "MainC"}680 service, ctx := initEnv(t, mainTags...)681 oriThread, _ := pubThread(t, service, testUser{email: "t@example.com"})682 mod, _ := loginUser(t, service, testUser{email: "mod@example.com"})683 mod.Role = entity.RoleMod684 _, err := service.Repo.User.Update(ctx, mod)685 if err != nil {686 t.Fatal(err)687 }688 oriThread.MainTag = "MainC"689 oriThread.SubTags = []string{"SubC", "SubB", "SubA"}690 _, modCtx := loginUser(t, service, testUser{email: "mod@example.com"})691 t.Run("check thread in memory", func(t *testing.T) {692 thread, err := service.EditTags(modCtx, oriThread.ID, oriThread.MainTag, oriThread.SubTags)693 if err != nil {694 t.Fatal(errors.Wrap(err, "EditTags"))695 }696 oriThread.CreatedAt = thread.CreatedAt697 if diff := cmp.Diff(thread, oriThread); diff != "" {698 t.Errorf("EditTags() not matched: %s", diff)699 }700 })701 t.Run("check thread in database", func(t *testing.T) {702 thread, err := service.GetThreadByID(modCtx, oriThread.ID)703 if err != nil {704 t.Fatal(errors.Wrap(err, "GetThreadByID"))705 }706 oriThread.CreatedAt = thread.CreatedAt707 if diff := cmp.Diff(thread, oriThread); diff != "" {708 t.Errorf("EditTags() not matched: %s", diff)709 }710 })711}712func TestService_SearchThreads(t *testing.T) {713 mainTags := []string{"MainA", "MainB", "MainC"}714 service, _ := initEnv(t, mainTags...)715 var threads []*entity.Thread716 tu := testUser{email: "a@example.com", name: "a"}717 for i := 0; i < 10; i++ {718 var thread *entity.Thread719 switch {720 case i < 3:721 thread, _ = pubThreadWithTags(t, service, tu, "MainA", []string{"SubA"})722 case i < 6:723 thread, _ = pubThreadWithTags(t, service, tu, "MainA", []string{"SubA", "SubB"})724 default:725 thread, _ = pubThreadWithTags(t, service, tu, "MainC", []string{"SubB", "SubC"})726 }727 threads = append(threads, thread)728 }729 _, ctx := loginUser(t, service, testUser{email: "a@example.com"})730 type args struct {731 ctx context.Context732 tags []string733 query entity.SliceQuery734 }735 tests := []struct {736 name string737 args args738 want *entity.ThreadSlice739 wantErr bool740 }{741 {742 name: "first 5 threads with empty array as tag",743 args: args{744 ctx: ctx,745 tags: []string{""},746 query: entity.SliceQuery{747 After: algo.NullString(""),748 Limit: 5,749 },750 },751 want: &entity.ThreadSlice{752 Threads: []*entity.Thread{},753 SliceInfo: &entity.SliceInfo{754 FirstCursor: "",755 LastCursor: "",756 HasNext: false,757 },758 },759 },760 {761 name: "first 5 threads with a maintag",762 args: args{763 ctx: ctx,764 tags: []string{"MainA"},765 query: entity.SliceQuery{766 After: algo.NullString(""),767 Limit: 5,768 },769 },770 want: &entity.ThreadSlice{771 Threads: []*entity.Thread{772 threads[5], threads[4], threads[3], threads[2], threads[1],773 },774 SliceInfo: &entity.SliceInfo{775 FirstCursor: threads[5].ID.ToBase64String(),776 LastCursor: threads[1].ID.ToBase64String(),777 HasNext: true,778 },779 },780 },781 {782 name: "first 5 threads with two tags",783 args: args{784 ctx: ctx,785 tags: []string{"MainC", "SubB"},786 query: entity.SliceQuery{787 After: algo.NullString(""),788 Limit: 5,789 },790 },791 want: &entity.ThreadSlice{792 Threads: []*entity.Thread{793 threads[9], threads[8], threads[7], threads[6], threads[5],794 },795 SliceInfo: &entity.SliceInfo{796 FirstCursor: threads[9].ID.ToBase64String(),797 LastCursor: threads[5].ID.ToBase64String(),798 HasNext: true,799 },800 },801 },802 {803 name: "last 5 threads with only subtag",804 args: args{805 ctx: ctx,806 tags: []string{"SubC"},807 query: entity.SliceQuery{808 Before: algo.NullString(""),809 Limit: 5,810 },811 },812 want: &entity.ThreadSlice{813 Threads: []*entity.Thread{814 threads[9], threads[8], threads[7], threads[6],815 },816 SliceInfo: &entity.SliceInfo{817 FirstCursor: threads[9].ID.ToBase64String(),818 LastCursor: threads[6].ID.ToBase64String(),819 HasNext: false,820 },821 },822 },823 }824 for _, tt := range tests {825 t.Run(tt.name, func(t *testing.T) {826 got, err := service.SearchThreads(tt.args.ctx, tt.args.tags, tt.args.query)827 if (err != nil) != tt.wantErr {828 t.Errorf("Service.SearchThreads() error = %v, wantErr %v", err, tt.wantErr)829 return830 }831 if diff := cmp.Diff(got.SliceInfo, tt.want.SliceInfo); diff != "" {832 t.Errorf("Service.SearchThreads().SliceInfo diff: %s", diff)833 }834 if len(got.Threads) != len(tt.want.Threads) {835 t.Errorf("Service.SearchThreads().len(Threads) = %v, want %v", len(got.Threads), len(tt.want.Threads))836 }837 for i, thread := range got.Threads {838 thread.CreatedAt = tt.want.Threads[i].CreatedAt839 if diff := cmp.Diff(thread, tt.want.Threads[i]); diff != "" {840 t.Errorf("Service.SearchThreads().Threads[%v] diff: %s", i, diff)841 }842 }843 })844 }845}846func TestService_GetThreadReplies(t *testing.T) {847 mainTags := []string{"MainA", "MainB", "MainC"}848 service, _ := initEnv(t, mainTags...)849 thread, ctx := pubThread(t, service, testUser{email: "t@example", name: "a"})850 var posts []*entity.Post851 for i := 0; i < 10; i++ {852 post, _ := pubPost(t, service, testUser{email: "p@example"}, thread.ID)853 posts = append(posts, post)854 }855 type args struct {856 ctx context.Context857 thread *entity.Thread858 query entity.SliceQuery859 }860 tests := []struct {861 name string862 args args863 want *entity.PostSlice864 wantErr bool865 }{866 {867 name: "first 5",868 args: args{869 ctx: ctx,870 thread: thread,871 query: entity.SliceQuery{872 After: algo.NullString(""),873 Limit: 5,874 },875 },876 want: &entity.PostSlice{877 Posts: []*entity.Post{878 posts[0], posts[1], posts[2], posts[3], posts[4],879 },880 SliceInfo: &entity.SliceInfo{881 FirstCursor: posts[0].ID.ToBase64String(),882 LastCursor: posts[4].ID.ToBase64String(),883 HasNext: true,884 },885 },886 wantErr: false,887 },888 }889 for _, tt := range tests {890 t.Run(tt.name, func(t *testing.T) {891 got, err := service.GetThreadReplies(tt.args.ctx, tt.args.thread, tt.args.query)892 if (err != nil) != tt.wantErr {893 t.Errorf("Service.GetThreadReplies() error = %v, wantErr %v", err, tt.wantErr)894 return895 }896 if !reflect.DeepEqual(got, tt.want) {897 t.Errorf("Service.GetThreadReplies() = %v, want %v", got, tt.want)898 }899 })900 }901}902func TestService_GetThreadReplyCount(t *testing.T) {903 mainTags := []string{"MainA", "MainB", "MainC"}904 service, _ := initEnv(t, mainTags...)905 thread, ctx := pubThread(t, service, testUser{email: "t@example", name: "a"})906 for i := 0; i < 10; i++ {907 pubPost(t, service, testUser{email: "p@example"}, thread.ID)908 }909 type args struct {910 ctx context.Context911 thread *entity.Thread912 }913 tests := []struct {914 name string915 args args916 want int917 wantErr bool918 }{919 {920 name: "normal",921 args: args{922 ctx: ctx,923 thread: thread,924 },925 want: 10,926 wantErr: false,927 },928 }929 for _, tt := range tests {930 t.Run(tt.name, func(t *testing.T) {931 got, err := service.GetThreadReplyCount(tt.args.ctx, tt.args.thread)932 if (err != nil) != tt.wantErr {933 t.Errorf("Service.GetThreadReplyCount() error = %v, wantErr %v", err, tt.wantErr)934 return935 }936 if got != tt.want {937 t.Errorf("Service.GetThreadReplyCount() = %v, want %v", got, tt.want)938 }939 })940 }941}942func TestService_GetThreadCatalog(t *testing.T) {943 mainTags := []string{"MainA", "MainB", "MainC"}944 service, _ := initEnv(t, mainTags...)945 thread, ctx := pubThread(t, service, testUser{email: "t@example", name: "a"})946 var catalog []*entity.ThreadCatalogItem947 for i := 0; i < 10; i++ {948 post, _ := pubPost(t, service, testUser{email: "p@example"}, thread.ID)949 catalog = append(catalog, &entity.ThreadCatalogItem{950 PostID: post.ID,951 CreatedAt: post.CreatedAt,952 })953 }954 type args struct {955 ctx context.Context956 thread *entity.Thread957 }958 tests := []struct {959 name string960 args args961 want []*entity.ThreadCatalogItem962 wantErr bool963 }{964 {965 name: "normal",966 args: args{967 ctx: ctx,968 thread: thread,969 },970 want: catalog,971 wantErr: false,972 },973 }974 for _, tt := range tests {975 t.Run(tt.name, func(t *testing.T) {976 got, err := service.GetThreadCatalog(tt.args.ctx, tt.args.thread)977 if (err != nil) != tt.wantErr {978 t.Errorf("Service.GetThreadCatalog() error = %v, wantErr %v", err, tt.wantErr)979 return980 }981 if !reflect.DeepEqual(got, tt.want) {982 t.Errorf("Service.GetThreadCatalog() = %v, want %v", got, tt.want)983 }984 })985 }986}987func TestService_PubPost(t *testing.T) {988 mainTags := []string{"MainA", "MainB", "MainC"}989 service, _ := initEnv(t, mainTags...)990 thread, _ := pubThread(t, service, testUser{email: "a@example.com", name: "a"})991 post, _ := pubPost(t, service, testUser{email: "a@example.com", name: "a"}, thread.ID)992 user1, userCtx1 := loginUser(t, service, testUser{email: "p1@example.com"})993 user2, userCtx2 := loginUser(t, service, testUser{email: "p2@example.com", name: "p2"})994 userG, userCtxG := loginUser(t, service, testUser{})995 type args struct {996 ctx context.Context997 post entity.PostInput998 }999 type quotedChecker struct {1000 quotedCount int1001 }1002 tests := []struct {1003 name string1004 args args1005 want *entity.Post1006 wantErrIs error1007 checkQuoted *quotedChecker1008 }{1009 {1010 name: "anonymous signed in user",1011 args: args{1012 ctx: userCtx1,1013 post: entity.PostInput{1014 ThreadID: thread.ID,1015 Anonymous: true,1016 Content: "content1",1017 },1018 },1019 want: &entity.Post{1020 Author: &entity.Author{1021 UserID: user1.ID,1022 Anonymous: true,1023 Author: user1.ID.ToBase64String(),1024 },1025 Content: "content1",1026 ThreadID: thread.ID,1027 },1028 },1029 {1030 name: "pub post with user name",1031 args: args{1032 ctx: userCtx2,1033 post: entity.PostInput{1034 ThreadID: thread.ID,1035 Anonymous: false,1036 Content: "content2",1037 },1038 },1039 want: &entity.Post{1040 Author: &entity.Author{1041 UserID: user2.ID,1042 Anonymous: false,1043 Author: *user2.Name,1044 },1045 Content: "content2",1046 ThreadID: thread.ID,1047 },1048 },1049 {1050 name: "check duplicated",1051 args: args{1052 ctx: userCtx2,1053 post: entity.PostInput{1054 ThreadID: thread.ID,1055 Anonymous: false,1056 Content: "content2",1057 },1058 },1059 wantErrIs: errors.Duplicated.New(),1060 },1061 {1062 name: "pub post with quoted post",1063 args: args{1064 ctx: userCtx1,1065 post: entity.PostInput{1066 ThreadID: thread.ID,1067 Anonymous: true,1068 Content: "content3",1069 QuoteIds: []uid.UID{post.ID},1070 },1071 },1072 want: &entity.Post{1073 Author: &entity.Author{1074 UserID: user1.ID,1075 Anonymous: true,1076 Author: user1.ID.ToBase64String(),1077 },1078 Content: "content3",1079 ThreadID: thread.ID,1080 QuoteIDs: []uid.UID{post.ID},1081 },1082 checkQuoted: "edChecker{1083 quotedCount: 1,1084 },1085 },1086 {1087 name: "pub post with guest user",1088 args: args{1089 ctx: userCtxG,1090 post: entity.PostInput{1091 ThreadID: thread.ID,1092 Anonymous: true,1093 Content: "contentG",1094 },1095 },1096 want: &entity.Post{1097 Author: &entity.Author{1098 UserID: userG.ID,1099 Guest: true,1100 Anonymous: true,1101 Author: userG.ID.ToBase64String(),1102 },1103 Content: "contentG",1104 ThreadID: thread.ID,1105 },1106 },1107 }1108 for _, tt := range tests {1109 t.Run(tt.name, func(t *testing.T) {1110 got, err := service.PubPost(tt.args.ctx, tt.args.post)1111 if (tt.wantErrIs == nil && err != nil) || (tt.wantErrIs != nil && !errors.Is(err, tt.wantErrIs)) {1112 t.Errorf("Service.PubThread() error = %v, wantErr %v", err, tt.wantErrIs)1113 }1114 if err != nil {1115 return1116 }1117 tt.want.ID = got.ID1118 tt.want.CreatedAt = got.CreatedAt1119 if tt.args.post.Anonymous {1120 tt.want.Author.Author = got.Author.Author1121 }1122 if diff := cmp.Diff(got, tt.want); diff != "" {1123 t.Errorf("Service.PubPost() missmatch %s", diff)1124 }1125 if len(tt.want.QuoteIDs) != 0 {1126 quoted, err := service.Repo.Post.QuotedPosts(tt.args.ctx, got)1127 if err != nil {1128 t.Error(errors.Wrap(err, "Quotes()"))1129 }1130 if len(quoted) == 0 {1131 t.Error("should have a quoted post")1132 } else if diff := cmp.Diff(quoted[0], post); diff != "" {1133 t.Errorf("Service.PubPost().Quotes() missmatch: %s", diff)1134 }1135 }1136 if tt.checkQuoted != nil {1137 gotCount, err := service.Repo.Post.QuotedCount(tt.args.ctx, post)1138 if err != nil {1139 t.Errorf("quotedPost.QuotedCount error: %v", err)1140 }1141 if gotCount != tt.checkQuoted.quotedCount {1142 t.Errorf("Post(%v).QuotedCount()=%v, want=%v", post, gotCount, tt.checkQuoted.quotedCount)1143 }1144 }1145 })1146 }1147}1148func TestService_BlockPost(t *testing.T) {1149 mainTags := []string{"MainA", "MainB", "MainC"}1150 service, ctx := initEnv(t, mainTags...)1151 thread, _ := pubThread(t, service, testUser{email: "t@example.com"})1152 oriPost, _ := pubPost(t, service, testUser{email: "p@example.com"}, thread.ID)1153 mod, _ := loginUser(t, service, testUser{email: "mod@example.com"})1154 mod.Role = entity.RoleMod1155 _, err := service.Repo.User.Update(ctx, mod)1156 if err != nil {1157 t.Fatal(err)1158 }1159 oriPost.Blocked = true1160 oriPost.Content = entity.BlockedContent1161 _, modCtx := loginUser(t, service, testUser{email: "mod@example.com"})1162 t.Run("check post in memory", func(t *testing.T) {1163 post, err := service.BlockPost(modCtx, oriPost.ID)1164 if err != nil {1165 t.Fatal(errors.Wrap(err, "BlockPost"))1166 }1167 oriPost.CreatedAt = post.CreatedAt1168 if diff := cmp.Diff(post, oriPost); diff != "" {1169 t.Errorf("BlockPost() post matched: %s", diff)1170 }1171 })1172 t.Run("check post in database", func(t *testing.T) {1173 post, err := service.GetPostByID(modCtx, oriPost.ID)1174 if err != nil {1175 t.Fatal(errors.Wrap(err, "GetPostByID"))1176 }1177 oriPost.CreatedAt = post.CreatedAt1178 if diff := cmp.Diff(post, oriPost); diff != "" {1179 t.Errorf("BlockPost() post matched: %s", diff)1180 }1181 })1182}1183func TestService_GetPostQuotedPosts(t *testing.T) {1184 mainTags := []string{"MainA", "MainB", "MainC"}1185 service, _ := initEnv(t, mainTags...)1186 thread, _ := pubThread(t, service, testUser{email: "t@example", name: "a"})1187 post1, _ := pubPost(t, service, testUser{email: "1@example"}, thread.ID)1188 post2, _ := pubPost(t, service, testUser{email: "2@example"}, thread.ID)1189 post3, _ := pubPost(t, service, testUser{email: "3@example"}, thread.ID)1190 post4, ctx := pubPost(t, service, testUser{email: "4@example"}, thread.ID, post2.ID, post1.ID, post3.ID)1191 type args struct {1192 ctx context.Context1193 post *entity.Post1194 }1195 tests := []struct {1196 name string1197 args args1198 want []*entity.Post1199 wantErr bool1200 }{1201 {1202 name: "quote 3, test order",1203 args: args{1204 ctx: ctx,1205 post: post4,1206 },1207 want: []*entity.Post{post2, post1, post3},1208 wantErr: false,1209 },1210 }1211 for _, tt := range tests {1212 t.Run(tt.name, func(t *testing.T) {1213 got, err := service.GetPostQuotedPosts(tt.args.ctx, tt.args.post)1214 if (err != nil) != tt.wantErr {1215 t.Errorf("Service.GetPostQuotedPosts() error = %v, wantErr %v", err, tt.wantErr)1216 return1217 }1218 if !reflect.DeepEqual(got, tt.want) {1219 t.Errorf("Service.GetPostQuotedPosts() = %v, want %v", got, tt.want)1220 }1221 })1222 }1223}1224func TestService_GetPostQuotedCount(t *testing.T) {1225 mainTags := []string{"MainA", "MainB", "MainC"}1226 service, _ := initEnv(t, mainTags...)1227 thread, _ := pubThread(t, service, testUser{email: "t@example", name: "a"})1228 post1, ctx := pubPost(t, service, testUser{email: "1@example"}, thread.ID)1229 pubPost(t, service, testUser{email: "2@example"}, thread.ID, post1.ID)1230 pubPost(t, service, testUser{email: "3@example"}, thread.ID, post1.ID)1231 type args struct {1232 ctx context.Context1233 post *entity.Post1234 }1235 tests := []struct {1236 name string1237 args args1238 want int1239 wantErr bool1240 }{1241 {1242 name: "normal",1243 args: args{1244 ctx: ctx,1245 post: post1,1246 },1247 want: 2,1248 wantErr: false,1249 },1250 }1251 for _, tt := range tests {1252 t.Run(tt.name, func(t *testing.T) {1253 got, err := service.GetPostQuotedCount(tt.args.ctx, tt.args.post)1254 if (err != nil) != tt.wantErr {1255 t.Errorf("Service.GetPostQuotedCount() error = %v, wantErr %v", err, tt.wantErr)1256 return1257 }1258 if got != tt.want {1259 t.Errorf("Service.GetPostQuotedCount() = %v, want %v", got, tt.want)1260 }1261 })1262 }1263}1264func TestService_SearchTags(t *testing.T) {1265 mainTags := []string{"MainA", "MainB", "MainC"}1266 service, ctx := initEnv(t, mainTags...)1267 pubThreadWithTags(t, service, testUser{email: "a@example.com"}, "MainA", []string{"Sub11", "Sub21"})1268 pubThreadWithTags(t, service, testUser{email: "a@example.com"}, "MainB", []string{"Sub12", "Sub22"})1269 pubThreadWithTags(t, service, testUser{email: "a@example.com"}, "MainC", []string{"Sub13", "Sub23"})1270 pubThreadWithTags(t, service, testUser{email: "a@example.com"}, "MainA", []string{"Sub14", "Sub24"})1271 pubThreadWithTags(t, service, testUser{email: "a@example.com"}, "MainB", []string{"Sub15", "Sub25"})1272 pubThreadWithTags(t, service, testUser{email: "a@example.com"}, "MainC", []string{"Sub16", "Sub26"})1273 type args struct {1274 ctx context.Context1275 query *string1276 limit *int1277 }1278 tests := []struct {1279 name string1280 args args1281 ignoreOrder bool1282 want []*entity.Tag1283 wantErr bool1284 }{1285 {1286 name: "search all tags",1287 args: args{1288 ctx: ctx,1289 query: nil,1290 limit: algo.NullInt(9),1291 },1292 want: []*entity.Tag{1293 {Name: "MainA", IsMain: true},1294 {Name: "MainB", IsMain: true},1295 {Name: "MainC", IsMain: true},1296 {Name: "Sub14", IsMain: false},1297 {Name: "Sub15", IsMain: false},1298 {Name: "Sub16", IsMain: false},1299 {Name: "Sub24", IsMain: false},1300 {Name: "Sub25", IsMain: false},1301 {Name: "Sub26", IsMain: false},1302 },1303 ignoreOrder: true,1304 },1305 {1306 name: "search mainTags tags",1307 args: args{1308 ctx: ctx,1309 query: algo.NullString("Main"),1310 limit: algo.NullInt(10),1311 },1312 want: []*entity.Tag{1313 {Name: "MainC", IsMain: true},1314 {Name: "MainB", IsMain: true},1315 {Name: "MainA", IsMain: true},1316 },1317 },1318 {1319 name: "search sub tags",1320 args: args{1321 ctx: ctx,1322 query: algo.NullString("ub1"),1323 limit: algo.NullInt(10),1324 },1325 want: []*entity.Tag{1326 {Name: "Sub16", IsMain: false},1327 {Name: "Sub15", IsMain: false},1328 {Name: "Sub14", IsMain: false},1329 {Name: "Sub13", IsMain: false},1330 {Name: "Sub12", IsMain: false},1331 {Name: "Sub11", IsMain: false},1332 },1333 },1334 }1335 for _, tt := range tests {1336 t.Run(tt.name, func(t *testing.T) {1337 got, err := service.SearchTags(tt.args.ctx, tt.args.query, tt.args.limit)1338 if (err != nil) != tt.wantErr {1339 t.Errorf("Service.SearchTags() error = %v, wantErr %v", err, tt.wantErr)1340 return1341 }1342 if !tt.ignoreOrder {1343 if diff := cmp.Diff(got, tt.want); diff != "" {1344 t.Errorf("Service.SearchTags() missmatch: %s", diff)1345 }1346 } else {1347 if diff := cmp.Diff(got, tt.want, tagSetCmp); diff != "" {1348 t.Errorf("Service.SearchTags() missmatch: %s", diff)1349 }1350 }1351 })1352 }1353}1354func TestService_GetUnreadNotiCount(t *testing.T) {1355 mainTags := []string{"MainA", "MainB", "MainC"}1356 service, ctx := initEnv(t, mainTags...)1357 user, userCtx := loginUser(t, service, testUser{email: "a@example.com"})1358 type args struct {1359 ctx context.Context1360 }1361 tests := []struct {1362 name string1363 args args1364 beforeTest func(t *testing.T)1365 want int1366 wantErr bool1367 }{1368 {1369 name: "1 system noti(welcome)",1370 args: args{1371 ctx: userCtx,1372 },1373 want: 1,1374 },1375 {1376 name: "1 global system noti",1377 args: args{1378 ctx: userCtx,1379 },1380 beforeTest: func(t *testing.T) {1381 noti, err := entity.NewSystemNoti("welcome!", "welcome to abyss", entity.SendToGroup(entity.AllUser))1382 if err != nil {1383 t.Fatal(err)1384 }1385 if err := service.Repo.Noti.Insert(ctx, noti); err != nil {1386 t.Fatal(err)1387 }1388 },1389 want: 2,1390 },1391 {1392 name: "count after read",1393 args: args{1394 ctx: userCtx,1395 },1396 beforeTest: func(t *testing.T) {1397 if _, err := service.GetNotifications(userCtx, entity.SliceQuery{1398 After: algo.NullString(""),1399 Limit: 5,1400 }); err != nil {1401 t.Fatal(err)1402 }1403 },1404 want: 0,1405 },1406 {1407 name: "new reply noti",1408 args: args{1409 ctx: userCtx,1410 },1411 beforeTest: func(t *testing.T) {1412 thread, _ := pubThread(t, service, testUser{email: *user.Email})1413 pubPost(t, service, testUser{email: "p@example.com"}, thread.ID)1414 time.Sleep(100 * time.Millisecond)1415 },1416 want: 1,1417 },1418 }1419 for _, tt := range tests {1420 t.Run(tt.name, func(t *testing.T) {1421 if tt.beforeTest != nil {1422 tt.beforeTest(t)1423 }1424 got, err := service.GetUnreadNotiCount(tt.args.ctx)1425 if (err != nil) != tt.wantErr {1426 t.Errorf("Service.GetUnreadNotiCount() error = %v, wantErr %v", err, tt.wantErr)1427 return1428 }1429 if !reflect.DeepEqual(got, tt.want) {1430 t.Errorf("Service.GetUnreadNotiCount() = %v, want %v", got, tt.want)1431 }1432 })1433 }1434}1435func TestService_GetNotification(t *testing.T) {1436 mainTags := []string{"MainA", "MainB", "MainC"}1437 service, ctx := initEnv(t, mainTags...)1438 user, _ := loginUser(t, service, testUser{email: "t@example.com"}) // One Welcome Noti1439 thread, _ := pubThread(t, service, testUser{email: *user.Email})1440 type args struct {1441 email string1442 query entity.SliceQuery1443 }1444 tests := []struct {1445 name string1446 args args1447 beforeTest func(t *testing.T, want *entity.NotiSlice)1448 want *entity.NotiSlice1449 wantErr bool1450 }{1451 {1452 name: "2 system noti 1 replied noti",1453 args: args{1454 email: *user.Email,1455 query: entity.SliceQuery{After: algo.NullString(""), Limit: 5},1456 },1457 beforeTest: func(t *testing.T, want *entity.NotiSlice) {1458 noti, err := entity.NewSystemNoti("Hi everyone!", "Let's Party!", entity.SendToGroup(entity.AllUser))1459 if err != nil {1460 t.Fatal(err)1461 }1462 if err := service.Repo.Noti.Insert(ctx, noti); err != nil {1463 t.Fatal(err)1464 }1465 post, _ := pubPost(t, service, testUser{email: "p1@example.com"}, thread.ID)1466 content := want.Notifications[0].Content.(entity.RepliedNoti)1467 content.FirstReplyID = post.ID1468 want.Notifications[0].Content = content1469 time.Sleep(100 * time.Millisecond)1470 },1471 want: &entity.NotiSlice{1472 SliceInfo: &entity.SliceInfo{1473 HasNext: false,1474 },1475 Notifications: []*entity.Notification{1476 {1477 Type: entity.NotiTypeReplied,1478 Content: entity.RepliedNoti{1479 Thread: &entity.ThreadOutline{1480 ID: thread.ID,1481 Title: thread.Title,...
plugin_hooks_test.go
Source:plugin_hooks_test.go
...62 )63 type MyPlugin struct {64 plugin.MattermostPlugin65 }66 func (p *MyPlugin) MessageWillBePosted(c *plugin.Context, post *model.Post) (*model.Post, string) {67 return nil, "rejected"68 }69 func main() {70 plugin.ClientMain(&MyPlugin{})71 }72 `,73 }, th.App, th.App.NewPluginAPI)74 defer tearDown()75 post := &model.Post{76 UserId: th.BasicUser.Id,77 ChannelId: th.BasicChannel.Id,78 Message: "message_",79 CreateAt: model.GetMillis() - 10000,80 }81 _, err := th.App.CreatePost(post, th.BasicChannel, false)82 if assert.NotNil(t, err) {83 assert.Equal(t, "Post rejected by plugin. rejected", err.Message)84 }85 })86 t.Run("rejected, returned post ignored", func(t *testing.T) {87 th := Setup(t).InitBasic()88 defer th.TearDown()89 tearDown, _, _ := SetAppEnvironmentWithPlugins(t, []string{90 `91 package main92 import (93 "github.com/mattermost/mattermost-server/plugin"94 "github.com/mattermost/mattermost-server/model"95 )96 type MyPlugin struct {97 plugin.MattermostPlugin98 }99 func (p *MyPlugin) MessageWillBePosted(c *plugin.Context, post *model.Post) (*model.Post, string) {100 post.Message = "ignored"101 return post, "rejected"102 }103 func main() {104 plugin.ClientMain(&MyPlugin{})105 }106 `,107 }, th.App, th.App.NewPluginAPI)108 defer tearDown()109 post := &model.Post{110 UserId: th.BasicUser.Id,111 ChannelId: th.BasicChannel.Id,112 Message: "message_",113 CreateAt: model.GetMillis() - 10000,114 }115 _, err := th.App.CreatePost(post, th.BasicChannel, false)116 if assert.NotNil(t, err) {117 assert.Equal(t, "Post rejected by plugin. rejected", err.Message)118 }119 })120 t.Run("allowed", func(t *testing.T) {121 th := Setup(t).InitBasic()122 defer th.TearDown()123 tearDown, _, _ := SetAppEnvironmentWithPlugins(t, []string{124 `125 package main126 import (127 "github.com/mattermost/mattermost-server/plugin"128 "github.com/mattermost/mattermost-server/model"129 )130 type MyPlugin struct {131 plugin.MattermostPlugin132 }133 func (p *MyPlugin) MessageWillBePosted(c *plugin.Context, post *model.Post) (*model.Post, string) {134 return nil, ""135 }136 func main() {137 plugin.ClientMain(&MyPlugin{})138 }139 `,140 }, th.App, th.App.NewPluginAPI)141 defer tearDown()142 post := &model.Post{143 UserId: th.BasicUser.Id,144 ChannelId: th.BasicChannel.Id,145 Message: "message",146 CreateAt: model.GetMillis() - 10000,147 }148 post, err := th.App.CreatePost(post, th.BasicChannel, false)149 require.Nil(t, err)150 assert.Equal(t, "message", post.Message)151 retrievedPost, errSingle := th.App.Srv.Store.Post().GetSingle(post.Id)152 require.Nil(t, errSingle)153 assert.Equal(t, "message", retrievedPost.Message)154 })155 t.Run("updated", func(t *testing.T) {156 th := Setup(t).InitBasic()157 defer th.TearDown()158 tearDown, _, _ := SetAppEnvironmentWithPlugins(t, []string{159 `160 package main161 import (162 "github.com/mattermost/mattermost-server/plugin"163 "github.com/mattermost/mattermost-server/model"164 )165 type MyPlugin struct {166 plugin.MattermostPlugin167 }168 func (p *MyPlugin) MessageWillBePosted(c *plugin.Context, post *model.Post) (*model.Post, string) {169 post.Message = post.Message + "_fromplugin"170 return post, ""171 }172 func main() {173 plugin.ClientMain(&MyPlugin{})174 }175 `,176 }, th.App, th.App.NewPluginAPI)177 defer tearDown()178 post := &model.Post{179 UserId: th.BasicUser.Id,180 ChannelId: th.BasicChannel.Id,181 Message: "message",182 CreateAt: model.GetMillis() - 10000,183 }184 post, err := th.App.CreatePost(post, th.BasicChannel, false)185 require.Nil(t, err)186 assert.Equal(t, "message_fromplugin", post.Message)187 retrievedPost, errSingle := th.App.Srv.Store.Post().GetSingle(post.Id)188 require.Nil(t, errSingle)189 assert.Equal(t, "message_fromplugin", retrievedPost.Message)190 })191 t.Run("multiple updated", func(t *testing.T) {192 th := Setup(t).InitBasic()193 defer th.TearDown()194 tearDown, _, _ := SetAppEnvironmentWithPlugins(t, []string{195 `196 package main197 import (198 "github.com/mattermost/mattermost-server/plugin"199 "github.com/mattermost/mattermost-server/model"200 )201 type MyPlugin struct {202 plugin.MattermostPlugin203 }204 func (p *MyPlugin) MessageWillBePosted(c *plugin.Context, post *model.Post) (*model.Post, string) {205 post.Message = "prefix_" + post.Message206 return post, ""207 }208 func main() {209 plugin.ClientMain(&MyPlugin{})210 }211 `,212 `213 package main214 import (215 "github.com/mattermost/mattermost-server/plugin"216 "github.com/mattermost/mattermost-server/model"217 )218 type MyPlugin struct {219 plugin.MattermostPlugin220 }221 func (p *MyPlugin) MessageWillBePosted(c *plugin.Context, post *model.Post) (*model.Post, string) {222 post.Message = post.Message + "_suffix"223 return post, ""224 }225 func main() {226 plugin.ClientMain(&MyPlugin{})227 }228 `,229 }, th.App, th.App.NewPluginAPI)230 defer tearDown()231 post := &model.Post{232 UserId: th.BasicUser.Id,233 ChannelId: th.BasicChannel.Id,234 Message: "message",235 CreateAt: model.GetMillis() - 10000,236 }237 post, err := th.App.CreatePost(post, th.BasicChannel, false)238 require.Nil(t, err)239 assert.Equal(t, "prefix_message_suffix", post.Message)240 })241}242func TestHookMessageHasBeenPosted(t *testing.T) {243 th := Setup(t).InitBasic()244 defer th.TearDown()245 var mockAPI plugintest.API246 mockAPI.On("LoadPluginConfiguration", mock.Anything).Return(nil)247 mockAPI.On("LogDebug", "message").Return(nil)248 tearDown, _, _ := SetAppEnvironmentWithPlugins(t,249 []string{250 `251 package main252 import (253 "github.com/mattermost/mattermost-server/plugin"254 "github.com/mattermost/mattermost-server/model"255 )256 type MyPlugin struct {257 plugin.MattermostPlugin258 }259 func (p *MyPlugin) MessageHasBeenPosted(c *plugin.Context, post *model.Post) {260 p.API.LogDebug(post.Message)261 }262 func main() {263 plugin.ClientMain(&MyPlugin{})264 }265 `}, th.App, func(*model.Manifest) plugin.API { return &mockAPI })266 defer tearDown()267 post := &model.Post{268 UserId: th.BasicUser.Id,269 ChannelId: th.BasicChannel.Id,270 Message: "message",271 CreateAt: model.GetMillis() - 10000,272 }273 _, err := th.App.CreatePost(post, th.BasicChannel, false)274 require.Nil(t, err)275}276func TestHookMessageWillBeUpdated(t *testing.T) {277 th := Setup(t).InitBasic()278 defer th.TearDown()279 tearDown, _, _ := SetAppEnvironmentWithPlugins(t,280 []string{281 `282 package main283 import (284 "github.com/mattermost/mattermost-server/plugin"285 "github.com/mattermost/mattermost-server/model"286 )287 type MyPlugin struct {288 plugin.MattermostPlugin289 }290 func (p *MyPlugin) MessageWillBeUpdated(c *plugin.Context, newPost, oldPost *model.Post) (*model.Post, string) {291 newPost.Message = newPost.Message + "fromplugin"292 return newPost, ""293 }294 func main() {295 plugin.ClientMain(&MyPlugin{})296 }297 `}, th.App, th.App.NewPluginAPI)298 defer tearDown()299 post := &model.Post{300 UserId: th.BasicUser.Id,301 ChannelId: th.BasicChannel.Id,302 Message: "message_",303 CreateAt: model.GetMillis() - 10000,304 }305 post, err := th.App.CreatePost(post, th.BasicChannel, false)306 require.Nil(t, err)307 assert.Equal(t, "message_", post.Message)308 post.Message = post.Message + "edited_"309 post, err = th.App.UpdatePost(post, true)310 require.Nil(t, err)311 assert.Equal(t, "message_edited_fromplugin", post.Message)312}313func TestHookMessageHasBeenUpdated(t *testing.T) {314 th := Setup(t).InitBasic()315 defer th.TearDown()316 var mockAPI plugintest.API317 mockAPI.On("LoadPluginConfiguration", mock.Anything).Return(nil)318 mockAPI.On("LogDebug", "message_edited").Return(nil)319 mockAPI.On("LogDebug", "message_").Return(nil)320 tearDown, _, _ := SetAppEnvironmentWithPlugins(t,321 []string{322 `323 package main324 import (325 "github.com/mattermost/mattermost-server/plugin"326 "github.com/mattermost/mattermost-server/model"327 )328 type MyPlugin struct {329 plugin.MattermostPlugin330 }331 func (p *MyPlugin) MessageHasBeenUpdated(c *plugin.Context, newPost, oldPost *model.Post) {332 p.API.LogDebug(newPost.Message)333 p.API.LogDebug(oldPost.Message)334 }335 func main() {336 plugin.ClientMain(&MyPlugin{})337 }338 `}, th.App, func(*model.Manifest) plugin.API { return &mockAPI })339 defer tearDown()340 post := &model.Post{341 UserId: th.BasicUser.Id,342 ChannelId: th.BasicChannel.Id,343 Message: "message_",344 CreateAt: model.GetMillis() - 10000,345 }346 post, err := th.App.CreatePost(post, th.BasicChannel, false)347 require.Nil(t, err)348 assert.Equal(t, "message_", post.Message)349 post.Message = post.Message + "edited"350 _, err = th.App.UpdatePost(post, true)351 require.Nil(t, err)352}353func TestHookFileWillBeUploaded(t *testing.T) {354 t.Run("rejected", func(t *testing.T) {355 th := Setup(t).InitBasic()356 defer th.TearDown()357 var mockAPI plugintest.API358 mockAPI.On("LoadPluginConfiguration", mock.Anything).Return(nil)359 mockAPI.On("LogDebug", "testhook.txt").Return(nil)360 mockAPI.On("LogDebug", "inputfile").Return(nil)361 tearDown, _, _ := SetAppEnvironmentWithPlugins(t, []string{362 `363 package main364 import (365 "io"366 "github.com/mattermost/mattermost-server/plugin"367 "github.com/mattermost/mattermost-server/model"368 )369 type MyPlugin struct {370 plugin.MattermostPlugin371 }372 func (p *MyPlugin) FileWillBeUploaded(c *plugin.Context, info *model.FileInfo, file io.Reader, output io.Writer) (*model.FileInfo, string) {373 return nil, "rejected"374 }375 func main() {376 plugin.ClientMain(&MyPlugin{})377 }378 `,379 }, th.App, func(*model.Manifest) plugin.API { return &mockAPI })380 defer tearDown()381 _, err := th.App.UploadFiles(382 "noteam",383 th.BasicChannel.Id,384 th.BasicUser.Id,385 []io.ReadCloser{ioutil.NopCloser(bytes.NewBufferString("inputfile"))},386 []string{"testhook.txt"},387 []string{},388 time.Now(),389 )390 if assert.NotNil(t, err) {391 assert.Equal(t, "File rejected by plugin. rejected", err.Message)392 }393 })394 t.Run("rejected, returned file ignored", func(t *testing.T) {395 th := Setup(t).InitBasic()396 defer th.TearDown()397 var mockAPI plugintest.API398 mockAPI.On("LoadPluginConfiguration", mock.Anything).Return(nil)399 mockAPI.On("LogDebug", "testhook.txt").Return(nil)400 mockAPI.On("LogDebug", "inputfile").Return(nil)401 tearDown, _, _ := SetAppEnvironmentWithPlugins(t, []string{402 `403 package main404 import (405 "fmt"406 "io"407 "github.com/mattermost/mattermost-server/plugin"408 "github.com/mattermost/mattermost-server/model"409 )410 type MyPlugin struct {411 plugin.MattermostPlugin412 }413 func (p *MyPlugin) FileWillBeUploaded(c *plugin.Context, info *model.FileInfo, file io.Reader, output io.Writer) (*model.FileInfo, string) {414 n, err := output.Write([]byte("ignored"))415 if err != nil {416 return info, fmt.Sprintf("FAILED to write output file n: %v, err: %v", n, err)417 }418 info.Name = "ignored"419 return info, "rejected"420 }421 func main() {422 plugin.ClientMain(&MyPlugin{})423 }424 `,425 }, th.App, func(*model.Manifest) plugin.API { return &mockAPI })426 defer tearDown()427 _, err := th.App.UploadFiles(428 "noteam",429 th.BasicChannel.Id,430 th.BasicUser.Id,431 []io.ReadCloser{ioutil.NopCloser(bytes.NewBufferString("inputfile"))},432 []string{"testhook.txt"},433 []string{},434 time.Now(),435 )436 if assert.NotNil(t, err) {437 assert.Equal(t, "File rejected by plugin. rejected", err.Message)438 }439 })440 t.Run("allowed", func(t *testing.T) {441 th := Setup(t).InitBasic()442 defer th.TearDown()443 var mockAPI plugintest.API444 mockAPI.On("LoadPluginConfiguration", mock.Anything).Return(nil)445 mockAPI.On("LogDebug", "testhook.txt").Return(nil)446 mockAPI.On("LogDebug", "inputfile").Return(nil)447 tearDown, _, _ := SetAppEnvironmentWithPlugins(t, []string{448 `449 package main450 import (451 "io"452 "github.com/mattermost/mattermost-server/plugin"453 "github.com/mattermost/mattermost-server/model"454 )455 type MyPlugin struct {456 plugin.MattermostPlugin457 }458 func (p *MyPlugin) FileWillBeUploaded(c *plugin.Context, info *model.FileInfo, file io.Reader, output io.Writer) (*model.FileInfo, string) {459 return nil, ""460 }461 func main() {462 plugin.ClientMain(&MyPlugin{})463 }464 `,465 }, th.App, func(*model.Manifest) plugin.API { return &mockAPI })466 defer tearDown()467 response, err := th.App.UploadFiles(468 "noteam",469 th.BasicChannel.Id,470 th.BasicUser.Id,471 []io.ReadCloser{ioutil.NopCloser(bytes.NewBufferString("inputfile"))},472 []string{"testhook.txt"},473 []string{},474 time.Now(),475 )476 assert.Nil(t, err)477 assert.NotNil(t, response)478 assert.Equal(t, 1, len(response.FileInfos))479 480 fileId := response.FileInfos[0].Id481 fileInfo, err := th.App.GetFileInfo(fileId)482 assert.Nil(t, err)483 assert.NotNil(t, fileInfo)484 assert.Equal(t, "testhook.txt", fileInfo.Name)485 fileReader, err := th.App.FileReader(fileInfo.Path)486 assert.Nil(t, err)487 var resultBuf bytes.Buffer488 io.Copy(&resultBuf, fileReader)489 assert.Equal(t, "inputfile", resultBuf.String())490 })491 t.Run("updated", func(t *testing.T) {492 th := Setup(t).InitBasic()493 defer th.TearDown()494 var mockAPI plugintest.API495 mockAPI.On("LoadPluginConfiguration", mock.Anything).Return(nil)496 mockAPI.On("LogDebug", "testhook.txt").Return(nil)497 mockAPI.On("LogDebug", "inputfile").Return(nil)498 tearDown, _, _ := SetAppEnvironmentWithPlugins(t, []string{499 `500 package main501 import (502 "io"503 "fmt"504 "bytes"505 "github.com/mattermost/mattermost-server/plugin"506 "github.com/mattermost/mattermost-server/model"507 )508 type MyPlugin struct {509 plugin.MattermostPlugin510 }511 func (p *MyPlugin) FileWillBeUploaded(c *plugin.Context, info *model.FileInfo, file io.Reader, output io.Writer) (*model.FileInfo, string) {512 var buf bytes.Buffer513 n, err := buf.ReadFrom(file)514 if err != nil {515 panic(fmt.Sprintf("buf.ReadFrom failed, reading %d bytes: %s", err.Error()))516 }517 outbuf := bytes.NewBufferString("changedtext")518 n, err = io.Copy(output, outbuf)519 if err != nil {520 panic(fmt.Sprintf("io.Copy failed after %d bytes: %s", n, err.Error()))521 }522 if n != 11 {523 panic(fmt.Sprintf("io.Copy only copied %d bytes", n))524 }525 info.Name = "modifiedinfo"526 return info, ""527 }528 func main() {529 plugin.ClientMain(&MyPlugin{})530 }531 `,532 }, th.App, func(*model.Manifest) plugin.API { return &mockAPI })533 defer tearDown()534 response, err := th.App.UploadFiles(535 "noteam",536 th.BasicChannel.Id,537 th.BasicUser.Id,538 []io.ReadCloser{ioutil.NopCloser(bytes.NewBufferString("inputfile"))},539 []string{"testhook.txt"},540 []string{},541 time.Now(),542 )543 assert.Nil(t, err)544 assert.NotNil(t, response)545 assert.Equal(t, 1, len(response.FileInfos))546 fileId := response.FileInfos[0].Id547 fileInfo, err := th.App.GetFileInfo(fileId)548 assert.Nil(t, err)549 assert.NotNil(t, fileInfo)550 assert.Equal(t, "modifiedinfo", fileInfo.Name)551 fileReader, err := th.App.FileReader(fileInfo.Path)552 assert.Nil(t, err)553 var resultBuf bytes.Buffer554 io.Copy(&resultBuf, fileReader)555 assert.Equal(t, "changedtext", resultBuf.String())556 })557}558func TestUserWillLogIn_Blocked(t *testing.T) {559 th := Setup(t).InitBasic()560 defer th.TearDown()561 err := th.App.UpdatePassword(th.BasicUser, "hunter2")562 assert.Nil(t, err, "Error updating user password: %s", err)563 tearDown, _, _ := SetAppEnvironmentWithPlugins(t,564 []string{565 `566 package main567 import (568 "github.com/mattermost/mattermost-server/plugin"569 "github.com/mattermost/mattermost-server/model"570 )571 type MyPlugin struct {572 plugin.MattermostPlugin573 }574 func (p *MyPlugin) UserWillLogIn(c *plugin.Context, user *model.User) string {575 return "Blocked By Plugin"576 }577 func main() {578 plugin.ClientMain(&MyPlugin{})579 }580 `}, th.App, th.App.NewPluginAPI)581 defer tearDown()582 r := &http.Request{}583 w := httptest.NewRecorder()584 _, err = th.App.DoLogin(w, r, th.BasicUser, "")585 assert.Contains(t, err.Id, "Login rejected by plugin", "Expected Login rejected by plugin, got %s", err.Id)586}587func TestUserWillLogInIn_Passed(t *testing.T) {588 th := Setup(t).InitBasic()589 defer th.TearDown()590 err := th.App.UpdatePassword(th.BasicUser, "hunter2")591 assert.Nil(t, err, "Error updating user password: %s", err)592 tearDown, _, _ := SetAppEnvironmentWithPlugins(t,593 []string{594 `595 package main596 import (597 "github.com/mattermost/mattermost-server/plugin"598 "github.com/mattermost/mattermost-server/model"599 )600 type MyPlugin struct {601 plugin.MattermostPlugin602 }603 func (p *MyPlugin) UserWillLogIn(c *plugin.Context, user *model.User) string {604 return ""605 }606 func main() {607 plugin.ClientMain(&MyPlugin{})608 }609 `}, th.App, th.App.NewPluginAPI)610 defer tearDown()611 r := &http.Request{}612 w := httptest.NewRecorder()613 session, err := th.App.DoLogin(w, r, th.BasicUser, "")614 assert.Nil(t, err, "Expected nil, got %s", err)615 assert.Equal(t, session.UserId, th.BasicUser.Id)616}617func TestUserHasLoggedIn(t *testing.T) {618 th := Setup(t).InitBasic()619 defer th.TearDown()620 err := th.App.UpdatePassword(th.BasicUser, "hunter2")621 assert.Nil(t, err, "Error updating user password: %s", err)622 tearDown, _, _ := SetAppEnvironmentWithPlugins(t,623 []string{624 `625 package main626 import (627 "github.com/mattermost/mattermost-server/plugin"628 "github.com/mattermost/mattermost-server/model"629 )630 type MyPlugin struct {631 plugin.MattermostPlugin632 }633 func (p *MyPlugin) UserHasLoggedIn(c *plugin.Context, user *model.User) {634 user.FirstName = "plugin-callback-success"635 p.API.UpdateUser(user)636 }637 func main() {638 plugin.ClientMain(&MyPlugin{})639 }640 `}, th.App, th.App.NewPluginAPI)641 defer tearDown()642 r := &http.Request{}643 w := httptest.NewRecorder()644 _, err = th.App.DoLogin(w, r, th.BasicUser, "")645 assert.Nil(t, err, "Expected nil, got %s", err)646 time.Sleep(2 * time.Second)647 user, _ := th.App.GetUser(th.BasicUser.Id)648 assert.Equal(t, user.FirstName, "plugin-callback-success", "Expected firstname overwrite, got default")649}650func TestUserHasBeenCreated(t *testing.T) {651 th := Setup(t).InitBasic()652 defer th.TearDown()653 tearDown, _, _ := SetAppEnvironmentWithPlugins(t,654 []string{655 `656 package main657 import (658 "github.com/mattermost/mattermost-server/plugin"659 "github.com/mattermost/mattermost-server/model"660 )661 type MyPlugin struct {662 plugin.MattermostPlugin663 }664 func (p *MyPlugin) UserHasBeenCreated(c *plugin.Context, user *model.User) {665 user.Nickname = "plugin-callback-success"666 p.API.UpdateUser(user)667 }668 func main() {669 plugin.ClientMain(&MyPlugin{})670 }671 `}, th.App, th.App.NewPluginAPI)672 defer tearDown()673 user := &model.User{674 Email: model.NewId() + "success+test@example.com",675 Nickname: "Darth Vader",676 Username: "vader" + model.NewId(),677 Password: "passwd1",678 AuthService: "",679 }680 _, err := th.App.CreateUser(user)681 require.Nil(t, err)682 time.Sleep(1 * time.Second)683 user, err = th.App.GetUser(user.Id)684 require.Nil(t, err)685 require.Equal(t, "plugin-callback-success", user.Nickname)686}687func TestErrorString(t *testing.T) {688 th := Setup(t).InitBasic()689 defer th.TearDown()690 t.Run("errors.New", func(t *testing.T) {691 tearDown, _, activationErrors := SetAppEnvironmentWithPlugins(t,692 []string{693 `694 package main695 import (696 "errors"697 "github.com/mattermost/mattermost-server/plugin"698 )699 type MyPlugin struct {700 plugin.MattermostPlugin701 }702 func (p *MyPlugin) OnActivate() error {703 return errors.New("simulate failure")704 }705 func main() {706 plugin.ClientMain(&MyPlugin{})707 }708 `}, th.App, th.App.NewPluginAPI)709 defer tearDown()710 require.Len(t, activationErrors, 1)711 require.NotNil(t, activationErrors[0])712 require.Contains(t, activationErrors[0].Error(), "simulate failure")713 })714 t.Run("AppError", func(t *testing.T) {715 tearDown, _, activationErrors := SetAppEnvironmentWithPlugins(t,716 []string{717 `718 package main719 import (720 "github.com/mattermost/mattermost-server/plugin"721 "github.com/mattermost/mattermost-server/model"722 )723 type MyPlugin struct {724 plugin.MattermostPlugin725 }726 func (p *MyPlugin) OnActivate() error {727 return model.NewAppError("where", "id", map[string]interface{}{"param": 1}, "details", 42)728 }729 func main() {730 plugin.ClientMain(&MyPlugin{})731 }732 `}, th.App, th.App.NewPluginAPI)733 defer tearDown()734 require.Len(t, activationErrors, 1)735 require.NotNil(t, activationErrors[0])736 cause := errors.Cause(activationErrors[0])737 require.IsType(t, &model.AppError{}, cause)738 // params not expected, since not exported739 expectedErr := model.NewAppError("where", "id", nil, "details", 42)740 require.Equal(t, expectedErr, cause)741 })742}743func TestHookContext(t *testing.T) {744 th := Setup(t).InitBasic()745 defer th.TearDown()746 // We don't actually have a session, we are faking it so just set something arbitrarily747 th.App.Session.Id = model.NewId()748 th.App.RequestId = model.NewId()749 th.App.IpAddress = model.NewId()750 th.App.AcceptLanguage = model.NewId()751 th.App.UserAgent = model.NewId()752 var mockAPI plugintest.API753 mockAPI.On("LoadPluginConfiguration", mock.Anything).Return(nil)754 mockAPI.On("LogDebug", th.App.Session.Id).Return(nil)755 mockAPI.On("LogInfo", th.App.RequestId).Return(nil)756 mockAPI.On("LogError", th.App.IpAddress).Return(nil)757 mockAPI.On("LogWarn", th.App.AcceptLanguage).Return(nil)758 mockAPI.On("DeleteTeam", th.App.UserAgent).Return(nil)759 tearDown, _, _ := SetAppEnvironmentWithPlugins(t,760 []string{761 `762 package main763 import (764 "github.com/mattermost/mattermost-server/plugin"765 "github.com/mattermost/mattermost-server/model"766 )767 type MyPlugin struct {768 plugin.MattermostPlugin769 }770 func (p *MyPlugin) MessageHasBeenPosted(c *plugin.Context, post *model.Post) {771 p.API.LogDebug(c.SessionId)772 p.API.LogInfo(c.RequestId)773 p.API.LogError(c.IpAddress)774 p.API.LogWarn(c.AcceptLanguage)775 p.API.DeleteTeam(c.UserAgent)776 }777 func main() {778 plugin.ClientMain(&MyPlugin{})779 }780 `}, th.App, func(*model.Manifest) plugin.API { return &mockAPI })781 defer tearDown()782 post := &model.Post{783 UserId: th.BasicUser.Id,784 ChannelId: th.BasicChannel.Id,785 Message: "not this",786 CreateAt: model.GetMillis() - 10000,787 }788 _, err := th.App.CreatePost(post, th.BasicChannel, false)789 require.Nil(t, err)790}...
router.go
Source:router.go
1package routers2import (3 "ZkkfProject/controllers"4 "github.com/astaxie/beego"5)6func init() {7 //ç½ç«é¦é¡µç¸å
³8 beego.Router("/?:url", &controllers.IndexController{}, "*:Index")9 beego.Router("/effect/?:type", &controllers.IndexController{}, "*:Effect")10 beego.Router("/template/?:url", &controllers.IndexController{}, "*:Template")11 beego.Router("/detail/?:rid", &controllers.DeviceController{}, "*:Detail")12 beego.Router("/detail/relate", &controllers.DeviceController{}, "POST:Relate")13 beego.Router("/type/all", &controllers.TypeController{}, "*:All")14 beego.Router("/type/?:id", &controllers.TypeController{}, "*:Redirect")15 beego.Router("/news/all", &controllers.NewsController{}, "*:All")16 beego.Router("/news/?:rid", &controllers.NewsController{}, "*:Detail")17 beego.Router("/type/device", &controllers.DeviceController{}, "*:ListByType")18 beego.Router("/typeChild/queryByTid", &controllers.TypeChildController{}, "POST:QueryByTid")19 beego.Router("/order/add", &controllers.OrderController{}, "*:IndexAdd")20 beego.Router("/other/?:url", &controllers.IndexController{}, "*:Other")21 beego.Router("/index/mail4index", &controllers.IndexController{}, "*:Mail4Index")22 //ç¾åæ°æ®23 beego.Router("/signData", &controllers.IndexController{}, "POST:SignData")24 //ç»å½ç¸å
³25 beego.Router("/login", &controllers.LoginController{}, "*:LoginIndex")26 beego.Router("/validate", &controllers.LoginController{}, "*:Validate")27 beego.Router("/timeout", &controllers.LoginController{}, "*:Timeout")28 beego.Router("/signCode", &controllers.LoginController{}, "POST:SignCode")29 beego.Router("/sign", &controllers.LoginController{}, "POST:Sign")30 beego.Router("/forget", &controllers.LoginController{}, "POST:Forget")31 beego.Router("/reset", &controllers.LoginController{}, "POST:Reset")32 //åå°ç®¡çç¸å
³33 beego.Router("/main", &controllers.MainController{}, "*:Index")34 beego.Router("/main/?:redirect", &controllers.MainController{}, "*:Redirect")35 beego.Router("/main/alive", &controllers.MainController{}, "*:Alive")36 //æ°é»ç®¡ç37 beego.Router("/main/news/add", &controllers.NewsController{}, "POST:Add")38 beego.Router("/main/news/update", &controllers.NewsController{}, "POST:Update")39 beego.Router("/main/news/delete", &controllers.NewsController{}, "POST:Delete")40 beego.Router("/main/news/del4batch", &controllers.NewsController{}, "POST:Delete4Batch")41 beego.Router("/main/news/list", &controllers.NewsController{}, "POST:List")42 beego.Router("/index/news/all", &controllers.NewsController{}, "POST:All")43 //ç¨æ·ä¿¡æ¯ç®¡ç44 beego.Router("/main/user/list", &controllers.UserController{}, "POST:List")45 beego.Router("/main/user/add", &controllers.UserController{}, "POST:Add")46 beego.Router("/main/user/update", &controllers.UserController{}, "POST:Update")47 beego.Router("/main/user/updateProfile", &controllers.UserController{}, "POST:UpdateProfile")48 beego.Router("/main/user/updateInfo", &controllers.UserController{}, "POST:UpdateInfo")49 beego.Router("/main/user/delete", &controllers.UserController{}, "POST:Delete")50 beego.Router("/main/user/del4batch", &controllers.UserController{}, "POST:Delete4Batch")51 beego.Router("/main/user/all", &controllers.UserController{}, "POST:All")52 beego.Router("/main/user/customer", &controllers.UserController{}, "POST:AllCustomer")53 beego.Router("/main/user/listOne", &controllers.UserController{}, "POST:ListOne")54 beego.Router("/main/user/validate4mail", &controllers.UserController{}, "POST:Validate4mail")55 beego.Router("/main/user/mail4confirm", &controllers.UserController{}, "POST:Mail4confirm")56 beego.Router("/main/user/assign", &controllers.UserController{}, "POST:Assign")57 //设å¤åç»ç®¡ç58 beego.Router("/main/type/list", &controllers.TypeController{}, "POST:List")59 beego.Router("/main/type/add", &controllers.TypeController{}, "POST:Add")60 beego.Router("/main/type/update", &controllers.TypeController{}, "POST:Update")61 beego.Router("/main/type/delete", &controllers.TypeController{}, "POST:Delete")62 beego.Router("/main/type/del4batch", &controllers.TypeController{}, "POST:Delete4Batch")63 beego.Router("/main/type/all", &controllers.TypeController{}, "POST:All")64 beego.Router("/main/type/rank", &controllers.TypeController{}, "POST:Rank")65 beego.Router("/main/type/all4device", &controllers.TypeController{}, "POST:All4Device")66 //设å¤åç»ç®¡ç267 beego.Router("/main/typeChild/list", &controllers.TypeChildController{}, "POST:List")68 beego.Router("/main/typeChild/add", &controllers.TypeChildController{}, "POST:Add")69 beego.Router("/main/typeChild/update", &controllers.TypeChildController{}, "POST:Update")70 beego.Router("/main/typeChild/delete", &controllers.TypeChildController{}, "POST:Delete")71 beego.Router("/main/typeChild/del4batch", &controllers.TypeChildController{}, "POST:Delete4Batch")72 beego.Router("/main/typeChild/all", &controllers.TypeChildController{}, "POST:All")73 beego.Router("/main/typeChild/queryByTid", &controllers.TypeChildController{}, "POST:QueryByTid")74 beego.Router("/main/typeChild/queryByTidDevice", &controllers.TypeChildController{}, "POST:QueryByTidDevice")75 //设å¤ç®¡ç76 beego.Router("/main/device/list", &controllers.DeviceController{}, "POST:List")77 beego.Router("/main/device/add", &controllers.DeviceController{}, "POST:Add")78 beego.Router("/main/device/update", &controllers.DeviceController{}, "POST:Update")79 beego.Router("/main/device/delete", &controllers.DeviceController{}, "POST:Delete")80 beego.Router("/main/device/del4batch", &controllers.DeviceController{}, "POST:Delete4Batch")81 beego.Router("/main/device/all", &controllers.DeviceController{}, "POST:All")82 beego.Router("/main/device/reservation", &controllers.DeviceController{}, "POST:Reservation")83 //é¢çº¦ç®¡ç84 beego.Router("/main/reservation/list", &controllers.ReservationController{}, "POST:List")85 beego.Router("/main/reservation/list4person", &controllers.ReservationController{}, "POST:ListForPerson")86 beego.Router("/main/reservation/add", &controllers.ReservationController{}, "POST:Add")87 beego.Router("/main/reservation/update", &controllers.ReservationController{}, "POST:Update")88 beego.Router("/main/reservation/delete", &controllers.ReservationController{}, "POST:Delete")89 beego.Router("/main/reservation/delete4soft", &controllers.ReservationController{}, "POST:SoftDelete")90 beego.Router("/main/reservation/all", &controllers.ReservationController{}, "POST:All")91 beego.Router("/reservation/timeQuery", &controllers.ReservationController{}, "POST:TimeQuery")92 beego.Router("/reservation/add", &controllers.ReservationController{}, "*:IndexAdd")93 beego.Router("/main/reservation/info", &controllers.ReservationController{}, "POST:Info")94 //订å管ç95 beego.Router("/main/order/list", &controllers.OrderController{}, "POST:List")96 beego.Router("/main/order/list4person", &controllers.OrderController{}, "POST:ListForPerson")97 beego.Router("/main/order/add", &controllers.OrderController{}, "POST:Add")98 beego.Router("/main/order/update", &controllers.OrderController{}, "POST:Update")99 beego.Router("/main/order/delete", &controllers.OrderController{}, "POST:Delete")100 beego.Router("/main/order/delete4soft", &controllers.OrderController{}, "POST:SoftDelete")101 beego.Router("/main/order/all", &controllers.OrderController{}, "POST:All")102 beego.Router("/main/order/detail", &controllers.OrderController{}, "POST:Detail")103 beego.Router("/main/order/info", &controllers.OrderController{}, "POST:Info")104 //ç³»ç»è®¾ç½®ç¸å
³105 beego.Router("/main/setting/list", &controllers.SettingController{}, "POST:List")106 beego.Router("/main/setting/add", &controllers.SettingController{}, "POST:Add")107 beego.Router("/main/setting/update", &controllers.SettingController{}, "POST:Update")108 beego.Router("/main/setting/delete", &controllers.SettingController{}, "POST:Delete")109 //æ件管ç110 beego.Router("/main/file/add", &controllers.FileController{}, "POST:Add")111 beego.Router("/main/file/update", &controllers.FileController{}, "POST:Update")112 beego.Router("/main/file/delete", &controllers.FileController{}, "POST:Delete")113 beego.Router("/main/file/del4batch", &controllers.FileController{}, "POST:Delete4Batch")114 beego.Router("/main/file/list", &controllers.FileController{}, "POST:List")115 beego.Router("/main/file/all", &controllers.FileController{}, "POST:All")116 beego.Router("/main/file/list4type", &controllers.FileController{}, "POST:List4Type")117 beego.Router("/main/file/report", &controllers.FileController{}, "POST:Report")118 //å¯ææ¬æ件管ç119 beego.Router("/main/upload", &controllers.FileController{}, "POST:Upload")120 //å¾çä¸ä¼ 121 beego.Router("/main/upload4pic", &controllers.FileController{}, "POST:Upload4Pic")122 beego.Router("/main/file/upload4file", &controllers.FileController{}, "POST:Upload4File")123 //å议管ç124 beego.Router("/main/protocol/info", &controllers.ProtocolController{}, "POST:Info")125 //æ派任å¡ç®¡ç126 beego.Router("/main/assign/assign", &controllers.AssignController{}, "POST:Assign")127 beego.Router("/main/assign/list", &controllers.AssignController{}, "POST:List")128 beego.Router("/main/assign/confirm", &controllers.AssignController{}, "POST:Confirm")129 beego.Router("/main/assign/complete", &controllers.AssignController{}, "POST:Complete")130 beego.Router("/main/assign/cancel", &controllers.AssignController{}, "POST:Cancel")131 beego.Router("/main/assign/statement", &controllers.AssignController{}, "POST:Statement")132 beego.Router("/main/assign/wrong", &controllers.AssignController{}, "POST:Wrong")133 //æ¶æ¯ç®¡ç134 beego.Router("/main/message/listAll", &controllers.MessageController{}, "POST:ListAll")135 //è¯ä»·ç®¡ç136 beego.Router("/main/evaluate/add", &controllers.EvaluateController{}, "POST:Add")137 beego.Router("/main/evaluate/update", &controllers.EvaluateController{}, "POST:Update")138 beego.Router("/main/evaluate/delete", &controllers.EvaluateController{}, "POST:Delete")139 beego.Router("/main/evaluate/del4batch", &controllers.EvaluateController{}, "POST:Delete4Batch")140 beego.Router("/main/evaluate/list", &controllers.EvaluateController{}, "POST:List")141 beego.Router("/main/evaluate/list4randomId", &controllers.EvaluateController{}, "POST:ListByRandomId")142 beego.Router("/index/evaluate/list4device", &controllers.EvaluateController{}, "POST:ListByDeviceRid")143 //å®å¶é误页144 beego.ErrorController(&controllers.ErrorController{})145}...
routes.go
Source:routes.go
...8 "github.com/kobeld/duoerl/handlers/followbrands"9 "github.com/kobeld/duoerl/handlers/news"10 "github.com/kobeld/duoerl/handlers/notes"11 "github.com/kobeld/duoerl/handlers/ownitems"12 "github.com/kobeld/duoerl/handlers/posts"13 "github.com/kobeld/duoerl/handlers/products"14 "github.com/kobeld/duoerl/handlers/reviews"15 "github.com/kobeld/duoerl/handlers/sessions"16 "github.com/kobeld/duoerl/handlers/users"17 "github.com/kobeld/duoerl/handlers/wishitems"18 "github.com/kobeld/duoerl/middlewares"19 "github.com/kobeld/duoerl/models/images"20 "github.com/kobeld/mangogzip"21 "github.com/paulbellamy/mango"22 "github.com/shaoshing/train"23 "github.com/sunfmin/mangolog"24 "github.com/sunfmin/tenpu"25 "net/http"26)27func Mux() (mux *http.ServeMux) {28 p := pat.New()29 sessionMW := mango.Sessions("f908b1c425062e95d30b8d30de7123458", "duoerl", &mango.CookieOptions{Path: "/", MaxAge: 3600 * 24 * 7})30 rendererMW := middlewares.ProduceRenderer()31 authenMW := middlewares.AuthenticateUser()32 hardAuthenMW := middlewares.HardAuthenUser()33 rHtml, rJson := middlewares.RespondHtml(), middlewares.RespondJson()34 mainLayoutMW := middlewares.ProduceLayout(middlewares.MAIN_LAYOUT)35 mainStack := new(mango.Stack)36 mainStack.Middleware(mangogzip.Zipper, mangolog.Logger, sessionMW, authenMW, mainLayoutMW, rendererMW, rHtml)37 mainAjaxStack := new(mango.Stack)38 mainAjaxStack.Middleware(mangogzip.Zipper, mangolog.Logger, sessionMW, authenMW, rJson)39 hardAuthenStack := new(mango.Stack)40 hardAuthenStack.Middleware(mangogzip.Zipper, mangolog.Logger, sessionMW, hardAuthenMW, mainLayoutMW, rendererMW, rHtml)41 // User42 p.Get("/login", mainStack.HandlerFunc(sessions.LoginPage))43 p.Post("/login", mainStack.HandlerFunc(sessions.LoginAction))44 p.Get("/signup", mainStack.HandlerFunc(sessions.SignupPage))45 p.Post("/signup", mainStack.HandlerFunc(sessions.SignupAction))46 p.Get("/logout", mainStack.HandlerFunc(sessions.Logout))47 p.Post("/user/update", hardAuthenStack.HandlerFunc(users.Update))48 p.Get("/user/edit", hardAuthenStack.HandlerFunc(users.Edit))49 p.Get("/user/:id", mainStack.HandlerFunc(users.Show))50 // User post51 p.Post("/post/create", mainAjaxStack.HandlerFunc(posts.Create))52 // Brand53 p.Get("/brands", mainStack.HandlerFunc(brands.Index))54 p.Get("/brand/new", mainStack.HandlerFunc(brands.New))55 p.Post("/brand/create", mainStack.HandlerFunc(brands.Create))56 p.Get("/brand/:id", mainStack.HandlerFunc(brands.Show))57 p.Get("/brand/:id/edit", mainStack.HandlerFunc(brands.Edit))58 p.Post("/brand/update", mainStack.HandlerFunc(brands.Update))59 // Follow brand60 p.Post("/brand/follow", mainStack.HandlerFunc(followbrands.Create))61 p.Post("/brand/unfollow", mainStack.HandlerFunc(followbrands.Delete))62 // Product63 p.Get("/products", mainStack.HandlerFunc(products.Index))64 p.Get("/product/new", mainStack.HandlerFunc(products.New))65 p.Post("/product/create", mainStack.HandlerFunc(products.Create))...
post
Using AI Code Generation
1import (2func main() {3 http.HandleFunc("/", handler)4 http.ListenAndServe(":8080", nil)5}6func handler(w http.ResponseWriter, r *http.Request) {7 fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])8}9import (10func main() {11 http.HandleFunc("/", handler)12 http.ListenAndServe(":8080", nil)13}14func handler(w http.ResponseWriter, r *http.Request) {15 fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])16}17import (18func main() {19 http.HandleFunc("/", handler)20 http.ListenAndServe(":8080", nil)21}22func handler(w http.ResponseWriter, r *http.Request) {23 fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])24}25import (26func main() {27 http.HandleFunc("/", handler)28 http.ListenAndServe(":8080", nil)29}30func handler(w http.ResponseWriter, r *http.Request) {31 fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])32}33import (34func main() {35 http.HandleFunc("/", handler)36 http.ListenAndServe(":8080", nil)37}38func handler(w http.ResponseWriter, r *http.Request) {39 fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])40}41import (42func main() {43 http.HandleFunc("/", handler)44 http.ListenAndServe(":8080", nil)45}46func handler(w http.ResponseWriter, r *http.Request) {47 fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
post
Using AI Code Generation
1import (2func main() {3 http.HandleFunc("/", handler)4 http.ListenAndServe(":8080", nil)5}6func handler(w http.ResponseWriter, r *http.Request) {7 fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])8}
post
Using AI Code Generation
1import (2func main() {3 fmt.Println("URL:>", url)4 var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`)5 req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))6 req.Header.Set("X-Custom-Header", "myvalue")7 req.Header.Set("Content-Type", "application/json")8 client := &http.Client{}9 resp, err := client.Do(req)10 if err != nil {11 panic(err)12 }13 defer resp.Body.Close()14 fmt.Println("response Status:", resp.Status)15 fmt.Println("response Headers:", resp.Header)16 body, _ := ioutil.ReadAll(resp.Body)17 fmt.Println("response Body:", string(body))18}19response Headers: map[Content-Type:[application/json; charset=UTF-8] Date:[Thu, 24 Nov 2016 10:29:49 GMT] Content-Length:[50]]20response Body: {"title":"Buy cheese and bread for breakfast."}
post
Using AI Code Generation
1import (2func main() {3 http.ListenAndServe("localhost:8000", nil)4}5func handler(w http.ResponseWriter, r *http.Request) {6 fmt.Fprintf(w, "URL.Path = %q7}8import (9func main() {10 http.ListenAndServe("localhost:8000", nil)11}12func handler(w http.ResponseWriter, r *http.Request) {13 fmt.Fprintf(w, "URL.Path = %q14}15import (16func main() {17 http.ListenAndServe("localhost:8000", nil)18}19func handler(w http.ResponseWriter, r *http.Request) {20 fmt.Fprintf(w, "URL.Path = %q21}22import (23func main() {24 http.ListenAndServe("localhost:8000", nil)25}26func handler(w http.ResponseWriter, r *http.Request) {27 fmt.Fprintf(w, "URL.Path = %q28}29import (30func main() {31 http.ListenAndServe("localhost:8000", nil)32}33func handler(w http.ResponseWriter, r *http.Request) {34 fmt.Fprintf(w, "URL.Path = %q35}36import (
post
Using AI Code Generation
1import (2type Post struct {3}4func main() {5 fmt.Println("Starting the application...")6 if err != nil {7 fmt.Printf("The HTTP request failed with error %s8 } else {9 data, _ := ioutil.ReadAll(response.Body)10 fmt.Println(string(data))11 json.Unmarshal(data, &posts)12 fmt.Println(posts)13 fmt.Println(posts[0].Title)14 fmt.Println(strconv.Itoa(posts[0].UserId))15 }16 fmt.Println("Terminating the application...")17}18import (19type Post struct {20}21func main() {22 fmt.Println("Starting the application...")23 if err != nil {24 fmt.Printf("The HTTP request failed with error %s25 } else {26 data, _ := ioutil.ReadAll(response.Body)27 fmt.Println(string(data))28 json.Unmarshal(data, &posts)29 fmt.Println(posts)30 fmt.Println(posts[0].Title)31 fmt.Println(strconv.Itoa(posts[0].UserId))32 }33 fmt.Println("Terminating the application...")34}35import (36type Post struct {37}38func main() {39 fmt.Println("Starting the application
post
Using AI Code Generation
1import (2func main() {3 fmt.Println("URL:>", url)4 var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`)5 req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))6 req.Header.Set("X-Custom-Header", "myvalue")7 req.Header.Set("Content-Type", "application/json")8 client := &http.Client{}9 resp, err := client.Do(req)10 if err != nil {11 panic(err)12 }13 defer resp.Body.Close()14 fmt.Println("response Status:", resp.Status)15 fmt.Println("response Headers:", resp.Header)16 body, _ := ioutil.ReadAll(resp.Body)17 fmt.Println("response Body:", string(body))18}
post
Using AI Code Generation
1import (2func main() {3 fmt.Println("URL:>", url)4 var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`)5 req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))6 req.Header.Set("X-Custom-Header", "myvalue")7 req.Header.Set("Content-Type", "application/json")8 client := &http.Client{}9 resp, err := client.Do(req)10 if err != nil {11 panic(err)12 }13 defer resp.Body.Close()14 fmt.Println("response Status:", resp.Status)15 fmt.Println("response Headers:", resp.Header)16 body, _ := ioutil.ReadAll(resp.Body)17 fmt.Println("response Body:", string(body))18}19import (20func main() {21 fmt.Println("URL:>", url)22 var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`)23 req, err := http.NewRequest("PUT", url, bytes.NewBuffer(jsonStr))24 req.Header.Set("X-Custom-Header", "myvalue")25 req.Header.Set("Content-Type", "application/json")26 client := &http.Client{}27 resp, err := client.Do(req)28 if err != nil {29 panic(err)30 }31 defer resp.Body.Close()32 fmt.Println("response Status:", resp.Status)33 fmt.Println("response Headers:", resp.Header)34 body, _ := ioutil.ReadAll(resp.Body)35 fmt.Println("response Body:", string(body))36}37import (38func main() {39 fmt.Println("URL:>", url)40 var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`)41 req, err := http.NewRequest("DELETE", url, bytes.NewBuffer(jsonStr))42 req.Header.Set("X-Custom-Header", "myvalue")43 req.Header.Set("Content-Type", "application/json")44 client := &http.Client{}45 resp, err := client.Do(req)46 if err != nil {47 panic(err)48 }
post
Using AI Code Generation
1func main() {2 if err != nil {3 log.Fatal("NewRequest: ", err)4 }5 req.Header.Add("Content-Type", "application/json")6 client := &http.Client{}7 resp, err := client.Do(req)8 if err != nil {9 log.Fatal("Do: ", err)10 }11 defer resp.Body.Close()12 body, err := ioutil.ReadAll(resp.Body)13 if err != nil {14 log.Fatal("ReadAll: ", err)15 }16 fmt.Printf("%s17}18{"message":"Hello World"}
post
Using AI Code Generation
1import (2func main() {3 fmt.Println("URL:>", url)4 var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`)5 req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))6 req.Header.Set("X-Custom-Header", "myvalue")7 req.Header.Set("Content-Type", "application/json")8 client := &http.Client{}9 resp, err := client.Do(req)10 if err != nil {11 panic(err)12 }13 defer resp.Body.Close()14 fmt.Println("response Status:", resp.Status)15 fmt.Println("response Headers:", resp.Header)16 body, _ := ioutil.ReadAll(resp.Body)17 fmt.Println("response Body:", string(body))18}19import (20func main() {21 fmt.Println("URL:>", url)22 var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`)23 req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))24 req.Header.Set("X-Custom-Header", "myvalue")25 req.Header.Set("Content-Type", "application/json")26 client := &http.Client{}27 resp, err := client.Do(req)28 if err != nil {29 panic(err)30 }31 defer resp.Body.Close()32 fmt.Println("response Status:", resp.Status)33 fmt.Println("response Headers:", resp.Header)34 body, _ := ioutil.ReadAll(resp.Body)35 fmt.Println("response Body:", string(body))36}37import (38func main() {39 fmt.Println("URL:>", url)40 var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`)41 req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))42 req.Header.Set("X-Custom-Header", "myvalue")43 req.Header.Set("Content-Type", "application/json")
post
Using AI Code Generation
1import (2func main(){3 fmt.Println("Enter the url:")4 fmt.Scan(&url)5 fmt.Println("Enter the data to post:")6 fmt.Scan(&data)7 resp, err := http.Post(url,"application/x-www-form-urlencoded",strings.NewReader(data))8 if err != nil {9 fmt.Println(err)10 }11 defer resp.Body.Close()12 body, err := ioutil.ReadAll(resp.Body)13 if err != nil {14 fmt.Println(err)15 }16 fmt.Println(string(body))17}18{19 "args": {}, 20 "files": {}, 21 "form": {}, 22 "headers": {23 },
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!!