How to use Post method of client Package

Best Testkube code snippet using client.Post

post_test.go

Source:post_test.go Github

copy

Full Screen

...19 "github.com/mattermost/mattermost-server/model"20 "github.com/mattermost/mattermost-server/utils"21 "github.com/mattermost/mattermost-server/utils/testutils"22)23func TestCreatePost(t *testing.T) {24 th := Setup().InitBasic()25 defer th.TearDown()26 Client := th.Client27 post := &model.Post{ChannelId: th.BasicChannel.Id, Message: "#hashtag a" + model.NewId() + "a", Props: model.StringInterface{model.PROPS_ADD_CHANNEL_MEMBER: "no good"}}28 rpost, resp := Client.CreatePost(post)29 CheckNoError(t, resp)30 CheckCreatedStatus(t, resp)31 if rpost.Message != post.Message {32 t.Fatal("message didn't match")33 }34 if rpost.Hashtags != "#hashtag" {35 t.Fatal("hashtag didn't match")36 }37 if len(rpost.FileIds) != 0 {38 t.Fatal("shouldn't have files")39 }40 if rpost.EditAt != 0 {41 t.Fatal("newly created post shouldn't have EditAt set")42 }43 if rpost.Props[model.PROPS_ADD_CHANNEL_MEMBER] != nil {44 t.Fatal("newly created post shouldn't have Props['add_channel_member'] set")45 }46 post.RootId = rpost.Id47 post.ParentId = rpost.Id48 _, resp = Client.CreatePost(post)49 CheckNoError(t, resp)50 post.RootId = "junk"51 _, resp = Client.CreatePost(post)52 CheckBadRequestStatus(t, resp)53 post.RootId = rpost.Id54 post.ParentId = "junk"55 _, resp = Client.CreatePost(post)56 CheckBadRequestStatus(t, resp)57 post2 := &model.Post{ChannelId: th.BasicChannel2.Id, Message: "zz" + model.NewId() + "a", CreateAt: 123}58 rpost2, _ := Client.CreatePost(post2)59 if rpost2.CreateAt == post2.CreateAt {60 t.Fatal("create at should not match")61 }62 t.Run("with file uploaded by same user", func(t *testing.T) {63 fileResp, subResponse := Client.UploadFile([]byte("data"), th.BasicChannel.Id, "test")64 CheckNoError(t, subResponse)65 fileId := fileResp.FileInfos[0].Id66 postWithFiles, subResponse := Client.CreatePost(&model.Post{67 ChannelId: th.BasicChannel.Id,68 Message: "with files",69 FileIds: model.StringArray{fileId},70 })71 CheckNoError(t, subResponse)72 assert.Equal(t, model.StringArray{fileId}, postWithFiles.FileIds)73 actualPostWithFiles, subResponse := Client.GetPost(postWithFiles.Id, "")74 CheckNoError(t, subResponse)75 assert.Equal(t, model.StringArray{fileId}, actualPostWithFiles.FileIds)76 })77 t.Run("with file uploaded by different user", func(t *testing.T) {78 fileResp, subResponse := th.SystemAdminClient.UploadFile([]byte("data"), th.BasicChannel.Id, "test")79 CheckNoError(t, subResponse)80 fileId := fileResp.FileInfos[0].Id81 postWithFiles, subResponse := Client.CreatePost(&model.Post{82 ChannelId: th.BasicChannel.Id,83 Message: "with files",84 FileIds: model.StringArray{fileId},85 })86 CheckNoError(t, subResponse)87 assert.Empty(t, postWithFiles.FileIds)88 actualPostWithFiles, subResponse := Client.GetPost(postWithFiles.Id, "")89 CheckNoError(t, subResponse)90 assert.Empty(t, actualPostWithFiles.FileIds)91 })92 t.Run("with file uploaded by nouser", func(t *testing.T) {93 fileInfo, err := th.App.UploadFile([]byte("data"), th.BasicChannel.Id, "test")94 require.Nil(t, err)95 fileId := fileInfo.Id96 postWithFiles, subResponse := Client.CreatePost(&model.Post{97 ChannelId: th.BasicChannel.Id,98 Message: "with files",99 FileIds: model.StringArray{fileId},100 })101 CheckNoError(t, subResponse)102 assert.Equal(t, model.StringArray{fileId}, postWithFiles.FileIds)103 actualPostWithFiles, subResponse := Client.GetPost(postWithFiles.Id, "")104 CheckNoError(t, subResponse)105 assert.Equal(t, model.StringArray{fileId}, actualPostWithFiles.FileIds)106 })107 post.RootId = ""108 post.ParentId = ""109 post.Type = model.POST_SYSTEM_GENERIC110 _, resp = Client.CreatePost(post)111 CheckBadRequestStatus(t, resp)112 post.Type = ""113 post.RootId = rpost2.Id114 post.ParentId = rpost2.Id115 _, resp = Client.CreatePost(post)116 CheckBadRequestStatus(t, resp)117 post.RootId = ""118 post.ParentId = ""119 post.ChannelId = "junk"120 _, resp = Client.CreatePost(post)121 CheckForbiddenStatus(t, resp)122 post.ChannelId = model.NewId()123 _, resp = Client.CreatePost(post)124 CheckForbiddenStatus(t, resp)125 if r, err := Client.DoApiPost("/posts", "garbage"); err == nil {126 t.Fatal("should have errored")127 } else {128 if r.StatusCode != http.StatusBadRequest {129 t.Log("actual: " + strconv.Itoa(r.StatusCode))130 t.Log("expected: " + strconv.Itoa(http.StatusBadRequest))131 t.Fatal("wrong status code")132 }133 }134 Client.Logout()135 _, resp = Client.CreatePost(post)136 CheckUnauthorizedStatus(t, resp)137 post.ChannelId = th.BasicChannel.Id138 post.CreateAt = 123139 rpost, resp = th.SystemAdminClient.CreatePost(post)140 CheckNoError(t, resp)141 if rpost.CreateAt != post.CreateAt {142 t.Fatal("create at should match")143 }144}145func TestCreatePostEphemeral(t *testing.T) {146 th := Setup().InitBasic()147 defer th.TearDown()148 Client := th.SystemAdminClient149 ephemeralPost := &model.PostEphemeral{150 UserID: th.BasicUser2.Id,151 Post: &model.Post{ChannelId: th.BasicChannel.Id, Message: "a" + model.NewId() + "a", Props: model.StringInterface{model.PROPS_ADD_CHANNEL_MEMBER: "no good"}},152 }153 rpost, resp := Client.CreatePostEphemeral(ephemeralPost)154 CheckNoError(t, resp)155 CheckCreatedStatus(t, resp)156 if rpost.Message != ephemeralPost.Post.Message {157 t.Fatal("message didn't match")158 }159 if rpost.EditAt != 0 {160 t.Fatal("newly created ephemeral post shouldn't have EditAt set")161 }162 if r, err := Client.DoApiPost("/posts/ephemeral", "garbage"); err == nil {163 t.Fatal("should have errored")164 } else {165 if r.StatusCode != http.StatusBadRequest {166 t.Log("actual: " + strconv.Itoa(r.StatusCode))167 t.Log("expected: " + strconv.Itoa(http.StatusBadRequest))168 t.Fatal("wrong status code")169 }170 }171 Client.Logout()172 _, resp = Client.CreatePostEphemeral(ephemeralPost)173 CheckUnauthorizedStatus(t, resp)174 Client = th.Client175 _, resp = Client.CreatePostEphemeral(ephemeralPost)176 CheckForbiddenStatus(t, resp)177}178func testCreatePostWithOutgoingHook(179 t *testing.T,180 hookContentType, expectedContentType, message, triggerWord string,181 fileIds []string,182 triggerWhen int,183 commentPostType bool,184) {185 th := Setup().InitBasic()186 defer th.TearDown()187 user := th.SystemAdminUser188 team := th.BasicTeam189 channel := th.BasicChannel190 enableOutgoingWebhooks := *th.App.Config().ServiceSettings.EnableOutgoingWebhooks191 allowedUntrustedInternalConnections := *th.App.Config().ServiceSettings.AllowedUntrustedInternalConnections192 defer func() {193 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOutgoingWebhooks = enableOutgoingWebhooks })194 th.App.UpdateConfig(func(cfg *model.Config) {195 *cfg.ServiceSettings.AllowedUntrustedInternalConnections = allowedUntrustedInternalConnections196 })197 }()198 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOutgoingWebhooks = true })199 th.App.UpdateConfig(func(cfg *model.Config) {200 *cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost,127.0.0.1"201 })202 var hook *model.OutgoingWebhook203 var post *model.Post204 // Create a test server that is the target of the outgoing webhook. It will205 // validate the webhook body fields and write to the success channel on206 // success/failure.207 success := make(chan bool)208 wait := make(chan bool, 1)209 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {210 <-wait211 requestContentType := r.Header.Get("Content-Type")212 if requestContentType != expectedContentType {213 t.Logf("Content-Type is %s, should be %s", requestContentType, expectedContentType)214 success <- false215 return216 }217 expectedPayload := &model.OutgoingWebhookPayload{218 Token: hook.Token,219 TeamId: hook.TeamId,220 TeamDomain: team.Name,221 ChannelId: post.ChannelId,222 ChannelName: channel.Name,223 Timestamp: post.CreateAt,224 UserId: post.UserId,225 UserName: user.Username,226 PostId: post.Id,227 Text: post.Message,228 TriggerWord: triggerWord,229 FileIds: strings.Join(post.FileIds, ","),230 }231 // depending on the Content-Type, we expect to find a JSON or form encoded payload232 if requestContentType == "application/json" {233 decoder := json.NewDecoder(r.Body)234 o := &model.OutgoingWebhookPayload{}235 decoder.Decode(&o)236 if !reflect.DeepEqual(expectedPayload, o) {237 t.Logf("JSON payload is %+v, should be %+v", o, expectedPayload)238 success <- false239 return240 }241 } else {242 err := r.ParseForm()243 if err != nil {244 t.Logf("Error parsing form: %q", err)245 success <- false246 return247 }248 expectedFormValues, _ := url.ParseQuery(expectedPayload.ToFormValues())249 if !reflect.DeepEqual(expectedFormValues, r.Form) {250 t.Logf("Form values are: %q\n, should be: %q\n", r.Form, expectedFormValues)251 success <- false252 return253 }254 }255 respPostType := "" //if is empty or post will do a normal post.256 if commentPostType {257 respPostType = model.OUTGOING_HOOK_RESPONSE_TYPE_COMMENT258 }259 outGoingHookResponse := &model.OutgoingWebhookResponse{260 Text: model.NewString("some test text"),261 Username: "TestCommandServer",262 IconURL: "https://www.mattermost.org/wp-content/uploads/2016/04/icon.png",263 Type: "custom_as",264 ResponseType: respPostType,265 }266 fmt.Fprintf(w, outGoingHookResponse.ToJson())267 success <- true268 }))269 defer ts.Close()270 // create an outgoing webhook, passing it the test server URL271 var triggerWords []string272 if triggerWord != "" {273 triggerWords = []string{triggerWord}274 }275 hook = &model.OutgoingWebhook{276 ChannelId: channel.Id,277 TeamId: team.Id,278 ContentType: hookContentType,279 TriggerWords: triggerWords,280 TriggerWhen: triggerWhen,281 CallbackURLs: []string{ts.URL},282 }283 hook, resp := th.SystemAdminClient.CreateOutgoingWebhook(hook)284 CheckNoError(t, resp)285 // create a post to trigger the webhook286 post = &model.Post{287 ChannelId: channel.Id,288 Message: message,289 FileIds: fileIds,290 }291 post, resp = th.SystemAdminClient.CreatePost(post)292 CheckNoError(t, resp)293 wait <- true294 // We wait for the test server to write to the success channel and we make295 // the test fail if that doesn't happen before the timeout.296 select {297 case ok := <-success:298 if !ok {299 t.Fatal("Test server did send an invalid webhook.")300 }301 case <-time.After(time.Second):302 t.Fatal("Timeout, test server did not send the webhook.")303 }304 if commentPostType {305 time.Sleep(time.Millisecond * 100)306 postList, resp := th.SystemAdminClient.GetPostThread(post.Id, "")307 CheckNoError(t, resp)308 if postList.Order[0] != post.Id {309 t.Fatal("wrong order")310 }311 if _, ok := postList.Posts[post.Id]; !ok {312 t.Fatal("should have had post")313 }314 if len(postList.Posts) != 2 {315 t.Fatal("should have 2 posts")316 }317 }318}319func TestCreatePostWithOutgoingHook_form_urlencoded(t *testing.T) {320 testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_EXACT_MATCH, false)321 testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_STARTS_WITH, false)322 testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "", "", []string{"file_id_1"}, app.TRIGGERWORDS_EXACT_MATCH, false)323 testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "", "", []string{"file_id_1"}, app.TRIGGERWORDS_STARTS_WITH, false)324 testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_EXACT_MATCH, true)325 testCreatePostWithOutgoingHook(t, "application/x-www-form-urlencoded", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_STARTS_WITH, true)326}327func TestCreatePostWithOutgoingHook_json(t *testing.T) {328 testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerword lorem ipsum", "triggerword", []string{"file_id_1, file_id_2"}, app.TRIGGERWORDS_EXACT_MATCH, false)329 testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1, file_id_2"}, app.TRIGGERWORDS_STARTS_WITH, false)330 testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerword lorem ipsum", "", []string{"file_id_1"}, app.TRIGGERWORDS_EXACT_MATCH, false)331 testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerwordaaazzz lorem ipsum", "", []string{"file_id_1"}, app.TRIGGERWORDS_STARTS_WITH, false)332 testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerword lorem ipsum", "triggerword", []string{"file_id_1, file_id_2"}, app.TRIGGERWORDS_EXACT_MATCH, true)333 testCreatePostWithOutgoingHook(t, "application/json", "application/json", "triggerwordaaazzz lorem ipsum", "", []string{"file_id_1"}, app.TRIGGERWORDS_STARTS_WITH, true)334}335// hooks created before we added the ContentType field should be considered as336// application/x-www-form-urlencoded337func TestCreatePostWithOutgoingHook_no_content_type(t *testing.T) {338 testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_EXACT_MATCH, false)339 testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_STARTS_WITH, false)340 testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "", []string{"file_id_1, file_id_2"}, app.TRIGGERWORDS_EXACT_MATCH, false)341 testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerwordaaazzz lorem ipsum", "", []string{"file_id_1, file_id_2"}, app.TRIGGERWORDS_STARTS_WITH, false)342 testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "triggerword", []string{"file_id_1"}, app.TRIGGERWORDS_EXACT_MATCH, true)343 testCreatePostWithOutgoingHook(t, "", "application/x-www-form-urlencoded", "triggerword lorem ipsum", "", []string{"file_id_1, file_id_2"}, app.TRIGGERWORDS_EXACT_MATCH, true)344}345func TestCreatePostPublic(t *testing.T) {346 th := Setup().InitBasic()347 defer th.TearDown()348 Client := th.Client349 post := &model.Post{ChannelId: th.BasicChannel.Id, Message: "#hashtag a" + model.NewId() + "a"}350 user := model.User{Email: th.GenerateTestEmail(), Nickname: "Joram Wilander", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_USER_ROLE_ID}351 ruser, resp := Client.CreateUser(&user)352 CheckNoError(t, resp)353 Client.Login(user.Email, user.Password)354 _, resp = Client.CreatePost(post)355 CheckForbiddenStatus(t, resp)356 th.App.UpdateUserRoles(ruser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_POST_ALL_PUBLIC_ROLE_ID, false)357 th.App.InvalidateAllCaches()358 Client.Login(user.Email, user.Password)359 _, resp = Client.CreatePost(post)360 CheckNoError(t, resp)361 post.ChannelId = th.BasicPrivateChannel.Id362 _, resp = Client.CreatePost(post)363 CheckForbiddenStatus(t, resp)364 th.App.UpdateUserRoles(ruser.Id, model.SYSTEM_USER_ROLE_ID, false)365 th.App.JoinUserToTeam(th.BasicTeam, ruser, "")366 th.App.UpdateTeamMemberRoles(th.BasicTeam.Id, ruser.Id, model.TEAM_USER_ROLE_ID+" "+model.TEAM_POST_ALL_PUBLIC_ROLE_ID)367 th.App.InvalidateAllCaches()368 Client.Login(user.Email, user.Password)369 post.ChannelId = th.BasicPrivateChannel.Id370 _, resp = Client.CreatePost(post)371 CheckForbiddenStatus(t, resp)372 post.ChannelId = th.BasicChannel.Id373 _, resp = Client.CreatePost(post)374 CheckNoError(t, resp)375}376func TestCreatePostAll(t *testing.T) {377 th := Setup().InitBasic()378 defer th.TearDown()379 Client := th.Client380 post := &model.Post{ChannelId: th.BasicChannel.Id, Message: "#hashtag a" + model.NewId() + "a"}381 user := model.User{Email: th.GenerateTestEmail(), Nickname: "Joram Wilander", Password: "hello1", Username: GenerateTestUsername(), Roles: model.SYSTEM_USER_ROLE_ID}382 directChannel, _ := th.App.GetOrCreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id)383 ruser, resp := Client.CreateUser(&user)384 CheckNoError(t, resp)385 Client.Login(user.Email, user.Password)386 _, resp = Client.CreatePost(post)387 CheckForbiddenStatus(t, resp)388 th.App.UpdateUserRoles(ruser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_POST_ALL_ROLE_ID, false)389 th.App.InvalidateAllCaches()390 Client.Login(user.Email, user.Password)391 _, resp = Client.CreatePost(post)392 CheckNoError(t, resp)393 post.ChannelId = th.BasicPrivateChannel.Id394 _, resp = Client.CreatePost(post)395 CheckNoError(t, resp)396 post.ChannelId = directChannel.Id397 _, resp = Client.CreatePost(post)398 CheckNoError(t, resp)399 th.App.UpdateUserRoles(ruser.Id, model.SYSTEM_USER_ROLE_ID, false)400 th.App.JoinUserToTeam(th.BasicTeam, ruser, "")401 th.App.UpdateTeamMemberRoles(th.BasicTeam.Id, ruser.Id, model.TEAM_USER_ROLE_ID+" "+model.TEAM_POST_ALL_ROLE_ID)402 th.App.InvalidateAllCaches()403 Client.Login(user.Email, user.Password)404 post.ChannelId = th.BasicPrivateChannel.Id405 _, resp = Client.CreatePost(post)406 CheckNoError(t, resp)407 post.ChannelId = th.BasicChannel.Id408 _, resp = Client.CreatePost(post)409 CheckNoError(t, resp)410 post.ChannelId = directChannel.Id411 _, resp = Client.CreatePost(post)412 CheckForbiddenStatus(t, resp)413}414func TestCreatePostSendOutOfChannelMentions(t *testing.T) {415 th := Setup().InitBasic()416 defer th.TearDown()417 Client := th.Client418 WebSocketClient, err := th.CreateWebSocketClient()419 if err != nil {420 t.Fatal(err)421 }422 WebSocketClient.Listen()423 inChannelUser := th.CreateUser()424 th.LinkUserToTeam(inChannelUser, th.BasicTeam)425 th.App.AddUserToChannel(inChannelUser, th.BasicChannel)426 post1 := &model.Post{ChannelId: th.BasicChannel.Id, Message: "@" + inChannelUser.Username}427 _, resp := Client.CreatePost(post1)428 CheckNoError(t, resp)429 CheckCreatedStatus(t, resp)430 timeout := time.After(300 * time.Millisecond)431 waiting := true432 for waiting {433 select {434 case event := <-WebSocketClient.EventChannel:435 if event.Event == model.WEBSOCKET_EVENT_EPHEMERAL_MESSAGE {436 t.Fatal("should not have ephemeral message event")437 }438 case <-timeout:439 waiting = false440 }441 }442 outOfChannelUser := th.CreateUser()443 th.LinkUserToTeam(outOfChannelUser, th.BasicTeam)444 post2 := &model.Post{ChannelId: th.BasicChannel.Id, Message: "@" + outOfChannelUser.Username}445 _, resp = Client.CreatePost(post2)446 CheckNoError(t, resp)447 CheckCreatedStatus(t, resp)448 timeout = time.After(300 * time.Millisecond)449 waiting = true450 for waiting {451 select {452 case event := <-WebSocketClient.EventChannel:453 if event.Event != model.WEBSOCKET_EVENT_EPHEMERAL_MESSAGE {454 // Ignore any other events455 continue456 }457 wpost := model.PostFromJson(strings.NewReader(event.Data["post"].(string)))458 if acm, ok := wpost.Props[model.PROPS_ADD_CHANNEL_MEMBER].(map[string]interface{}); !ok {459 t.Fatal("should have received ephemeral post with 'add_channel_member' in props")460 } else {461 if acm["post_id"] == nil || acm["user_ids"] == nil || acm["usernames"] == nil {462 t.Fatal("should not be nil")463 }464 }465 waiting = false466 case <-timeout:467 t.Fatal("timed out waiting for ephemeral message event")468 }469 }470}471func TestUpdatePost(t *testing.T) {472 th := Setup().InitBasic()473 defer th.TearDown()474 Client := th.Client475 channel := th.BasicChannel476 th.App.SetLicense(model.NewTestLicense())477 fileIds := make([]string, 3)478 data, err := testutils.ReadTestFile("test.png")479 require.Nil(t, err)480 for i := 0; i < len(fileIds); i++ {481 fileResp, resp := Client.UploadFile(data, channel.Id, "test.png")482 CheckNoError(t, resp)483 fileIds[i] = fileResp.FileInfos[0].Id484 }485 rpost, err := th.App.CreatePost(&model.Post{486 UserId: th.BasicUser.Id,487 ChannelId: channel.Id,488 Message: "zz" + model.NewId() + "a",489 FileIds: fileIds,490 }, channel, false)491 require.Nil(t, err)492 assert.Equal(t, rpost.Message, rpost.Message, "full name didn't match")493 assert.EqualValues(t, 0, rpost.EditAt, "Newly created post shouldn't have EditAt set")494 assert.Equal(t, model.StringArray(fileIds), rpost.FileIds, "FileIds should have been set")495 t.Run("same message, fewer files", func(t *testing.T) {496 msg := "zz" + model.NewId() + " update post"497 rpost.Message = msg498 rpost.UserId = ""499 rupost, resp := Client.UpdatePost(rpost.Id, &model.Post{500 Id: rpost.Id,501 Message: rpost.Message,502 FileIds: fileIds[0:2], // one fewer file id503 })504 CheckNoError(t, resp)505 assert.Equal(t, rupost.Message, msg, "failed to updates")506 assert.NotEqual(t, 0, rupost.EditAt, "EditAt not updated for post")507 assert.Equal(t, model.StringArray(fileIds), rupost.FileIds, "FileIds should have not have been updated")508 actual, resp := Client.GetPost(rpost.Id, "")509 CheckNoError(t, resp)510 assert.Equal(t, actual.Message, msg, "failed to updates")511 assert.NotEqual(t, 0, actual.EditAt, "EditAt not updated for post")512 assert.Equal(t, model.StringArray(fileIds), actual.FileIds, "FileIds should have not have been updated")513 })514 t.Run("new message, invalid props", func(t *testing.T) {515 msg1 := "#hashtag a" + model.NewId() + " update post again"516 rpost.Message = msg1517 rpost.Props[model.PROPS_ADD_CHANNEL_MEMBER] = "no good"518 rrupost, resp := Client.UpdatePost(rpost.Id, rpost)519 CheckNoError(t, resp)520 assert.Equal(t, msg1, rrupost.Message, "failed to update message")521 assert.Equal(t, "#hashtag", rrupost.Hashtags, "failed to update hashtags")522 assert.Nil(t, rrupost.Props[model.PROPS_ADD_CHANNEL_MEMBER], "failed to sanitize Props['add_channel_member'], should be nil")523 actual, resp := Client.GetPost(rpost.Id, "")524 CheckNoError(t, resp)525 assert.Equal(t, msg1, actual.Message, "failed to update message")526 assert.Equal(t, "#hashtag", actual.Hashtags, "failed to update hashtags")527 assert.Nil(t, actual.Props[model.PROPS_ADD_CHANNEL_MEMBER], "failed to sanitize Props['add_channel_member'], should be nil")528 })529 t.Run("join/leave post", func(t *testing.T) {530 rpost2, err := th.App.CreatePost(&model.Post{531 ChannelId: channel.Id,532 Message: "zz" + model.NewId() + "a",533 Type: model.POST_JOIN_LEAVE,534 UserId: th.BasicUser.Id,535 }, channel, false)536 require.Nil(t, err)537 up2 := &model.Post{538 Id: rpost2.Id,539 ChannelId: channel.Id,540 Message: "zz" + model.NewId() + " update post 2",541 }542 _, resp := Client.UpdatePost(rpost2.Id, up2)543 CheckBadRequestStatus(t, resp)544 })545 rpost3, err := th.App.CreatePost(&model.Post{546 ChannelId: channel.Id,547 Message: "zz" + model.NewId() + "a",548 UserId: th.BasicUser.Id,549 }, channel, false)550 require.Nil(t, err)551 t.Run("new message, add files", func(t *testing.T) {552 up3 := &model.Post{553 Id: rpost3.Id,554 ChannelId: channel.Id,555 Message: "zz" + model.NewId() + " update post 3",556 FileIds: fileIds[0:2],557 }558 rrupost3, resp := Client.UpdatePost(rpost3.Id, up3)559 CheckNoError(t, resp)560 assert.Empty(t, rrupost3.FileIds)561 actual, resp := Client.GetPost(rpost.Id, "")562 CheckNoError(t, resp)563 assert.Equal(t, model.StringArray(fileIds), actual.FileIds)564 })565 t.Run("add slack attachments", func(t *testing.T) {566 up4 := &model.Post{567 Id: rpost3.Id,568 ChannelId: channel.Id,569 Message: "zz" + model.NewId() + " update post 3",570 }571 up4.AddProp("attachments", []model.SlackAttachment{572 {573 Text: "Hello World",574 },575 })576 rrupost3, resp := Client.UpdatePost(rpost3.Id, up4)577 CheckNoError(t, resp)578 assert.NotEqual(t, rpost3.EditAt, rrupost3.EditAt)579 assert.NotEqual(t, rpost3.Attachments(), rrupost3.Attachments())580 })581 t.Run("logged out", func(t *testing.T) {582 Client.Logout()583 _, resp := Client.UpdatePost(rpost.Id, rpost)584 CheckUnauthorizedStatus(t, resp)585 })586 t.Run("different user", func(t *testing.T) {587 th.LoginBasic2()588 _, resp := Client.UpdatePost(rpost.Id, rpost)589 CheckForbiddenStatus(t, resp)590 Client.Logout()591 })592 t.Run("different user, but team admin", func(t *testing.T) {593 th.LoginTeamAdmin()594 _, resp := Client.UpdatePost(rpost.Id, rpost)595 CheckForbiddenStatus(t, resp)596 Client.Logout()597 })598 t.Run("different user, but system admin", func(t *testing.T) {599 _, resp := th.SystemAdminClient.UpdatePost(rpost.Id, rpost)600 CheckNoError(t, resp)601 })602}603func TestUpdateOthersPostInDirectMessageChannel(t *testing.T) {604 // This test checks that a sysadmin with the "EDIT_OTHERS_POSTS" permission can edit someone else's post in a605 // channel without a team (DM/GM). This indirectly checks for the proper cascading all the way to system-wide roles606 // on the user object of permissions based on a post in a channel with no team ID.607 th := Setup().InitBasic()608 defer th.TearDown()609 dmChannel := th.CreateDmChannel(th.SystemAdminUser)610 post := &model.Post{611 Message: "asd",612 ChannelId: dmChannel.Id,613 PendingPostId: model.NewId() + ":" + fmt.Sprint(model.GetMillis()),614 UserId: th.BasicUser.Id,615 CreateAt: 0,616 }617 post, resp := th.Client.CreatePost(post)618 CheckNoError(t, resp)619 post.Message = "changed"620 post, resp = th.SystemAdminClient.UpdatePost(post.Id, post)621 CheckNoError(t, resp)622}623func TestPatchPost(t *testing.T) {624 th := Setup().InitBasic()625 defer th.TearDown()626 Client := th.Client627 channel := th.BasicChannel628 th.App.SetLicense(model.NewTestLicense())629 fileIds := make([]string, 3)630 data, err := testutils.ReadTestFile("test.png")631 require.Nil(t, err)632 for i := 0; i < len(fileIds); i++ {633 fileResp, resp := Client.UploadFile(data, channel.Id, "test.png")634 CheckNoError(t, resp)635 fileIds[i] = fileResp.FileInfos[0].Id636 }637 post := &model.Post{638 ChannelId: channel.Id,639 IsPinned: true,640 Message: "#hashtag a message",641 Props: model.StringInterface{"channel_header": "old_header"},642 FileIds: fileIds[0:2],643 HasReactions: true,644 }645 post, _ = Client.CreatePost(post)646 var rpost *model.Post647 t.Run("new message, props, files, HasReactions bit", func(t *testing.T) {648 patch := &model.PostPatch{}649 patch.IsPinned = model.NewBool(false)650 patch.Message = model.NewString("#otherhashtag other message")651 patch.Props = &model.StringInterface{"channel_header": "new_header"}652 patchFileIds := model.StringArray(fileIds) // one extra file653 patch.FileIds = &patchFileIds654 patch.HasReactions = model.NewBool(false)655 var resp *model.Response656 rpost, resp = Client.PatchPost(post.Id, patch)657 CheckNoError(t, resp)658 assert.False(t, rpost.IsPinned, "IsPinned did not update properly")659 assert.Equal(t, "#otherhashtag other message", rpost.Message, "Message did not update properly")660 assert.Equal(t, *patch.Props, rpost.Props, "Props did not update properly")661 assert.Equal(t, "#otherhashtag", rpost.Hashtags, "Message did not update properly")662 assert.Equal(t, model.StringArray(fileIds[0:2]), rpost.FileIds, "FileIds should not update")663 assert.False(t, rpost.HasReactions, "HasReactions did not update properly")664 })665 t.Run("add slack attachments", func(t *testing.T) {666 patch2 := &model.PostPatch{}667 attachments := []model.SlackAttachment{668 {669 Text: "Hello World",670 },671 }672 patch2.Props = &model.StringInterface{"attachments": attachments}673 rpost2, resp := Client.PatchPost(post.Id, patch2)674 CheckNoError(t, resp)675 assert.NotEmpty(t, rpost2.Props["attachments"])676 assert.NotEqual(t, rpost.EditAt, rpost2.EditAt)677 })678 t.Run("invalid requests", func(t *testing.T) {679 r, err := Client.DoApiPut("/posts/"+post.Id+"/patch", "garbage")680 require.EqualError(t, err, ": Invalid or missing post in request body, ")681 require.Equal(t, http.StatusBadRequest, r.StatusCode, "wrong status code")682 patch := &model.PostPatch{}683 _, resp := Client.PatchPost("junk", patch)684 CheckBadRequestStatus(t, resp)685 })686 t.Run("unknown post", func(t *testing.T) {687 patch := &model.PostPatch{}688 _, resp := Client.PatchPost(GenerateTestId(), patch)689 CheckForbiddenStatus(t, resp)690 })691 t.Run("logged out", func(t *testing.T) {692 Client.Logout()693 patch := &model.PostPatch{}694 _, resp := Client.PatchPost(post.Id, patch)695 CheckUnauthorizedStatus(t, resp)696 })697 t.Run("different user", func(t *testing.T) {698 th.LoginBasic2()699 patch := &model.PostPatch{}700 _, resp := Client.PatchPost(post.Id, patch)701 CheckForbiddenStatus(t, resp)702 })703 t.Run("different user, but team admin", func(t *testing.T) {704 th.LoginTeamAdmin()705 patch := &model.PostPatch{}706 _, resp := Client.PatchPost(post.Id, patch)707 CheckForbiddenStatus(t, resp)708 })709 t.Run("different user, but system admin", func(t *testing.T) {710 patch := &model.PostPatch{}711 _, resp := th.SystemAdminClient.PatchPost(post.Id, patch)712 CheckNoError(t, resp)713 })714}715func TestPinPost(t *testing.T) {716 th := Setup().InitBasic()717 defer th.TearDown()718 Client := th.Client719 post := th.BasicPost720 pass, resp := Client.PinPost(post.Id)721 CheckNoError(t, resp)722 if !pass {723 t.Fatal("should have passed")724 }725 if rpost, err := th.App.GetSinglePost(post.Id); err != nil && !rpost.IsPinned {726 t.Fatal("failed to pin post")727 }728 pass, resp = Client.PinPost("junk")729 CheckBadRequestStatus(t, resp)730 if pass {731 t.Fatal("should have failed")732 }733 _, resp = Client.PinPost(GenerateTestId())734 CheckForbiddenStatus(t, resp)735 t.Run("unable-to-pin-post-in-read-only-town-square", func(t *testing.T) {736 townSquareIsReadOnly := *th.App.Config().TeamSettings.ExperimentalTownSquareIsReadOnly737 th.App.SetLicense(model.NewTestLicense())738 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = true })739 defer th.App.RemoveLicense()740 defer th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = townSquareIsReadOnly })741 channel, err := th.App.GetChannelByName("town-square", th.BasicTeam.Id, true)742 assert.Nil(t, err)743 adminPost := th.CreatePostWithClient(th.SystemAdminClient, channel)744 _, resp = Client.PinPost(adminPost.Id)745 CheckForbiddenStatus(t, resp)746 })747 Client.Logout()748 _, resp = Client.PinPost(post.Id)749 CheckUnauthorizedStatus(t, resp)750 _, resp = th.SystemAdminClient.PinPost(post.Id)751 CheckNoError(t, resp)752}753func TestUnpinPost(t *testing.T) {754 th := Setup().InitBasic()755 defer th.TearDown()756 Client := th.Client757 pinnedPost := th.CreatePinnedPost()758 pass, resp := Client.UnpinPost(pinnedPost.Id)759 CheckNoError(t, resp)760 if !pass {761 t.Fatal("should have passed")762 }763 if rpost, err := th.App.GetSinglePost(pinnedPost.Id); err != nil && rpost.IsPinned {764 t.Fatal("failed to pin post")765 }766 pass, resp = Client.UnpinPost("junk")767 CheckBadRequestStatus(t, resp)768 if pass {769 t.Fatal("should have failed")770 }771 _, resp = Client.UnpinPost(GenerateTestId())772 CheckForbiddenStatus(t, resp)773 Client.Logout()774 _, resp = Client.UnpinPost(pinnedPost.Id)775 CheckUnauthorizedStatus(t, resp)776 _, resp = th.SystemAdminClient.UnpinPost(pinnedPost.Id)777 CheckNoError(t, resp)778}779func TestGetPostsForChannel(t *testing.T) {780 th := Setup().InitBasic()781 defer th.TearDown()782 Client := th.Client783 post1 := th.CreatePost()784 post2 := th.CreatePost()785 post3 := &model.Post{ChannelId: th.BasicChannel.Id, Message: "zz" + model.NewId() + "a", RootId: post1.Id}786 post3, _ = Client.CreatePost(post3)787 time.Sleep(300 * time.Millisecond)788 since := model.GetMillis()789 time.Sleep(300 * time.Millisecond)790 post4 := th.CreatePost()791 posts, resp := Client.GetPostsForChannel(th.BasicChannel.Id, 0, 60, "")792 CheckNoError(t, resp)793 if posts.Order[0] != post4.Id {794 t.Fatal("wrong order")795 }796 if posts.Order[1] != post3.Id {797 t.Fatal("wrong order")798 }799 if posts.Order[2] != post2.Id {800 t.Fatal("wrong order")801 }802 if posts.Order[3] != post1.Id {803 t.Fatal("wrong order")804 }805 posts, resp = Client.GetPostsForChannel(th.BasicChannel.Id, 0, 3, resp.Etag)806 CheckEtag(t, posts, resp)807 posts, resp = Client.GetPostsForChannel(th.BasicChannel.Id, 0, 3, "")808 CheckNoError(t, resp)809 if len(posts.Order) != 3 {810 t.Fatal("wrong number returned")811 }812 if _, ok := posts.Posts[post3.Id]; !ok {813 t.Fatal("missing comment")814 }815 if _, ok := posts.Posts[post1.Id]; !ok {816 t.Fatal("missing root post")817 }818 posts, resp = Client.GetPostsForChannel(th.BasicChannel.Id, 1, 1, "")819 CheckNoError(t, resp)820 if posts.Order[0] != post3.Id {821 t.Fatal("wrong order")822 }823 posts, resp = Client.GetPostsForChannel(th.BasicChannel.Id, 10000, 10000, "")824 CheckNoError(t, resp)825 if len(posts.Order) != 0 {826 t.Fatal("should be no posts")827 }828 post5 := th.CreatePost()829 posts, resp = Client.GetPostsSince(th.BasicChannel.Id, since)830 CheckNoError(t, resp)831 if len(posts.Posts) != 2 {832 t.Log(posts.Posts)833 t.Fatal("should return 2 posts")834 }835 // "since" query to return empty NextPostId and PrevPostId836 if posts.NextPostId != "" {837 t.Fatal("should return an empty NextPostId")838 }839 if posts.PrevPostId != "" {840 t.Fatal("should return an empty PrevPostId")841 }842 found := make([]bool, 2)843 for _, p := range posts.Posts {844 if p.CreateAt < since {845 t.Fatal("bad create at for post returned")846 }847 if p.Id == post4.Id {848 found[0] = true849 } else if p.Id == post5.Id {850 found[1] = true851 }852 }853 for _, f := range found {854 if !f {855 t.Fatal("missing post")856 }857 }858 _, resp = Client.GetPostsForChannel("", 0, 60, "")859 CheckBadRequestStatus(t, resp)860 _, resp = Client.GetPostsForChannel("junk", 0, 60, "")861 CheckBadRequestStatus(t, resp)862 _, resp = Client.GetPostsForChannel(model.NewId(), 0, 60, "")863 CheckForbiddenStatus(t, resp)864 Client.Logout()865 _, resp = Client.GetPostsForChannel(model.NewId(), 0, 60, "")866 CheckUnauthorizedStatus(t, resp)867 _, resp = th.SystemAdminClient.GetPostsForChannel(th.BasicChannel.Id, 0, 60, "")868 CheckNoError(t, resp)869 // more tests for next_post_id, prev_post_id, and order870 // There are 12 posts composed of first 2 system messages and 10 created posts871 Client.Login(th.BasicUser.Email, th.BasicUser.Password)872 th.CreatePost() // post6873 post7 := th.CreatePost()874 post8 := th.CreatePost()875 th.CreatePost() // post9876 post10 := th.CreatePost()877 // get the system post IDs posted before the created posts above878 posts, resp = Client.GetPostsBefore(th.BasicChannel.Id, post1.Id, 0, 2, "")879 systemPostId1 := posts.Order[1]880 // similar to '/posts'881 posts, resp = Client.GetPostsForChannel(th.BasicChannel.Id, 0, 60, "")882 CheckNoError(t, resp)883 if len(posts.Order) != 12 || posts.Order[0] != post10.Id || posts.Order[11] != systemPostId1 {884 t.Fatal("should return 12 posts and match order")885 }886 if posts.NextPostId != "" {887 t.Fatal("should return an empty NextPostId")888 }889 if posts.PrevPostId != "" {890 t.Fatal("should return an empty PrevPostId")891 }892 // similar to '/posts?per_page=3'893 posts, resp = Client.GetPostsForChannel(th.BasicChannel.Id, 0, 3, "")894 CheckNoError(t, resp)895 if len(posts.Order) != 3 || posts.Order[0] != post10.Id || posts.Order[2] != post8.Id {896 t.Fatal("should return 3 posts and match order")897 }898 if posts.NextPostId != "" {899 t.Fatal("should return an empty NextPostId")900 }901 if posts.PrevPostId != post7.Id {902 t.Fatal("should return post7.Id as PrevPostId")903 }904 // similar to '/posts?per_page=3&page=1'905 posts, resp = Client.GetPostsForChannel(th.BasicChannel.Id, 1, 3, "")906 CheckNoError(t, resp)907 if len(posts.Order) != 3 || posts.Order[0] != post7.Id || posts.Order[2] != post5.Id {908 t.Fatal("should return 3 posts and match order")909 }910 if posts.NextPostId != post8.Id {911 t.Fatal("should return post8.Id as NextPostId")912 }913 if posts.PrevPostId != post4.Id {914 t.Fatal("should return post4.Id as PrevPostId")915 }916 // similar to '/posts?per_page=3&page=2'917 posts, resp = Client.GetPostsForChannel(th.BasicChannel.Id, 2, 3, "")918 CheckNoError(t, resp)919 if len(posts.Order) != 3 || posts.Order[0] != post4.Id || posts.Order[2] != post2.Id {920 t.Fatal("should return 3 posts and match order")921 }922 if posts.NextPostId != post5.Id {923 t.Fatal("should return post5.Id as NextPostId")924 }925 if posts.PrevPostId != post1.Id {926 t.Fatal("should return post1.Id as PrevPostId")927 }928 // similar to '/posts?per_page=3&page=3'929 posts, resp = Client.GetPostsForChannel(th.BasicChannel.Id, 3, 3, "")930 CheckNoError(t, resp)931 if len(posts.Order) != 3 || posts.Order[0] != post1.Id || posts.Order[2] != systemPostId1 {932 t.Fatal("should return 3 posts and match order")933 }934 if posts.NextPostId != post2.Id {935 t.Fatal("should return post2.Id as NextPostId")936 }937 if posts.PrevPostId != "" {938 t.Fatal("should return an empty PrevPostId")939 }940 // similar to '/posts?per_page=3&page=4'941 posts, resp = Client.GetPostsForChannel(th.BasicChannel.Id, 4, 3, "")942 CheckNoError(t, resp)943 if len(posts.Order) != 0 {944 t.Fatal("should return 0 post")945 }946 if posts.NextPostId != "" {947 t.Fatal("should return an empty NextPostId")948 }949 if posts.PrevPostId != "" {950 t.Fatal("should return an empty PrevPostId")951 }952}953func TestGetFlaggedPostsForUser(t *testing.T) {954 th := Setup().InitBasic()955 defer th.TearDown()956 Client := th.Client957 user := th.BasicUser958 team1 := th.BasicTeam959 channel1 := th.BasicChannel960 post1 := th.CreatePost()961 channel2 := th.CreatePublicChannel()962 post2 := th.CreatePostWithClient(Client, channel2)963 preference := model.Preference{964 UserId: user.Id,965 Category: model.PREFERENCE_CATEGORY_FLAGGED_POST,966 Name: post1.Id,967 Value: "true",968 }969 _, resp := Client.UpdatePreferences(user.Id, &model.Preferences{preference})970 CheckNoError(t, resp)971 preference.Name = post2.Id972 _, resp = Client.UpdatePreferences(user.Id, &model.Preferences{preference})973 CheckNoError(t, resp)974 opl := model.NewPostList()975 opl.AddPost(post1)976 opl.AddOrder(post1.Id)977 rpl, resp := Client.GetFlaggedPostsForUserInChannel(user.Id, channel1.Id, 0, 10)978 CheckNoError(t, resp)979 if len(rpl.Posts) != 1 {980 t.Fatal("should have returned 1 post")981 }982 if !reflect.DeepEqual(rpl.Posts, opl.Posts) {983 t.Fatal("posts should have matched")984 }985 rpl, resp = Client.GetFlaggedPostsForUserInChannel(user.Id, channel1.Id, 0, 1)986 CheckNoError(t, resp)987 if len(rpl.Posts) != 1 {988 t.Fatal("should have returned 1 post")989 }990 rpl, resp = Client.GetFlaggedPostsForUserInChannel(user.Id, channel1.Id, 1, 1)991 CheckNoError(t, resp)992 if len(rpl.Posts) != 0 {993 t.Fatal("should be empty")994 }995 rpl, resp = Client.GetFlaggedPostsForUserInChannel(user.Id, GenerateTestId(), 0, 10)996 CheckNoError(t, resp)997 if len(rpl.Posts) != 0 {998 t.Fatal("should be empty")999 }1000 rpl, resp = Client.GetFlaggedPostsForUserInChannel(user.Id, "junk", 0, 10)1001 CheckBadRequestStatus(t, resp)1002 if rpl != nil {1003 t.Fatal("should be nil")1004 }1005 opl.AddPost(post2)1006 opl.AddOrder(post2.Id)1007 rpl, resp = Client.GetFlaggedPostsForUserInTeam(user.Id, team1.Id, 0, 10)1008 CheckNoError(t, resp)1009 if len(rpl.Posts) != 2 {1010 t.Fatal("should have returned 2 posts")1011 }1012 if !reflect.DeepEqual(rpl.Posts, opl.Posts) {1013 t.Fatal("posts should have matched")1014 }1015 rpl, resp = Client.GetFlaggedPostsForUserInTeam(user.Id, team1.Id, 0, 1)1016 CheckNoError(t, resp)1017 if len(rpl.Posts) != 1 {1018 t.Fatal("should have returned 1 post")1019 }1020 rpl, resp = Client.GetFlaggedPostsForUserInTeam(user.Id, team1.Id, 1, 1)1021 CheckNoError(t, resp)1022 if len(rpl.Posts) != 1 {1023 t.Fatal("should have returned 1 post")1024 }1025 rpl, resp = Client.GetFlaggedPostsForUserInTeam(user.Id, team1.Id, 1000, 10)1026 CheckNoError(t, resp)1027 if len(rpl.Posts) != 0 {1028 t.Fatal("should be empty")1029 }1030 rpl, resp = Client.GetFlaggedPostsForUserInTeam(user.Id, GenerateTestId(), 0, 10)1031 CheckNoError(t, resp)1032 if len(rpl.Posts) != 0 {1033 t.Fatal("should be empty")1034 }1035 rpl, resp = Client.GetFlaggedPostsForUserInTeam(user.Id, "junk", 0, 10)1036 CheckBadRequestStatus(t, resp)1037 if rpl != nil {1038 t.Fatal("should be nil")1039 }1040 channel3 := th.CreatePrivateChannel()1041 post4 := th.CreatePostWithClient(Client, channel3)1042 preference.Name = post4.Id1043 Client.UpdatePreferences(user.Id, &model.Preferences{preference})1044 opl.AddPost(post4)1045 opl.AddOrder(post4.Id)1046 rpl, resp = Client.GetFlaggedPostsForUser(user.Id, 0, 10)1047 CheckNoError(t, resp)1048 if len(rpl.Posts) != 3 {1049 t.Fatal("should have returned 3 posts")1050 }1051 if !reflect.DeepEqual(rpl.Posts, opl.Posts) {1052 t.Fatal("posts should have matched")1053 }1054 rpl, resp = Client.GetFlaggedPostsForUser(user.Id, 0, 2)1055 CheckNoError(t, resp)1056 if len(rpl.Posts) != 2 {1057 t.Fatal("should have returned 2 posts")1058 }1059 rpl, resp = Client.GetFlaggedPostsForUser(user.Id, 2, 2)1060 CheckNoError(t, resp)1061 if len(rpl.Posts) != 1 {1062 t.Fatal("should have returned 1 post")1063 }1064 rpl, resp = Client.GetFlaggedPostsForUser(user.Id, 1000, 10)1065 CheckNoError(t, resp)1066 if len(rpl.Posts) != 0 {1067 t.Fatal("should be empty")1068 }1069 channel4 := th.CreateChannelWithClient(th.SystemAdminClient, model.CHANNEL_PRIVATE)1070 post5 := th.CreatePostWithClient(th.SystemAdminClient, channel4)1071 preference.Name = post5.Id1072 _, resp = Client.UpdatePreferences(user.Id, &model.Preferences{preference})1073 CheckForbiddenStatus(t, resp)1074 rpl, resp = Client.GetFlaggedPostsForUser(user.Id, 0, 10)1075 CheckNoError(t, resp)1076 if len(rpl.Posts) != 3 {1077 t.Fatal("should have returned 3 posts")1078 }1079 if !reflect.DeepEqual(rpl.Posts, opl.Posts) {1080 t.Fatal("posts should have matched")1081 }1082 th.AddUserToChannel(user, channel4)1083 _, resp = Client.UpdatePreferences(user.Id, &model.Preferences{preference})1084 CheckNoError(t, resp)1085 rpl, resp = Client.GetFlaggedPostsForUser(user.Id, 0, 10)1086 CheckNoError(t, resp)1087 opl.AddPost(post5)1088 opl.AddOrder(post5.Id)1089 if len(rpl.Posts) != 4 {1090 t.Fatal("should have returned 4 posts")1091 }1092 if !reflect.DeepEqual(rpl.Posts, opl.Posts) {1093 t.Fatal("posts should have matched")1094 }1095 err := th.App.RemoveUserFromChannel(user.Id, "", channel4)1096 if err != nil {1097 t.Error("Unable to remove user from channel")1098 }1099 rpl, resp = Client.GetFlaggedPostsForUser(user.Id, 0, 10)1100 CheckNoError(t, resp)1101 opl2 := model.NewPostList()1102 opl2.AddPost(post1)1103 opl2.AddOrder(post1.Id)1104 opl2.AddPost(post2)1105 opl2.AddOrder(post2.Id)1106 opl2.AddPost(post4)1107 opl2.AddOrder(post4.Id)1108 if len(rpl.Posts) != 3 {1109 t.Fatal("should have returned 3 posts")1110 }1111 if !reflect.DeepEqual(rpl.Posts, opl2.Posts) {1112 t.Fatal("posts should have matched")1113 }1114 _, resp = Client.GetFlaggedPostsForUser("junk", 0, 10)1115 CheckBadRequestStatus(t, resp)1116 _, resp = Client.GetFlaggedPostsForUser(GenerateTestId(), 0, 10)1117 CheckForbiddenStatus(t, resp)1118 Client.Logout()1119 _, resp = Client.GetFlaggedPostsForUserInChannel(user.Id, channel1.Id, 0, 10)1120 CheckUnauthorizedStatus(t, resp)1121 _, resp = Client.GetFlaggedPostsForUserInTeam(user.Id, team1.Id, 0, 10)1122 CheckUnauthorizedStatus(t, resp)1123 _, resp = Client.GetFlaggedPostsForUser(user.Id, 0, 10)1124 CheckUnauthorizedStatus(t, resp)1125 _, resp = th.SystemAdminClient.GetFlaggedPostsForUserInChannel(user.Id, channel1.Id, 0, 10)1126 CheckNoError(t, resp)1127 _, resp = th.SystemAdminClient.GetFlaggedPostsForUserInTeam(user.Id, team1.Id, 0, 10)1128 CheckNoError(t, resp)1129 _, resp = th.SystemAdminClient.GetFlaggedPostsForUser(user.Id, 0, 10)1130 CheckNoError(t, resp)1131}1132func TestGetPostsBefore(t *testing.T) {1133 th := Setup().InitBasic()1134 defer th.TearDown()1135 Client := th.Client1136 post1 := th.CreatePost()1137 post2 := th.CreatePost()1138 post3 := th.CreatePost()1139 post4 := th.CreatePost()1140 post5 := th.CreatePost()1141 posts, resp := Client.GetPostsBefore(th.BasicChannel.Id, post3.Id, 0, 100, "")1142 CheckNoError(t, resp)1143 found := make([]bool, 2)1144 for _, p := range posts.Posts {1145 if p.Id == post1.Id {1146 found[0] = true1147 } else if p.Id == post2.Id {1148 found[1] = true1149 }1150 if p.Id == post4.Id || p.Id == post5.Id {1151 t.Fatal("returned posts after")1152 }1153 }1154 for _, f := range found {1155 if !f {1156 t.Fatal("missing post")1157 }1158 }1159 if posts.NextPostId != post3.Id {1160 t.Fatal("should match NextPostId")1161 }1162 if posts.PrevPostId != "" {1163 t.Fatal("should match empty PrevPostId")1164 }1165 posts, resp = Client.GetPostsBefore(th.BasicChannel.Id, post4.Id, 1, 1, "")1166 CheckNoError(t, resp)1167 if len(posts.Posts) != 1 {1168 t.Fatal("too many posts returned")1169 }1170 if posts.Order[0] != post2.Id {1171 t.Fatal("should match returned post")1172 }1173 if posts.NextPostId != post3.Id {1174 t.Fatal("should match NextPostId")1175 }1176 if posts.PrevPostId != post1.Id {1177 t.Fatal("should match PrevPostId")1178 }1179 posts, resp = Client.GetPostsBefore(th.BasicChannel.Id, "junk", 1, 1, "")1180 CheckBadRequestStatus(t, resp)1181 posts, resp = Client.GetPostsBefore(th.BasicChannel.Id, post5.Id, 0, 3, "")1182 CheckNoError(t, resp)1183 if len(posts.Posts) != 3 {1184 t.Fatal("should match length of posts returned")1185 }1186 if posts.Order[0] != post4.Id {1187 t.Fatal("should match returned post")1188 }1189 if posts.Order[2] != post2.Id {1190 t.Fatal("should match returned post")1191 }1192 if posts.NextPostId != post5.Id {1193 t.Fatal("should match NextPostId")1194 }1195 if posts.PrevPostId != post1.Id {1196 t.Fatal("should match PrevPostId")1197 }1198 // get the system post IDs posted before the created posts above1199 posts, resp = Client.GetPostsBefore(th.BasicChannel.Id, post1.Id, 0, 2, "")1200 CheckNoError(t, resp)1201 systemPostId2 := posts.Order[0]1202 systemPostId1 := posts.Order[1]1203 posts, resp = Client.GetPostsBefore(th.BasicChannel.Id, post5.Id, 1, 3, "")1204 CheckNoError(t, resp)1205 if len(posts.Posts) != 3 {1206 t.Fatal("should match length of posts returned")1207 }1208 if posts.Order[0] != post1.Id {1209 t.Fatal("should match returned post")1210 }1211 if posts.Order[1] != systemPostId2 {1212 t.Fatal("should match returned post")1213 }1214 if posts.Order[2] != systemPostId1 {1215 t.Fatal("should match returned post")1216 }1217 if posts.NextPostId != post2.Id {1218 t.Fatal("should match NextPostId")1219 }1220 if posts.PrevPostId != "" {1221 t.Fatal("should return empty PrevPostId")1222 }1223 // more tests for next_post_id, prev_post_id, and order1224 // There are 12 posts composed of first 2 system messages and 10 created posts1225 post6 := th.CreatePost()1226 th.CreatePost() // post71227 post8 := th.CreatePost()1228 post9 := th.CreatePost()1229 th.CreatePost() // post101230 // similar to '/posts?before=post9'1231 posts, resp = Client.GetPostsBefore(th.BasicChannel.Id, post9.Id, 0, 60, "")1232 CheckNoError(t, resp)1233 if len(posts.Order) != 10 || posts.Order[0] != post8.Id || posts.Order[9] != systemPostId1 {1234 t.Fatal("should return 10 posts and match order")1235 }1236 if posts.NextPostId != post9.Id {1237 t.Fatal("should return post9.Id as NextPostId")1238 }1239 if posts.PrevPostId != "" {1240 t.Fatal("should return an empty PrevPostId")1241 }1242 // similar to '/posts?before=post9&per_page=3'1243 posts, resp = Client.GetPostsBefore(th.BasicChannel.Id, post9.Id, 0, 3, "")1244 CheckNoError(t, resp)1245 if len(posts.Order) != 3 || posts.Order[0] != post8.Id || posts.Order[2] != post6.Id {1246 t.Fatal("should return 3 posts and match order")1247 }1248 if posts.NextPostId != post9.Id {1249 t.Fatal("should return post9.Id as NextPostId")1250 }1251 if posts.PrevPostId != post5.Id {1252 t.Fatal("should return post5.Id as PrevPostId")1253 }1254 // similar to '/posts?before=post9&per_page=3&page=1'1255 posts, resp = Client.GetPostsBefore(th.BasicChannel.Id, post9.Id, 1, 3, "")1256 CheckNoError(t, resp)1257 if len(posts.Order) != 3 || posts.Order[0] != post5.Id || posts.Order[2] != post3.Id {1258 t.Fatal("should return 3 posts and match order")1259 }1260 if posts.NextPostId != post6.Id {1261 t.Fatal("should return post6.Id as NextPostId")1262 }1263 if posts.PrevPostId != post2.Id {1264 t.Fatal("should return post2.Id as PrevPostId")1265 }1266 // similar to '/posts?before=post9&per_page=3&page=2'1267 posts, resp = Client.GetPostsBefore(th.BasicChannel.Id, post9.Id, 2, 3, "")1268 CheckNoError(t, resp)1269 if len(posts.Order) != 3 || posts.Order[0] != post2.Id || posts.Order[2] != systemPostId2 {1270 t.Fatal("should return 3 posts and match order")1271 }1272 if posts.NextPostId != post3.Id {1273 t.Fatal("should return post3.Id as NextPostId")1274 }1275 if posts.PrevPostId != systemPostId1 {1276 t.Fatal("should return systemPostId1 as PrevPostId")1277 }1278 // similar to '/posts?before=post1&per_page=3'1279 posts, resp = Client.GetPostsBefore(th.BasicChannel.Id, post1.Id, 0, 3, "")1280 CheckNoError(t, resp)1281 if len(posts.Order) != 2 || posts.Order[0] != systemPostId2 || posts.Order[1] != systemPostId1 {1282 t.Fatal("should return 2 posts and match order")1283 }1284 if posts.NextPostId != post1.Id {1285 t.Fatal("should return post1.Id as NextPostId")1286 }1287 if posts.PrevPostId != "" {1288 t.Fatal("should return an empty PrevPostId")1289 }1290 // similar to '/posts?before=systemPostId1'1291 posts, resp = Client.GetPostsBefore(th.BasicChannel.Id, systemPostId1, 0, 60, "")1292 CheckNoError(t, resp)1293 if len(posts.Order) != 0 {1294 t.Fatal("should return 0 post")1295 }1296 if posts.NextPostId != systemPostId1 {1297 t.Fatal("should return systemPostId1 as NextPostId")1298 }1299 if posts.PrevPostId != "" {1300 t.Fatal("should return an empty PrevPostId")1301 }1302 // similar to '/posts?before=systemPostId1&per_page=60&page=1'1303 posts, resp = Client.GetPostsBefore(th.BasicChannel.Id, systemPostId1, 1, 60, "")1304 CheckNoError(t, resp)1305 if len(posts.Order) != 0 {1306 t.Fatal("should return 0 post")1307 }1308 if posts.NextPostId != "" {1309 t.Fatal("should return an empty NextPostId")1310 }1311 if posts.PrevPostId != "" {1312 t.Fatal("should return an empty PrevPostId")1313 }1314 // similar to '/posts?before=non-existent-post'1315 nonExistentPostId := model.NewId()1316 posts, resp = Client.GetPostsBefore(th.BasicChannel.Id, nonExistentPostId, 0, 60, "")1317 CheckNoError(t, resp)1318 if len(posts.Order) != 0 {1319 t.Fatal("should return 0 post")1320 }1321 if posts.NextPostId != nonExistentPostId {1322 t.Fatal("should return nonExistentPostId as NextPostId")1323 }1324 if posts.PrevPostId != "" {1325 t.Fatal("should return an empty PrevPostId")1326 }1327}1328func TestGetPostsAfter(t *testing.T) {1329 th := Setup().InitBasic()1330 defer th.TearDown()1331 Client := th.Client1332 post1 := th.CreatePost()1333 post2 := th.CreatePost()1334 post3 := th.CreatePost()1335 post4 := th.CreatePost()1336 post5 := th.CreatePost()1337 posts, resp := Client.GetPostsAfter(th.BasicChannel.Id, post3.Id, 0, 100, "")1338 CheckNoError(t, resp)1339 found := make([]bool, 2)1340 for _, p := range posts.Posts {1341 if p.Id == post4.Id {1342 found[0] = true1343 } else if p.Id == post5.Id {1344 found[1] = true1345 }1346 if p.Id == post1.Id || p.Id == post2.Id {1347 t.Fatal("returned posts before")1348 }1349 }1350 for _, f := range found {1351 if !f {1352 t.Fatal("missing post")1353 }1354 }1355 if posts.NextPostId != "" {1356 t.Fatal("should match empty NextPostId")1357 }1358 if posts.PrevPostId != post3.Id {1359 t.Fatal("should match PrevPostId")1360 }1361 posts, resp = Client.GetPostsAfter(th.BasicChannel.Id, post2.Id, 1, 1, "")1362 CheckNoError(t, resp)1363 if len(posts.Posts) != 1 {1364 t.Fatal("too many posts returned")1365 }1366 if posts.Order[0] != post4.Id {1367 t.Fatal("should match returned post")1368 }1369 if posts.NextPostId != post5.Id {1370 t.Fatal("should match NextPostId")1371 }1372 if posts.PrevPostId != post3.Id {1373 t.Fatal("should match PrevPostId")1374 }1375 posts, resp = Client.GetPostsAfter(th.BasicChannel.Id, "junk", 1, 1, "")1376 CheckBadRequestStatus(t, resp)1377 posts, resp = Client.GetPostsAfter(th.BasicChannel.Id, post1.Id, 0, 3, "")1378 CheckNoError(t, resp)1379 if len(posts.Posts) != 3 {1380 t.Fatal("should match length of posts returned")1381 }1382 if posts.Order[0] != post4.Id {1383 t.Fatal("should match returned post")1384 }1385 if posts.Order[2] != post2.Id {1386 t.Fatal("should match returned post")1387 }1388 if posts.NextPostId != post5.Id {1389 t.Fatal("should match NextPostId")1390 }1391 if posts.PrevPostId != post1.Id {1392 t.Fatal("should match PrevPostId")1393 }1394 posts, resp = Client.GetPostsAfter(th.BasicChannel.Id, post1.Id, 1, 3, "")1395 CheckNoError(t, resp)1396 if len(posts.Posts) != 1 {1397 t.Fatal("should match length of posts returned")1398 }1399 if posts.Order[0] != post5.Id {1400 t.Fatal("should match returned post")1401 }1402 if posts.NextPostId != "" {1403 t.Fatal("should match NextPostId")1404 }1405 if posts.PrevPostId != post4.Id {1406 t.Fatal("should match PrevPostId")1407 }1408 // more tests for next_post_id, prev_post_id, and order1409 // There are 12 posts composed of first 2 system messages and 10 created posts1410 post6 := th.CreatePost()1411 th.CreatePost() // post71412 post8 := th.CreatePost()1413 post9 := th.CreatePost()1414 post10 := th.CreatePost()1415 // similar to '/posts?after=post2'1416 posts, resp = Client.GetPostsAfter(th.BasicChannel.Id, post2.Id, 0, 60, "")1417 CheckNoError(t, resp)1418 if len(posts.Order) != 8 || posts.Order[0] != post10.Id || posts.Order[7] != post3.Id {1419 t.Fatal("should return 8 posts and match order")1420 }1421 if posts.NextPostId != "" {1422 t.Fatal("should return an empty NextPostId")1423 }1424 if posts.PrevPostId != post2.Id {1425 t.Fatal("should return post2.Id as PrevPostId")1426 }1427 // similar to '/posts?after=post2&per_page=3'1428 posts, resp = Client.GetPostsAfter(th.BasicChannel.Id, post2.Id, 0, 3, "")1429 CheckNoError(t, resp)1430 if len(posts.Order) != 3 || posts.Order[0] != post5.Id || posts.Order[2] != post3.Id {1431 t.Fatal("should return 3 posts and match order")1432 }1433 if posts.NextPostId != post6.Id {1434 t.Fatal("should return post6.Id as NextPostId")1435 }1436 if posts.PrevPostId != post2.Id {1437 t.Fatal("should return post2.Id as PrevPostId")1438 }1439 // similar to '/posts?after=post2&per_page=3&page=1'1440 posts, resp = Client.GetPostsAfter(th.BasicChannel.Id, post2.Id, 1, 3, "")1441 CheckNoError(t, resp)1442 if len(posts.Order) != 3 || posts.Order[0] != post8.Id || posts.Order[2] != post6.Id {1443 t.Fatal("should return 3 posts and match order")1444 }1445 if posts.NextPostId != post9.Id {1446 t.Fatal("should return post9.Id as NextPostId")1447 }1448 if posts.PrevPostId != post5.Id {1449 t.Fatal("should return post5.Id as PrevPostId")1450 }1451 // similar to '/posts?after=post2&per_page=3&page=2'1452 posts, resp = Client.GetPostsAfter(th.BasicChannel.Id, post2.Id, 2, 3, "")1453 CheckNoError(t, resp)1454 if len(posts.Order) != 2 || posts.Order[0] != post10.Id || posts.Order[1] != post9.Id {1455 t.Fatal("should return 2 posts and match order")1456 }1457 if posts.NextPostId != "" {1458 t.Fatal("should return an empty NextPostId")1459 }1460 if posts.PrevPostId != post8.Id {1461 t.Fatal("should return post8.Id as PrevPostId")1462 }1463 // similar to '/posts?after=post10'1464 posts, resp = Client.GetPostsAfter(th.BasicChannel.Id, post10.Id, 0, 60, "")1465 CheckNoError(t, resp)1466 if len(posts.Order) != 0 {1467 t.Fatal("should return 0 post")1468 }1469 if posts.NextPostId != "" {1470 t.Fatal("should return an empty NextPostId")1471 }1472 if posts.PrevPostId != post10.Id {1473 t.Fatal("should return post10.Id as PrevPostId")1474 }1475 // similar to '/posts?after=post10&page=1'1476 posts, resp = Client.GetPostsAfter(th.BasicChannel.Id, post10.Id, 1, 60, "")1477 CheckNoError(t, resp)1478 if len(posts.Order) != 0 {1479 t.Fatal("should return 0 post")1480 }1481 if posts.NextPostId != "" {1482 t.Fatal("should return an empty NextPostId")1483 }1484 if posts.PrevPostId != "" {1485 t.Fatal("should return an empty PrevPostId")1486 }1487 // similar to '/posts?after=non-existent-post'1488 nonExistentPostId := model.NewId()1489 posts, resp = Client.GetPostsAfter(th.BasicChannel.Id, nonExistentPostId, 0, 60, "")1490 CheckNoError(t, resp)1491 if len(posts.Order) != 0 {1492 t.Fatal("should return 0 post")1493 }1494 if posts.NextPostId != "" {1495 t.Fatal("should return an empty NextPostId")1496 }1497 if posts.PrevPostId != nonExistentPostId {1498 t.Fatal("should return nonExistentPostId as PrevPostId")1499 }1500}1501func TestGetPostsForChannelAroundLastUnread(t *testing.T) {1502 th := Setup().InitBasic()1503 defer th.TearDown()1504 Client := th.Client1505 userId := th.BasicUser.Id1506 channelId := th.BasicChannel.Id1507 // 12 posts = 2 systems posts + 10 created posts below1508 post1 := th.CreatePost()1509 post2 := th.CreatePost()1510 post3 := th.CreatePost()1511 post4 := th.CreatePost()1512 post5 := th.CreatePost()1513 replyPost := &model.Post{ChannelId: channelId, Message: model.NewId(), RootId: post4.Id, ParentId: post4.Id}1514 post6, resp := Client.CreatePost(replyPost)1515 CheckNoError(t, resp)1516 post7, resp := Client.CreatePost(replyPost)1517 CheckNoError(t, resp)1518 post8, resp := Client.CreatePost(replyPost)1519 CheckNoError(t, resp)1520 post9, resp := Client.CreatePost(replyPost)1521 CheckNoError(t, resp)1522 post10, resp := Client.CreatePost(replyPost)1523 CheckNoError(t, resp)1524 postIdNames := map[string]string{1525 post1.Id: "post1",1526 post2.Id: "post2",1527 post3.Id: "post3",1528 post4.Id: "post4",1529 post5.Id: "post5",1530 post6.Id: "post6 (reply to post4)",1531 post7.Id: "post7 (reply to post4)",1532 post8.Id: "post8 (reply to post4)",1533 post9.Id: "post9 (reply to post4)",1534 post10.Id: "post10 (reply to post4)",1535 }1536 namePost := func(postId string) string {1537 name, ok := postIdNames[postId]1538 if ok {1539 return name1540 }1541 return fmt.Sprintf("unknown (%s)", postId)1542 }1543 namePosts := func(postIds []string) []string {1544 namedPostIds := make([]string, 0, len(postIds))1545 for _, postId := range postIds {1546 namedPostIds = append(namedPostIds, namePost(postId))1547 }1548 return namedPostIds1549 }1550 namePostsMap := func(posts map[string]*model.Post) []string {1551 namedPostIds := make([]string, 0, len(posts))1552 for postId := range posts {1553 namedPostIds = append(namedPostIds, namePost(postId))1554 }1555 sort.Strings(namedPostIds)1556 return namedPostIds1557 }1558 assertPostList := func(t *testing.T, expected, actual *model.PostList) {1559 t.Helper()1560 require.Equal(t, namePosts(expected.Order), namePosts(actual.Order), "unexpected post order")1561 require.Equal(t, namePostsMap(expected.Posts), namePostsMap(actual.Posts), "unexpected posts")1562 require.Equal(t, namePost(expected.NextPostId), namePost(actual.NextPostId), "unexpected next post id")1563 require.Equal(t, namePost(expected.PrevPostId), namePost(actual.PrevPostId), "unexpected prev post id")1564 }1565 // All returned posts are all read by the user, since it's created by the user itself.1566 posts, resp := Client.GetPostsAroundLastUnread(userId, channelId, 20, 20)1567 CheckNoError(t, resp)1568 require.Len(t, posts.Order, 12, "Should return 12 posts only since there's no unread post")1569 // Set channel member's last viewed to 0.1570 // All returned posts are latest posts as if all previous posts were already read by the user.1571 channelMember, err := th.App.Srv.Store.Channel().GetMember(channelId, userId)1572 require.Nil(t, err)1573 channelMember.LastViewedAt = 01574 _, err = th.App.Srv.Store.Channel().UpdateMember(channelMember)1575 require.Nil(t, err)1576 th.App.Srv.Store.Post().InvalidateLastPostTimeCache(channelId)1577 posts, resp = Client.GetPostsAroundLastUnread(userId, channelId, 20, 20)1578 CheckNoError(t, resp)1579 require.Len(t, posts.Order, 12, "Should return 12 posts only since there's no unread post")1580 // get the first system post generated before the created posts above1581 posts, resp = Client.GetPostsBefore(th.BasicChannel.Id, post1.Id, 0, 2, "")1582 CheckNoError(t, resp)1583 systemPost0 := posts.Posts[posts.Order[0]]1584 postIdNames[systemPost0.Id] = "system post 0"1585 systemPost1 := posts.Posts[posts.Order[1]]1586 postIdNames[systemPost1.Id] = "system post 1"1587 // Set channel member's last viewed before post1.1588 channelMember, err = th.App.Srv.Store.Channel().GetMember(channelId, userId)1589 require.Nil(t, err)1590 channelMember.LastViewedAt = post1.CreateAt - 11591 _, err = th.App.Srv.Store.Channel().UpdateMember(channelMember)1592 require.Nil(t, err)1593 th.App.Srv.Store.Post().InvalidateLastPostTimeCache(channelId)1594 posts, resp = Client.GetPostsAroundLastUnread(userId, channelId, 3, 3)1595 CheckNoError(t, resp)1596 assertPostList(t, &model.PostList{1597 Order: []string{post3.Id, post2.Id, post1.Id, systemPost0.Id, systemPost1.Id},1598 Posts: map[string]*model.Post{1599 systemPost0.Id: systemPost0,1600 systemPost1.Id: systemPost1,1601 post1.Id: post1,1602 post2.Id: post2,1603 post3.Id: post3,1604 },1605 NextPostId: post4.Id,1606 PrevPostId: "",1607 }, posts)1608 // Set channel member's last viewed before post6.1609 channelMember, err = th.App.Srv.Store.Channel().GetMember(channelId, userId)1610 require.Nil(t, err)1611 channelMember.LastViewedAt = post6.CreateAt - 11612 _, err = th.App.Srv.Store.Channel().UpdateMember(channelMember)1613 require.Nil(t, err)1614 th.App.Srv.Store.Post().InvalidateLastPostTimeCache(channelId)1615 posts, resp = Client.GetPostsAroundLastUnread(userId, channelId, 3, 3)1616 CheckNoError(t, resp)1617 assertPostList(t, &model.PostList{1618 Order: []string{post8.Id, post7.Id, post6.Id, post5.Id, post4.Id, post3.Id},1619 Posts: map[string]*model.Post{1620 post3.Id: post3,1621 post4.Id: post4,1622 post5.Id: post5,1623 post6.Id: post6,1624 post7.Id: post7,1625 post8.Id: post8,1626 post9.Id: post9,1627 post10.Id: post10,1628 },1629 NextPostId: post9.Id,1630 PrevPostId: post2.Id,1631 }, posts)1632 // Set channel member's last viewed before post10.1633 channelMember, err = th.App.Srv.Store.Channel().GetMember(channelId, userId)1634 require.Nil(t, err)1635 channelMember.LastViewedAt = post10.CreateAt - 11636 _, err = th.App.Srv.Store.Channel().UpdateMember(channelMember)1637 require.Nil(t, err)1638 th.App.Srv.Store.Post().InvalidateLastPostTimeCache(channelId)1639 posts, resp = Client.GetPostsAroundLastUnread(userId, channelId, 3, 3)1640 CheckNoError(t, resp)1641 assertPostList(t, &model.PostList{1642 Order: []string{post10.Id, post9.Id, post8.Id, post7.Id},1643 Posts: map[string]*model.Post{1644 post4.Id: post4,1645 post6.Id: post6,1646 post7.Id: post7,1647 post8.Id: post8,1648 post9.Id: post9,1649 post10.Id: post10,1650 },1651 NextPostId: "",1652 PrevPostId: post6.Id,1653 }, posts)1654 // Set channel member's last viewed equal to post10.1655 channelMember, err = th.App.Srv.Store.Channel().GetMember(channelId, userId)1656 require.Nil(t, err)1657 channelMember.LastViewedAt = post10.CreateAt1658 _, err = th.App.Srv.Store.Channel().UpdateMember(channelMember)1659 require.Nil(t, err)1660 th.App.Srv.Store.Post().InvalidateLastPostTimeCache(channelId)1661 posts, resp = Client.GetPostsAroundLastUnread(userId, channelId, 3, 3)1662 CheckNoError(t, resp)1663 assertPostList(t, &model.PostList{1664 Order: []string{post10.Id, post9.Id, post8.Id},1665 Posts: map[string]*model.Post{1666 post4.Id: post4,1667 post6.Id: post6,1668 post7.Id: post7,1669 post8.Id: post8,1670 post9.Id: post9,1671 post10.Id: post10,1672 },1673 NextPostId: "",1674 PrevPostId: post7.Id,1675 }, posts)1676 // Set channel member's last viewed to just before a new reply to a previous thread, not1677 // otherwise in the requested window.1678 post11 := th.CreatePost()1679 post12, resp := Client.CreatePost(&model.Post{1680 ChannelId: channelId,1681 Message: model.NewId(),1682 RootId: post4.Id,1683 ParentId: post4.Id,1684 })1685 CheckNoError(t, resp)1686 post13 := th.CreatePost()1687 postIdNames[post11.Id] = "post11"1688 postIdNames[post12.Id] = "post12 (reply to post4)"1689 postIdNames[post13.Id] = "post13"1690 channelMember, err = th.App.Srv.Store.Channel().GetMember(channelId, userId)1691 require.Nil(t, err)1692 channelMember.LastViewedAt = post12.CreateAt - 11693 _, err = th.App.Srv.Store.Channel().UpdateMember(channelMember)1694 require.Nil(t, err)1695 th.App.Srv.Store.Post().InvalidateLastPostTimeCache(channelId)1696 posts, resp = Client.GetPostsAroundLastUnread(userId, channelId, 1, 2)1697 CheckNoError(t, resp)1698 assertPostList(t, &model.PostList{1699 Order: []string{post13.Id, post12.Id, post11.Id},1700 Posts: map[string]*model.Post{1701 post4.Id: post4,1702 post6.Id: post6,1703 post7.Id: post7,1704 post8.Id: post8,1705 post9.Id: post9,1706 post10.Id: post10,1707 post11.Id: post11,1708 post12.Id: post12,1709 post13.Id: post13,1710 },1711 NextPostId: "",1712 PrevPostId: post10.Id,1713 }, posts)1714}1715func TestGetPost(t *testing.T) {1716 th := Setup().InitBasic()1717 defer th.TearDown()1718 Client := th.Client1719 post, resp := Client.GetPost(th.BasicPost.Id, "")1720 CheckNoError(t, resp)1721 if post.Id != th.BasicPost.Id {1722 t.Fatal("post ids don't match")1723 }1724 post, resp = Client.GetPost(th.BasicPost.Id, resp.Etag)1725 CheckEtag(t, post, resp)1726 _, resp = Client.GetPost("", "")1727 CheckNotFoundStatus(t, resp)1728 _, resp = Client.GetPost("junk", "")1729 CheckBadRequestStatus(t, resp)1730 _, resp = Client.GetPost(model.NewId(), "")1731 CheckNotFoundStatus(t, resp)1732 Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser.Id)1733 // Channel is public, should be able to read post1734 _, resp = Client.GetPost(th.BasicPost.Id, "")1735 CheckNoError(t, resp)1736 privatePost := th.CreatePostWithClient(Client, th.BasicPrivateChannel)1737 _, resp = Client.GetPost(privatePost.Id, "")1738 CheckNoError(t, resp)1739 Client.RemoveUserFromChannel(th.BasicPrivateChannel.Id, th.BasicUser.Id)1740 // Channel is private, should not be able to read post1741 _, resp = Client.GetPost(privatePost.Id, "")1742 CheckForbiddenStatus(t, resp)1743 Client.Logout()1744 _, resp = Client.GetPost(model.NewId(), "")1745 CheckUnauthorizedStatus(t, resp)1746 _, resp = th.SystemAdminClient.GetPost(th.BasicPost.Id, "")1747 CheckNoError(t, resp)1748}1749func TestDeletePost(t *testing.T) {1750 th := Setup().InitBasic()1751 defer th.TearDown()1752 Client := th.Client1753 _, resp := Client.DeletePost("")1754 CheckNotFoundStatus(t, resp)1755 _, resp = Client.DeletePost("junk")1756 CheckBadRequestStatus(t, resp)1757 _, resp = Client.DeletePost(th.BasicPost.Id)1758 CheckForbiddenStatus(t, resp)1759 Client.Login(th.TeamAdminUser.Email, th.TeamAdminUser.Password)1760 _, resp = Client.DeletePost(th.BasicPost.Id)1761 CheckNoError(t, resp)1762 post := th.CreatePost()1763 user := th.CreateUser()1764 Client.Logout()1765 Client.Login(user.Email, user.Password)1766 _, resp = Client.DeletePost(post.Id)1767 CheckForbiddenStatus(t, resp)1768 Client.Logout()1769 _, resp = Client.DeletePost(model.NewId())1770 CheckUnauthorizedStatus(t, resp)1771 status, resp := th.SystemAdminClient.DeletePost(post.Id)1772 if !status {1773 t.Fatal("post should return status OK")1774 }1775 CheckNoError(t, resp)1776}1777func TestGetPostThread(t *testing.T) {1778 th := Setup().InitBasic()1779 defer th.TearDown()1780 Client := th.Client1781 post := &model.Post{ChannelId: th.BasicChannel.Id, Message: "zz" + model.NewId() + "a", RootId: th.BasicPost.Id}1782 post, _ = Client.CreatePost(post)1783 list, resp := Client.GetPostThread(th.BasicPost.Id, "")1784 CheckNoError(t, resp)1785 var list2 *model.PostList1786 list2, resp = Client.GetPostThread(th.BasicPost.Id, resp.Etag)1787 CheckEtag(t, list2, resp)1788 if list.Order[0] != th.BasicPost.Id {1789 t.Fatal("wrong order")1790 }1791 if _, ok := list.Posts[th.BasicPost.Id]; !ok {1792 t.Fatal("should have had post")1793 }1794 if _, ok := list.Posts[post.Id]; !ok {1795 t.Fatal("should have had post")1796 }1797 _, resp = Client.GetPostThread("junk", "")1798 CheckBadRequestStatus(t, resp)1799 _, resp = Client.GetPostThread(model.NewId(), "")1800 CheckNotFoundStatus(t, resp)1801 Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser.Id)1802 // Channel is public, should be able to read post1803 _, resp = Client.GetPostThread(th.BasicPost.Id, "")1804 CheckNoError(t, resp)1805 privatePost := th.CreatePostWithClient(Client, th.BasicPrivateChannel)1806 _, resp = Client.GetPostThread(privatePost.Id, "")1807 CheckNoError(t, resp)1808 Client.RemoveUserFromChannel(th.BasicPrivateChannel.Id, th.BasicUser.Id)1809 // Channel is private, should not be able to read post1810 _, resp = Client.GetPostThread(privatePost.Id, "")1811 CheckForbiddenStatus(t, resp)1812 Client.Logout()1813 _, resp = Client.GetPostThread(model.NewId(), "")1814 CheckUnauthorizedStatus(t, resp)1815 _, resp = th.SystemAdminClient.GetPostThread(th.BasicPost.Id, "")1816 CheckNoError(t, resp)1817}1818func TestSearchPosts(t *testing.T) {1819 th := Setup().InitBasic()1820 defer th.TearDown()1821 experimentalViewArchivedChannels := *th.App.Config().TeamSettings.ExperimentalViewArchivedChannels1822 defer func() {1823 th.App.UpdateConfig(func(cfg *model.Config) {1824 cfg.TeamSettings.ExperimentalViewArchivedChannels = &experimentalViewArchivedChannels1825 })1826 }()1827 th.App.UpdateConfig(func(cfg *model.Config) {1828 *cfg.TeamSettings.ExperimentalViewArchivedChannels = true1829 })1830 th.LoginBasic()1831 Client := th.Client1832 message := "search for post1"1833 _ = th.CreateMessagePost(message)1834 message = "search for post2"1835 post2 := th.CreateMessagePost(message)1836 message = "#hashtag search for post3"1837 post3 := th.CreateMessagePost(message)1838 message = "hashtag for post4"1839 _ = th.CreateMessagePost(message)1840 archivedChannel := th.CreatePublicChannel()1841 _ = th.CreateMessagePostWithClient(th.Client, archivedChannel, "#hashtag for post3")1842 th.Client.DeleteChannel(archivedChannel.Id)1843 terms := "search"1844 isOrSearch := false1845 timezoneOffset := 51846 searchParams := model.SearchParameter{1847 Terms: &terms,1848 IsOrSearch: &isOrSearch,1849 TimeZoneOffset: &timezoneOffset,1850 }1851 posts, resp := Client.SearchPostsWithParams(th.BasicTeam.Id, &searchParams)1852 CheckNoError(t, resp)1853 if len(posts.Order) != 3 {1854 t.Fatal("wrong search")1855 }1856 terms = "search"1857 page := 01858 perPage := 21859 searchParams = model.SearchParameter{1860 Terms: &terms,1861 IsOrSearch: &isOrSearch,1862 TimeZoneOffset: &timezoneOffset,1863 Page: &page,1864 PerPage: &perPage,1865 }1866 posts2, resp := Client.SearchPostsWithParams(th.BasicTeam.Id, &searchParams)1867 CheckNoError(t, resp)1868 if len(posts2.Order) != 3 { // We don't support paging for DB search yet, modify this when we do.1869 t.Fatal("Wrong number of posts", len(posts2.Order))1870 }1871 assert.Equal(t, posts.Order[0], posts2.Order[0])1872 assert.Equal(t, posts.Order[1], posts2.Order[1])1873 page = 11874 searchParams = model.SearchParameter{1875 Terms: &terms,1876 IsOrSearch: &isOrSearch,1877 TimeZoneOffset: &timezoneOffset,1878 Page: &page,1879 PerPage: &perPage,1880 }1881 posts2, resp = Client.SearchPostsWithParams(th.BasicTeam.Id, &searchParams)1882 CheckNoError(t, resp)1883 if len(posts2.Order) != 0 { // We don't support paging for DB search yet, modify this when we do.1884 t.Fatal("Wrong number of posts", len(posts2.Order))1885 }1886 posts, resp = Client.SearchPosts(th.BasicTeam.Id, "search", false)1887 CheckNoError(t, resp)1888 if len(posts.Order) != 3 {1889 t.Fatal("wrong search")1890 }1891 posts, resp = Client.SearchPosts(th.BasicTeam.Id, "post2", false)1892 CheckNoError(t, resp)1893 if len(posts.Order) != 1 && posts.Order[0] == post2.Id {1894 t.Fatal("wrong search")1895 }1896 posts, resp = Client.SearchPosts(th.BasicTeam.Id, "#hashtag", false)1897 CheckNoError(t, resp)1898 if len(posts.Order) != 1 && posts.Order[0] == post3.Id {1899 t.Fatal("wrong search")1900 }1901 terms = "#hashtag"1902 includeDeletedChannels := true1903 searchParams = model.SearchParameter{1904 Terms: &terms,1905 IsOrSearch: &isOrSearch,1906 TimeZoneOffset: &timezoneOffset,1907 IncludeDeletedChannels: &includeDeletedChannels,1908 }1909 posts, resp = Client.SearchPostsWithParams(th.BasicTeam.Id, &searchParams)1910 CheckNoError(t, resp)1911 if len(posts.Order) != 2 {1912 t.Fatal("wrong search")1913 }1914 th.App.UpdateConfig(func(cfg *model.Config) {1915 *cfg.TeamSettings.ExperimentalViewArchivedChannels = false1916 })1917 posts, resp = Client.SearchPostsWithParams(th.BasicTeam.Id, &searchParams)1918 CheckNoError(t, resp)1919 if len(posts.Order) != 1 {1920 t.Fatal("wrong search")1921 }1922 if posts, _ = Client.SearchPosts(th.BasicTeam.Id, "*", false); len(posts.Order) != 0 {1923 t.Fatal("searching for just * shouldn't return any results")1924 }1925 posts, resp = Client.SearchPosts(th.BasicTeam.Id, "post1 post2", true)1926 CheckNoError(t, resp)1927 if len(posts.Order) != 2 {1928 t.Fatal("wrong search results")1929 }1930 _, resp = Client.SearchPosts("junk", "#sgtitlereview", false)1931 CheckBadRequestStatus(t, resp)1932 _, resp = Client.SearchPosts(model.NewId(), "#sgtitlereview", false)1933 CheckForbiddenStatus(t, resp)1934 _, resp = Client.SearchPosts(th.BasicTeam.Id, "", false)1935 CheckBadRequestStatus(t, resp)1936 Client.Logout()1937 _, resp = Client.SearchPosts(th.BasicTeam.Id, "#sgtitlereview", false)1938 CheckUnauthorizedStatus(t, resp)1939}1940func TestSearchHashtagPosts(t *testing.T) {1941 th := Setup().InitBasic()1942 defer th.TearDown()1943 th.LoginBasic()1944 Client := th.Client1945 message := "#sgtitlereview with space"1946 assert.NotNil(t, th.CreateMessagePost(message))1947 message = "#sgtitlereview\n with return"1948 assert.NotNil(t, th.CreateMessagePost(message))1949 message = "no hashtag"1950 assert.NotNil(t, th.CreateMessagePost(message))1951 posts, resp := Client.SearchPosts(th.BasicTeam.Id, "#sgtitlereview", false)1952 CheckNoError(t, resp)1953 if len(posts.Order) != 2 {1954 t.Fatal("wrong search results")1955 }1956 Client.Logout()1957 _, resp = Client.SearchPosts(th.BasicTeam.Id, "#sgtitlereview", false)1958 CheckUnauthorizedStatus(t, resp)1959}1960func TestSearchPostsInChannel(t *testing.T) {1961 th := Setup().InitBasic()1962 defer th.TearDown()1963 th.LoginBasic()1964 Client := th.Client1965 channel := th.CreatePublicChannel()1966 message := "sgtitlereview with space"1967 _ = th.CreateMessagePost(message)1968 message = "sgtitlereview\n with return"1969 _ = th.CreateMessagePostWithClient(Client, th.BasicChannel2, message)1970 message = "other message with no return"1971 _ = th.CreateMessagePostWithClient(Client, th.BasicChannel2, message)1972 message = "other message with no return"1973 _ = th.CreateMessagePostWithClient(Client, channel, message)1974 if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "channel:", false); len(posts.Order) != 0 {1975 t.Fatalf("wrong number of posts returned %v", len(posts.Order))1976 }1977 if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "in:", false); len(posts.Order) != 0 {1978 t.Fatalf("wrong number of posts returned %v", len(posts.Order))1979 }1980 if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "channel:"+th.BasicChannel.Name, false); len(posts.Order) != 2 {1981 t.Fatalf("wrong number of posts returned %v", len(posts.Order))1982 }1983 if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "in:"+th.BasicChannel2.Name, false); len(posts.Order) != 2 {1984 t.Fatalf("wrong number of posts returned %v", len(posts.Order))1985 }1986 if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "channel:"+th.BasicChannel2.Name, false); len(posts.Order) != 2 {1987 t.Fatalf("wrong number of posts returned %v", len(posts.Order))1988 }1989 if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "ChAnNeL:"+th.BasicChannel2.Name, false); len(posts.Order) != 2 {1990 t.Fatalf("wrong number of posts returned %v", len(posts.Order))1991 }1992 if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "sgtitlereview", false); len(posts.Order) != 2 {1993 t.Fatalf("wrong number of posts returned %v", len(posts.Order))1994 }1995 if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "sgtitlereview channel:"+th.BasicChannel.Name, false); len(posts.Order) != 1 {1996 t.Fatalf("wrong number of posts returned %v", len(posts.Order))1997 }1998 if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "sgtitlereview in: "+th.BasicChannel2.Name, false); len(posts.Order) != 1 {1999 t.Fatalf("wrong number of posts returned %v", len(posts.Order))2000 }2001 if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "sgtitlereview channel: "+th.BasicChannel2.Name, false); len(posts.Order) != 1 {2002 t.Fatalf("wrong number of posts returned %v", len(posts.Order))2003 }2004 if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "channel: "+th.BasicChannel2.Name+" channel: "+channel.Name, false); len(posts.Order) != 3 {2005 t.Fatalf("wrong number of posts returned %v", len(posts.Order))2006 }2007}2008func TestSearchPostsFromUser(t *testing.T) {2009 th := Setup().InitBasic()2010 defer th.TearDown()2011 Client := th.Client2012 th.LoginTeamAdmin()2013 user := th.CreateUser()2014 th.LinkUserToTeam(user, th.BasicTeam)2015 th.App.AddUserToChannel(user, th.BasicChannel)2016 th.App.AddUserToChannel(user, th.BasicChannel2)2017 message := "sgtitlereview with space"2018 _ = th.CreateMessagePost(message)2019 Client.Logout()2020 th.LoginBasic2()2021 message = "sgtitlereview\n with return"2022 _ = th.CreateMessagePostWithClient(Client, th.BasicChannel2, message)2023 if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "from: "+th.TeamAdminUser.Username, false); len(posts.Order) != 2 {2024 t.Fatalf("wrong number of posts returned %v", len(posts.Order))2025 }2026 if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "from: "+th.BasicUser2.Username, false); len(posts.Order) != 1 {2027 t.Fatalf("wrong number of posts returned %v", len(posts.Order))2028 }2029 if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "from: "+th.BasicUser2.Username+" sgtitlereview", false); len(posts.Order) != 1 {2030 t.Fatalf("wrong number of posts returned %v", len(posts.Order))2031 }2032 message = "hullo"2033 _ = th.CreateMessagePost(message)2034 if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "from: "+th.BasicUser2.Username+" in:"+th.BasicChannel.Name, false); len(posts.Order) != 1 {2035 t.Fatalf("wrong number of posts returned %v", len(posts.Order))2036 }2037 Client.Login(user.Email, user.Password)2038 // wait for the join/leave messages to be created for user3 since they're done asynchronously2039 time.Sleep(100 * time.Millisecond)2040 if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "from: "+th.BasicUser2.Username, false); len(posts.Order) != 2 {2041 t.Fatalf("wrong number of posts returned %v", len(posts.Order))2042 }2043 if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "from: "+th.BasicUser2.Username+" from: "+user.Username, false); len(posts.Order) != 2 {2044 t.Fatalf("wrong number of posts returned %v", len(posts.Order))2045 }2046 if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "from: "+th.BasicUser2.Username+" from: "+user.Username+" in:"+th.BasicChannel2.Name, false); len(posts.Order) != 1 {2047 t.Fatalf("wrong number of posts returned %v", len(posts.Order))2048 }2049 message = "coconut"2050 _ = th.CreateMessagePostWithClient(Client, th.BasicChannel2, message)2051 if posts, _ := Client.SearchPosts(th.BasicTeam.Id, "from: "+th.BasicUser2.Username+" from: "+user.Username+" in:"+th.BasicChannel2.Name+" coconut", false); len(posts.Order) != 1 {2052 t.Fatalf("wrong number of posts returned %v", len(posts.Order))2053 }2054}2055func TestSearchPostsWithDateFlags(t *testing.T) {2056 th := Setup().InitBasic()2057 defer th.TearDown()2058 th.LoginBasic()2059 Client := th.Client2060 message := "sgtitlereview\n with return"2061 createDate := time.Date(2018, 8, 1, 5, 0, 0, 0, time.UTC)2062 _ = th.CreateMessagePostNoClient(th.BasicChannel, message, utils.MillisFromTime(createDate))2063 message = "other message with no return"2064 createDate = time.Date(2018, 8, 2, 5, 0, 0, 0, time.UTC)2065 _ = th.CreateMessagePostNoClient(th.BasicChannel, message, utils.MillisFromTime(createDate))2066 message = "other message with no return"2067 createDate = time.Date(2018, 8, 3, 5, 0, 0, 0, time.UTC)2068 _ = th.CreateMessagePostNoClient(th.BasicChannel, message, utils.MillisFromTime(createDate))2069 posts, _ := Client.SearchPosts(th.BasicTeam.Id, "return", false)2070 if len(posts.Order) != 3 {2071 t.Fatalf("wrong number of posts returned %v", len(posts.Order))2072 }2073 posts, _ = Client.SearchPosts(th.BasicTeam.Id, "on:", false)2074 if len(posts.Order) != 0 {2075 t.Fatalf("wrong number of posts returned %v", len(posts.Order))2076 }2077 posts, _ = Client.SearchPosts(th.BasicTeam.Id, "after:", false)2078 if len(posts.Order) != 0 {2079 t.Fatalf("wrong number of posts returned %v", len(posts.Order))2080 }2081 posts, _ = Client.SearchPosts(th.BasicTeam.Id, "before:", false)2082 if len(posts.Order) != 0 {2083 t.Fatalf("wrong number of posts returned %v", len(posts.Order))2084 }2085 posts, _ = Client.SearchPosts(th.BasicTeam.Id, "on:2018-08-01", false)2086 if len(posts.Order) != 1 {2087 t.Fatalf("wrong number of posts returned %v", len(posts.Order))2088 }2089 posts, _ = Client.SearchPosts(th.BasicTeam.Id, "after:2018-08-01", false)2090 resultCount := 02091 for _, post := range posts.Posts {2092 if post.UserId == th.BasicUser.Id {2093 resultCount = resultCount + 12094 }2095 }2096 if resultCount != 2 {2097 t.Fatalf("wrong number of posts returned %v", len(posts.Order))2098 }2099 posts, _ = Client.SearchPosts(th.BasicTeam.Id, "before:2018-08-02", false)2100 if len(posts.Order) != 1 {2101 t.Fatalf("wrong number of posts returned %v", len(posts.Order))2102 }2103 posts, _ = Client.SearchPosts(th.BasicTeam.Id, "before:2018-08-03 after:2018-08-02", false)2104 if len(posts.Order) != 0 {2105 t.Fatalf("wrong number of posts returned %v", len(posts.Order))2106 }2107 posts, _ = Client.SearchPosts(th.BasicTeam.Id, "before:2018-08-03 after:2018-08-01", false)2108 if len(posts.Order) != 1 {2109 t.Fatalf("wrong number of posts returned %v", len(posts.Order))2110 }2111}2112func TestGetFileInfosForPost(t *testing.T) {2113 th := Setup().InitBasic()2114 defer th.TearDown()2115 Client := th.Client2116 fileIds := make([]string, 3)2117 if data, err := testutils.ReadTestFile("test.png"); err != nil {2118 t.Fatal(err)2119 } else {2120 for i := 0; i < 3; i++ {2121 fileResp, _ := Client.UploadFile(data, th.BasicChannel.Id, "test.png")2122 fileIds[i] = fileResp.FileInfos[0].Id2123 }2124 }2125 post := &model.Post{ChannelId: th.BasicChannel.Id, Message: "zz" + model.NewId() + "a", FileIds: fileIds}2126 post, _ = Client.CreatePost(post)2127 infos, resp := Client.GetFileInfosForPost(post.Id, "")2128 CheckNoError(t, resp)2129 if len(infos) != 3 {2130 t.Fatal("missing file infos")2131 }2132 found := false2133 for _, info := range infos {2134 if info.Id == fileIds[0] {2135 found = true2136 }2137 }2138 if !found {2139 t.Fatal("missing file info")2140 }2141 infos, resp = Client.GetFileInfosForPost(post.Id, resp.Etag)2142 CheckEtag(t, infos, resp)2143 infos, resp = Client.GetFileInfosForPost(th.BasicPost.Id, "")2144 CheckNoError(t, resp)2145 if len(infos) != 0 {2146 t.Fatal("should have no file infos")2147 }2148 _, resp = Client.GetFileInfosForPost("junk", "")2149 CheckBadRequestStatus(t, resp)2150 _, resp = Client.GetFileInfosForPost(model.NewId(), "")2151 CheckForbiddenStatus(t, resp)2152 Client.Logout()2153 _, resp = Client.GetFileInfosForPost(model.NewId(), "")2154 CheckUnauthorizedStatus(t, resp)2155 _, resp = th.SystemAdminClient.GetFileInfosForPost(th.BasicPost.Id, "")2156 CheckNoError(t, resp)2157}...

Full Screen

Full Screen

j_tag_client.go

Source:j_tag_client.go Github

copy

Full Screen

...16 transport runtime.ClientTransport17 formats strfmt.Registry18}19/*20PostRemoteAPIJTagByRelevance post remote API j tag by relevance API21*/22func (a *Client) PostRemoteAPIJTagByRelevance(params *PostRemoteAPIJTagByRelevanceParams) (*PostRemoteAPIJTagByRelevanceOK, error) {23 // TODO: Validate the params before sending24 if params == nil {25 params = NewPostRemoteAPIJTagByRelevanceParams()26 }27 result, err := a.transport.Submit(&runtime.ClientOperation{28 ID: "PostRemoteAPIJTagByRelevance",29 Method: "POST",30 PathPattern: "/remote.api/JTag.byRelevance",31 ProducesMediaTypes: []string{""},32 ConsumesMediaTypes: []string{"application/json"},33 Schemes: []string{"http", "https"},34 Params: params,35 Reader: &PostRemoteAPIJTagByRelevanceReader{formats: a.formats},36 Context: params.Context,37 Client: params.HTTPClient,38 })39 if err != nil {40 return nil, err41 }42 return result.(*PostRemoteAPIJTagByRelevanceOK), nil43}44/*45PostRemoteAPIJTagByRelevanceForSkills post remote API j tag by relevance for skills API46*/47func (a *Client) PostRemoteAPIJTagByRelevanceForSkills(params *PostRemoteAPIJTagByRelevanceForSkillsParams) (*PostRemoteAPIJTagByRelevanceForSkillsOK, error) {48 // TODO: Validate the params before sending49 if params == nil {50 params = NewPostRemoteAPIJTagByRelevanceForSkillsParams()51 }52 result, err := a.transport.Submit(&runtime.ClientOperation{53 ID: "PostRemoteAPIJTagByRelevanceForSkills",54 Method: "POST",55 PathPattern: "/remote.api/JTag.byRelevanceForSkills",56 ProducesMediaTypes: []string{""},57 ConsumesMediaTypes: []string{"application/json"},58 Schemes: []string{"http", "https"},59 Params: params,60 Reader: &PostRemoteAPIJTagByRelevanceForSkillsReader{formats: a.formats},61 Context: params.Context,62 Client: params.HTTPClient,63 })64 if err != nil {65 return nil, err66 }67 return result.(*PostRemoteAPIJTagByRelevanceForSkillsOK), nil68}69/*70PostRemoteAPIJTagCount post remote API j tag count API71*/72func (a *Client) PostRemoteAPIJTagCount(params *PostRemoteAPIJTagCountParams) (*PostRemoteAPIJTagCountOK, error) {73 // TODO: Validate the params before sending74 if params == nil {75 params = NewPostRemoteAPIJTagCountParams()76 }77 result, err := a.transport.Submit(&runtime.ClientOperation{78 ID: "PostRemoteAPIJTagCount",79 Method: "POST",80 PathPattern: "/remote.api/JTag.count",81 ProducesMediaTypes: []string{""},82 ConsumesMediaTypes: []string{"application/json"},83 Schemes: []string{"http", "https"},84 Params: params,85 Reader: &PostRemoteAPIJTagCountReader{formats: a.formats},86 Context: params.Context,87 Client: params.HTTPClient,88 })89 if err != nil {90 return nil, err91 }92 return result.(*PostRemoteAPIJTagCountOK), nil93}94/*95PostRemoteAPIJTagCreate post remote API j tag create API96*/97func (a *Client) PostRemoteAPIJTagCreate(params *PostRemoteAPIJTagCreateParams) (*PostRemoteAPIJTagCreateOK, error) {98 // TODO: Validate the params before sending99 if params == nil {100 params = NewPostRemoteAPIJTagCreateParams()101 }102 result, err := a.transport.Submit(&runtime.ClientOperation{103 ID: "PostRemoteAPIJTagCreate",104 Method: "POST",105 PathPattern: "/remote.api/JTag.create",106 ProducesMediaTypes: []string{""},107 ConsumesMediaTypes: []string{"application/json"},108 Schemes: []string{"http", "https"},109 Params: params,110 Reader: &PostRemoteAPIJTagCreateReader{formats: a.formats},111 Context: params.Context,112 Client: params.HTTPClient,113 })114 if err != nil {115 return nil, err116 }117 return result.(*PostRemoteAPIJTagCreateOK), nil118}119/*120PostRemoteAPIJTagCreateSynonymID post remote API j tag create synonym ID API121*/122func (a *Client) PostRemoteAPIJTagCreateSynonymID(params *PostRemoteAPIJTagCreateSynonymIDParams) (*PostRemoteAPIJTagCreateSynonymIDOK, error) {123 // TODO: Validate the params before sending124 if params == nil {125 params = NewPostRemoteAPIJTagCreateSynonymIDParams()126 }127 result, err := a.transport.Submit(&runtime.ClientOperation{128 ID: "PostRemoteAPIJTagCreateSynonymID",129 Method: "POST",130 PathPattern: "/remote.api/JTag.createSynonym/{id}",131 ProducesMediaTypes: []string{""},132 ConsumesMediaTypes: []string{"application/json"},133 Schemes: []string{"http", "https"},134 Params: params,135 Reader: &PostRemoteAPIJTagCreateSynonymIDReader{formats: a.formats},136 Context: params.Context,137 Client: params.HTTPClient,138 })139 if err != nil {140 return nil, err141 }142 return result.(*PostRemoteAPIJTagCreateSynonymIDOK), nil143}144/*145PostRemoteAPIJTagCreateSystemTag post remote API j tag create system tag API146*/147func (a *Client) PostRemoteAPIJTagCreateSystemTag(params *PostRemoteAPIJTagCreateSystemTagParams) (*PostRemoteAPIJTagCreateSystemTagOK, error) {148 // TODO: Validate the params before sending149 if params == nil {150 params = NewPostRemoteAPIJTagCreateSystemTagParams()151 }152 result, err := a.transport.Submit(&runtime.ClientOperation{153 ID: "PostRemoteAPIJTagCreateSystemTag",154 Method: "POST",155 PathPattern: "/remote.api/JTag.createSystemTag",156 ProducesMediaTypes: []string{""},157 ConsumesMediaTypes: []string{"application/json"},158 Schemes: []string{"http", "https"},159 Params: params,160 Reader: &PostRemoteAPIJTagCreateSystemTagReader{formats: a.formats},161 Context: params.Context,162 Client: params.HTTPClient,163 })164 if err != nil {165 return nil, err166 }167 return result.(*PostRemoteAPIJTagCreateSystemTagOK), nil168}169/*170PostRemoteAPIJTagCursor post remote API j tag cursor API171*/172func (a *Client) PostRemoteAPIJTagCursor(params *PostRemoteAPIJTagCursorParams) (*PostRemoteAPIJTagCursorOK, error) {173 // TODO: Validate the params before sending174 if params == nil {175 params = NewPostRemoteAPIJTagCursorParams()176 }177 result, err := a.transport.Submit(&runtime.ClientOperation{178 ID: "PostRemoteAPIJTagCursor",179 Method: "POST",180 PathPattern: "/remote.api/JTag.cursor",181 ProducesMediaTypes: []string{""},182 ConsumesMediaTypes: []string{"application/json"},183 Schemes: []string{"http", "https"},184 Params: params,185 Reader: &PostRemoteAPIJTagCursorReader{formats: a.formats},186 Context: params.Context,187 Client: params.HTTPClient,188 })189 if err != nil {190 return nil, err191 }192 return result.(*PostRemoteAPIJTagCursorOK), nil193}194/*195PostRemoteAPIJTagCursorWithRelationship post remote API j tag cursor with relationship API196*/197func (a *Client) PostRemoteAPIJTagCursorWithRelationship(params *PostRemoteAPIJTagCursorWithRelationshipParams) (*PostRemoteAPIJTagCursorWithRelationshipOK, error) {198 // TODO: Validate the params before sending199 if params == nil {200 params = NewPostRemoteAPIJTagCursorWithRelationshipParams()201 }202 result, err := a.transport.Submit(&runtime.ClientOperation{203 ID: "PostRemoteAPIJTagCursorWithRelationship",204 Method: "POST",205 PathPattern: "/remote.api/JTag.cursorWithRelationship",206 ProducesMediaTypes: []string{""},207 ConsumesMediaTypes: []string{"application/json"},208 Schemes: []string{"http", "https"},209 Params: params,210 Reader: &PostRemoteAPIJTagCursorWithRelationshipReader{formats: a.formats},211 Context: params.Context,212 Client: params.HTTPClient,213 })214 if err != nil {215 return nil, err216 }217 return result.(*PostRemoteAPIJTagCursorWithRelationshipOK), nil218}219/*220PostRemoteAPIJTagDeleteID post remote API j tag delete ID API221*/222func (a *Client) PostRemoteAPIJTagDeleteID(params *PostRemoteAPIJTagDeleteIDParams) (*PostRemoteAPIJTagDeleteIDOK, error) {223 // TODO: Validate the params before sending224 if params == nil {225 params = NewPostRemoteAPIJTagDeleteIDParams()226 }227 result, err := a.transport.Submit(&runtime.ClientOperation{228 ID: "PostRemoteAPIJTagDeleteID",229 Method: "POST",230 PathPattern: "/remote.api/JTag.delete/{id}",231 ProducesMediaTypes: []string{""},232 ConsumesMediaTypes: []string{"application/json"},233 Schemes: []string{"http", "https"},234 Params: params,235 Reader: &PostRemoteAPIJTagDeleteIDReader{formats: a.formats},236 Context: params.Context,237 Client: params.HTTPClient,238 })239 if err != nil {240 return nil, err241 }242 return result.(*PostRemoteAPIJTagDeleteIDOK), nil243}244/*245PostRemoteAPIJTagEach post remote API j tag each API246*/247func (a *Client) PostRemoteAPIJTagEach(params *PostRemoteAPIJTagEachParams) (*PostRemoteAPIJTagEachOK, error) {248 // TODO: Validate the params before sending249 if params == nil {250 params = NewPostRemoteAPIJTagEachParams()251 }252 result, err := a.transport.Submit(&runtime.ClientOperation{253 ID: "PostRemoteAPIJTagEach",254 Method: "POST",255 PathPattern: "/remote.api/JTag.each",256 ProducesMediaTypes: []string{""},257 ConsumesMediaTypes: []string{"application/json"},258 Schemes: []string{"http", "https"},259 Params: params,260 Reader: &PostRemoteAPIJTagEachReader{formats: a.formats},261 Context: params.Context,262 Client: params.HTTPClient,263 })264 if err != nil {265 return nil, err266 }267 return result.(*PostRemoteAPIJTagEachOK), nil268}269/*270PostRemoteAPIJTagFetchContentTeasersID Method JTag.fetchContentTeasers271*/272func (a *Client) PostRemoteAPIJTagFetchContentTeasersID(params *PostRemoteAPIJTagFetchContentTeasersIDParams) (*PostRemoteAPIJTagFetchContentTeasersIDOK, error) {273 // TODO: Validate the params before sending274 if params == nil {275 params = NewPostRemoteAPIJTagFetchContentTeasersIDParams()276 }277 result, err := a.transport.Submit(&runtime.ClientOperation{278 ID: "PostRemoteAPIJTagFetchContentTeasersID",279 Method: "POST",280 PathPattern: "/remote.api/JTag.fetchContentTeasers/{id}",281 ProducesMediaTypes: []string{""},282 ConsumesMediaTypes: []string{"application/json"},283 Schemes: []string{"http", "https"},284 Params: params,285 Reader: &PostRemoteAPIJTagFetchContentTeasersIDReader{formats: a.formats},286 Context: params.Context,287 Client: params.HTTPClient,288 })289 if err != nil {290 return nil, err291 }292 return result.(*PostRemoteAPIJTagFetchContentTeasersIDOK), nil293}294/*295PostRemoteAPIJTagFetchContentsID post remote API j tag fetch contents ID API296*/297func (a *Client) PostRemoteAPIJTagFetchContentsID(params *PostRemoteAPIJTagFetchContentsIDParams) (*PostRemoteAPIJTagFetchContentsIDOK, error) {298 // TODO: Validate the params before sending299 if params == nil {300 params = NewPostRemoteAPIJTagFetchContentsIDParams()301 }302 result, err := a.transport.Submit(&runtime.ClientOperation{303 ID: "PostRemoteAPIJTagFetchContentsID",304 Method: "POST",305 PathPattern: "/remote.api/JTag.fetchContents/{id}",306 ProducesMediaTypes: []string{""},307 ConsumesMediaTypes: []string{"application/json"},308 Schemes: []string{"http", "https"},309 Params: params,310 Reader: &PostRemoteAPIJTagFetchContentsIDReader{formats: a.formats},311 Context: params.Context,312 Client: params.HTTPClient,313 })314 if err != nil {315 return nil, err316 }317 return result.(*PostRemoteAPIJTagFetchContentsIDOK), nil318}319/*320PostRemoteAPIJTagFetchCount post remote API j tag fetch count API321*/322func (a *Client) PostRemoteAPIJTagFetchCount(params *PostRemoteAPIJTagFetchCountParams) (*PostRemoteAPIJTagFetchCountOK, error) {323 // TODO: Validate the params before sending324 if params == nil {325 params = NewPostRemoteAPIJTagFetchCountParams()326 }327 result, err := a.transport.Submit(&runtime.ClientOperation{328 ID: "PostRemoteAPIJTagFetchCount",329 Method: "POST",330 PathPattern: "/remote.api/JTag.fetchCount",331 ProducesMediaTypes: []string{""},332 ConsumesMediaTypes: []string{"application/json"},333 Schemes: []string{"http", "https"},334 Params: params,335 Reader: &PostRemoteAPIJTagFetchCountReader{formats: a.formats},336 Context: params.Context,337 Client: params.HTTPClient,338 })339 if err != nil {340 return nil, err341 }342 return result.(*PostRemoteAPIJTagFetchCountOK), nil343}344/*345PostRemoteAPIJTagFetchFollowersWithRelationshipID post remote API j tag fetch followers with relationship ID API346*/347func (a *Client) PostRemoteAPIJTagFetchFollowersWithRelationshipID(params *PostRemoteAPIJTagFetchFollowersWithRelationshipIDParams) (*PostRemoteAPIJTagFetchFollowersWithRelationshipIDOK, error) {348 // TODO: Validate the params before sending349 if params == nil {350 params = NewPostRemoteAPIJTagFetchFollowersWithRelationshipIDParams()351 }352 result, err := a.transport.Submit(&runtime.ClientOperation{353 ID: "PostRemoteAPIJTagFetchFollowersWithRelationshipID",354 Method: "POST",355 PathPattern: "/remote.api/JTag.fetchFollowersWithRelationship/{id}",356 ProducesMediaTypes: []string{""},357 ConsumesMediaTypes: []string{"application/json"},358 Schemes: []string{"http", "https"},359 Params: params,360 Reader: &PostRemoteAPIJTagFetchFollowersWithRelationshipIDReader{formats: a.formats},361 Context: params.Context,362 Client: params.HTTPClient,363 })364 if err != nil {365 return nil, err366 }367 return result.(*PostRemoteAPIJTagFetchFollowersWithRelationshipIDOK), nil368}369/*370PostRemoteAPIJTagFetchFollowingWithRelationshipID post remote API j tag fetch following with relationship ID API371*/372func (a *Client) PostRemoteAPIJTagFetchFollowingWithRelationshipID(params *PostRemoteAPIJTagFetchFollowingWithRelationshipIDParams) (*PostRemoteAPIJTagFetchFollowingWithRelationshipIDOK, error) {373 // TODO: Validate the params before sending374 if params == nil {375 params = NewPostRemoteAPIJTagFetchFollowingWithRelationshipIDParams()376 }377 result, err := a.transport.Submit(&runtime.ClientOperation{378 ID: "PostRemoteAPIJTagFetchFollowingWithRelationshipID",379 Method: "POST",380 PathPattern: "/remote.api/JTag.fetchFollowingWithRelationship/{id}",381 ProducesMediaTypes: []string{""},382 ConsumesMediaTypes: []string{"application/json"},383 Schemes: []string{"http", "https"},384 Params: params,385 Reader: &PostRemoteAPIJTagFetchFollowingWithRelationshipIDReader{formats: a.formats},386 Context: params.Context,387 Client: params.HTTPClient,388 })389 if err != nil {390 return nil, err391 }392 return result.(*PostRemoteAPIJTagFetchFollowingWithRelationshipIDOK), nil393}394/*395PostRemoteAPIJTagFetchLastInteractorsID post remote API j tag fetch last interactors ID API396*/397func (a *Client) PostRemoteAPIJTagFetchLastInteractorsID(params *PostRemoteAPIJTagFetchLastInteractorsIDParams) (*PostRemoteAPIJTagFetchLastInteractorsIDOK, error) {398 // TODO: Validate the params before sending399 if params == nil {400 params = NewPostRemoteAPIJTagFetchLastInteractorsIDParams()401 }402 result, err := a.transport.Submit(&runtime.ClientOperation{403 ID: "PostRemoteAPIJTagFetchLastInteractorsID",404 Method: "POST",405 PathPattern: "/remote.api/JTag.fetchLastInteractors/{id}",406 ProducesMediaTypes: []string{""},407 ConsumesMediaTypes: []string{"application/json"},408 Schemes: []string{"http", "https"},409 Params: params,410 Reader: &PostRemoteAPIJTagFetchLastInteractorsIDReader{formats: a.formats},411 Context: params.Context,412 Client: params.HTTPClient,413 })414 if err != nil {415 return nil, err416 }417 return result.(*PostRemoteAPIJTagFetchLastInteractorsIDOK), nil418}419/*420PostRemoteAPIJTagFetchMyFollowees post remote API j tag fetch my followees API421*/422func (a *Client) PostRemoteAPIJTagFetchMyFollowees(params *PostRemoteAPIJTagFetchMyFolloweesParams) (*PostRemoteAPIJTagFetchMyFolloweesOK, error) {423 // TODO: Validate the params before sending424 if params == nil {425 params = NewPostRemoteAPIJTagFetchMyFolloweesParams()426 }427 result, err := a.transport.Submit(&runtime.ClientOperation{428 ID: "PostRemoteAPIJTagFetchMyFollowees",429 Method: "POST",430 PathPattern: "/remote.api/JTag.fetchMyFollowees",431 ProducesMediaTypes: []string{""},432 ConsumesMediaTypes: []string{"application/json"},433 Schemes: []string{"http", "https"},434 Params: params,435 Reader: &PostRemoteAPIJTagFetchMyFolloweesReader{formats: a.formats},436 Context: params.Context,437 Client: params.HTTPClient,438 })439 if err != nil {440 return nil, err441 }442 return result.(*PostRemoteAPIJTagFetchMyFolloweesOK), nil443}444/*445PostRemoteAPIJTagFetchSkillTags Method JTag.fetchSkillTags446*/447func (a *Client) PostRemoteAPIJTagFetchSkillTags(params *PostRemoteAPIJTagFetchSkillTagsParams) (*PostRemoteAPIJTagFetchSkillTagsOK, error) {448 // TODO: Validate the params before sending449 if params == nil {450 params = NewPostRemoteAPIJTagFetchSkillTagsParams()451 }452 result, err := a.transport.Submit(&runtime.ClientOperation{453 ID: "PostRemoteAPIJTagFetchSkillTags",454 Method: "POST",455 PathPattern: "/remote.api/JTag.fetchSkillTags",456 ProducesMediaTypes: []string{""},457 ConsumesMediaTypes: []string{"application/json"},458 Schemes: []string{"http", "https"},459 Params: params,460 Reader: &PostRemoteAPIJTagFetchSkillTagsReader{formats: a.formats},461 Context: params.Context,462 Client: params.HTTPClient,463 })464 if err != nil {465 return nil, err466 }467 return result.(*PostRemoteAPIJTagFetchSkillTagsOK), nil468}469/*470PostRemoteAPIJTagFetchSynonymID post remote API j tag fetch synonym ID API471*/472func (a *Client) PostRemoteAPIJTagFetchSynonymID(params *PostRemoteAPIJTagFetchSynonymIDParams) (*PostRemoteAPIJTagFetchSynonymIDOK, error) {473 // TODO: Validate the params before sending474 if params == nil {475 params = NewPostRemoteAPIJTagFetchSynonymIDParams()476 }477 result, err := a.transport.Submit(&runtime.ClientOperation{478 ID: "PostRemoteAPIJTagFetchSynonymID",479 Method: "POST",480 PathPattern: "/remote.api/JTag.fetchSynonym/{id}",481 ProducesMediaTypes: []string{""},482 ConsumesMediaTypes: []string{"application/json"},483 Schemes: []string{"http", "https"},484 Params: params,485 Reader: &PostRemoteAPIJTagFetchSynonymIDReader{formats: a.formats},486 Context: params.Context,487 Client: params.HTTPClient,488 })489 if err != nil {490 return nil, err491 }492 return result.(*PostRemoteAPIJTagFetchSynonymIDOK), nil493}494/*495PostRemoteAPIJTagFetchSystemTags post remote API j tag fetch system tags API496*/497func (a *Client) PostRemoteAPIJTagFetchSystemTags(params *PostRemoteAPIJTagFetchSystemTagsParams) (*PostRemoteAPIJTagFetchSystemTagsOK, error) {498 // TODO: Validate the params before sending499 if params == nil {500 params = NewPostRemoteAPIJTagFetchSystemTagsParams()501 }502 result, err := a.transport.Submit(&runtime.ClientOperation{503 ID: "PostRemoteAPIJTagFetchSystemTags",504 Method: "POST",505 PathPattern: "/remote.api/JTag.fetchSystemTags",506 ProducesMediaTypes: []string{""},507 ConsumesMediaTypes: []string{"application/json"},508 Schemes: []string{"http", "https"},509 Params: params,510 Reader: &PostRemoteAPIJTagFetchSystemTagsReader{formats: a.formats},511 Context: params.Context,512 Client: params.HTTPClient,513 })514 if err != nil {515 return nil, err516 }517 return result.(*PostRemoteAPIJTagFetchSystemTagsOK), nil518}519/*520PostRemoteAPIJTagFollowID post remote API j tag follow ID API521*/522func (a *Client) PostRemoteAPIJTagFollowID(params *PostRemoteAPIJTagFollowIDParams) (*PostRemoteAPIJTagFollowIDOK, error) {523 // TODO: Validate the params before sending524 if params == nil {525 params = NewPostRemoteAPIJTagFollowIDParams()526 }527 result, err := a.transport.Submit(&runtime.ClientOperation{528 ID: "PostRemoteAPIJTagFollowID",529 Method: "POST",530 PathPattern: "/remote.api/JTag.follow/{id}",531 ProducesMediaTypes: []string{""},532 ConsumesMediaTypes: []string{"application/json"},533 Schemes: []string{"http", "https"},534 Params: params,535 Reader: &PostRemoteAPIJTagFollowIDReader{formats: a.formats},536 Context: params.Context,537 Client: params.HTTPClient,538 })539 if err != nil {540 return nil, err541 }542 return result.(*PostRemoteAPIJTagFollowIDOK), nil543}544/*545PostRemoteAPIJTagModifyID post remote API j tag modify ID API546*/547func (a *Client) PostRemoteAPIJTagModifyID(params *PostRemoteAPIJTagModifyIDParams) (*PostRemoteAPIJTagModifyIDOK, error) {548 // TODO: Validate the params before sending549 if params == nil {550 params = NewPostRemoteAPIJTagModifyIDParams()551 }552 result, err := a.transport.Submit(&runtime.ClientOperation{553 ID: "PostRemoteAPIJTagModifyID",554 Method: "POST",555 PathPattern: "/remote.api/JTag.modify/{id}",556 ProducesMediaTypes: []string{""},557 ConsumesMediaTypes: []string{"application/json"},558 Schemes: []string{"http", "https"},559 Params: params,560 Reader: &PostRemoteAPIJTagModifyIDReader{formats: a.formats},561 Context: params.Context,562 Client: params.HTTPClient,563 })564 if err != nil {565 return nil, err566 }567 return result.(*PostRemoteAPIJTagModifyIDOK), nil568}569/*570PostRemoteAPIJTagOn post remote API j tag on API571*/572func (a *Client) PostRemoteAPIJTagOn(params *PostRemoteAPIJTagOnParams) (*PostRemoteAPIJTagOnOK, error) {573 // TODO: Validate the params before sending574 if params == nil {575 params = NewPostRemoteAPIJTagOnParams()576 }577 result, err := a.transport.Submit(&runtime.ClientOperation{578 ID: "PostRemoteAPIJTagOn",579 Method: "POST",580 PathPattern: "/remote.api/JTag.on",581 ProducesMediaTypes: []string{""},582 ConsumesMediaTypes: []string{"application/json"},583 Schemes: []string{"http", "https"},584 Params: params,585 Reader: &PostRemoteAPIJTagOnReader{formats: a.formats},586 Context: params.Context,587 Client: params.HTTPClient,588 })589 if err != nil {590 return nil, err591 }592 return result.(*PostRemoteAPIJTagOnOK), nil593}594/*595PostRemoteAPIJTagOne post remote API j tag one API596*/597func (a *Client) PostRemoteAPIJTagOne(params *PostRemoteAPIJTagOneParams) (*PostRemoteAPIJTagOneOK, error) {598 // TODO: Validate the params before sending599 if params == nil {600 params = NewPostRemoteAPIJTagOneParams()601 }602 result, err := a.transport.Submit(&runtime.ClientOperation{603 ID: "PostRemoteAPIJTagOne",604 Method: "POST",605 PathPattern: "/remote.api/JTag.one",606 ProducesMediaTypes: []string{""},607 ConsumesMediaTypes: []string{"application/json"},608 Schemes: []string{"http", "https"},609 Params: params,610 Reader: &PostRemoteAPIJTagOneReader{formats: a.formats},611 Context: params.Context,612 Client: params.HTTPClient,613 })614 if err != nil {615 return nil, err616 }617 return result.(*PostRemoteAPIJTagOneOK), nil618}619/*620PostRemoteAPIJTagSome post remote API j tag some API621*/622func (a *Client) PostRemoteAPIJTagSome(params *PostRemoteAPIJTagSomeParams) (*PostRemoteAPIJTagSomeOK, error) {623 // TODO: Validate the params before sending624 if params == nil {625 params = NewPostRemoteAPIJTagSomeParams()626 }627 result, err := a.transport.Submit(&runtime.ClientOperation{628 ID: "PostRemoteAPIJTagSome",629 Method: "POST",630 PathPattern: "/remote.api/JTag.some",631 ProducesMediaTypes: []string{""},632 ConsumesMediaTypes: []string{"application/json"},633 Schemes: []string{"http", "https"},634 Params: params,635 Reader: &PostRemoteAPIJTagSomeReader{formats: a.formats},636 Context: params.Context,637 Client: params.HTTPClient,638 })639 if err != nil {640 return nil, err641 }642 return result.(*PostRemoteAPIJTagSomeOK), nil643}644/*645PostRemoteAPIJTagUnfollowID post remote API j tag unfollow ID API646*/647func (a *Client) PostRemoteAPIJTagUnfollowID(params *PostRemoteAPIJTagUnfollowIDParams) (*PostRemoteAPIJTagUnfollowIDOK, error) {648 // TODO: Validate the params before sending649 if params == nil {650 params = NewPostRemoteAPIJTagUnfollowIDParams()651 }652 result, err := a.transport.Submit(&runtime.ClientOperation{653 ID: "PostRemoteAPIJTagUnfollowID",654 Method: "POST",655 PathPattern: "/remote.api/JTag.unfollow/{id}",656 ProducesMediaTypes: []string{""},657 ConsumesMediaTypes: []string{"application/json"},658 Schemes: []string{"http", "https"},659 Params: params,660 Reader: &PostRemoteAPIJTagUnfollowIDReader{formats: a.formats},661 Context: params.Context,662 Client: params.HTTPClient,663 })664 if err != nil {665 return nil, err666 }667 return result.(*PostRemoteAPIJTagUnfollowIDOK), nil668}669// SetTransport changes the transport on the client670func (a *Client) SetTransport(transport runtime.ClientTransport) {671 a.transport = transport672}...

Full Screen

Full Screen

j_workspace_client.go

Source:j_workspace_client.go Github

copy

Full Screen

...16 transport runtime.ClientTransport17 formats strfmt.Registry18}19/*20PostRemoteAPIJWorkspaceCreate post remote API j workspace create API21*/22func (a *Client) PostRemoteAPIJWorkspaceCreate(params *PostRemoteAPIJWorkspaceCreateParams) (*PostRemoteAPIJWorkspaceCreateOK, error) {23 // TODO: Validate the params before sending24 if params == nil {25 params = NewPostRemoteAPIJWorkspaceCreateParams()26 }27 result, err := a.transport.Submit(&runtime.ClientOperation{28 ID: "PostRemoteAPIJWorkspaceCreate",29 Method: "POST",30 PathPattern: "/remote.api/JWorkspace.create",31 ProducesMediaTypes: []string{""},32 ConsumesMediaTypes: []string{"application/json"},33 Schemes: []string{"http", "https"},34 Params: params,35 Reader: &PostRemoteAPIJWorkspaceCreateReader{formats: a.formats},36 Context: params.Context,37 Client: params.HTTPClient,38 })39 if err != nil {40 return nil, err41 }42 return result.(*PostRemoteAPIJWorkspaceCreateOK), nil43}44/*45PostRemoteAPIJWorkspaceCreateDefault post remote API j workspace create default API46*/47func (a *Client) PostRemoteAPIJWorkspaceCreateDefault(params *PostRemoteAPIJWorkspaceCreateDefaultParams) (*PostRemoteAPIJWorkspaceCreateDefaultOK, error) {48 // TODO: Validate the params before sending49 if params == nil {50 params = NewPostRemoteAPIJWorkspaceCreateDefaultParams()51 }52 result, err := a.transport.Submit(&runtime.ClientOperation{53 ID: "PostRemoteAPIJWorkspaceCreateDefault",54 Method: "POST",55 PathPattern: "/remote.api/JWorkspace.createDefault",56 ProducesMediaTypes: []string{""},57 ConsumesMediaTypes: []string{"application/json"},58 Schemes: []string{"http", "https"},59 Params: params,60 Reader: &PostRemoteAPIJWorkspaceCreateDefaultReader{formats: a.formats},61 Context: params.Context,62 Client: params.HTTPClient,63 })64 if err != nil {65 return nil, err66 }67 return result.(*PostRemoteAPIJWorkspaceCreateDefaultOK), nil68}69/*70PostRemoteAPIJWorkspaceDeleteByID post remote API j workspace delete by ID API71*/72func (a *Client) PostRemoteAPIJWorkspaceDeleteByID(params *PostRemoteAPIJWorkspaceDeleteByIDParams) (*PostRemoteAPIJWorkspaceDeleteByIDOK, error) {73 // TODO: Validate the params before sending74 if params == nil {75 params = NewPostRemoteAPIJWorkspaceDeleteByIDParams()76 }77 result, err := a.transport.Submit(&runtime.ClientOperation{78 ID: "PostRemoteAPIJWorkspaceDeleteByID",79 Method: "POST",80 PathPattern: "/remote.api/JWorkspace.deleteById",81 ProducesMediaTypes: []string{""},82 ConsumesMediaTypes: []string{"application/json"},83 Schemes: []string{"http", "https"},84 Params: params,85 Reader: &PostRemoteAPIJWorkspaceDeleteByIDReader{formats: a.formats},86 Context: params.Context,87 Client: params.HTTPClient,88 })89 if err != nil {90 return nil, err91 }92 return result.(*PostRemoteAPIJWorkspaceDeleteByIDOK), nil93}94/*95PostRemoteAPIJWorkspaceDeleteByUID post remote API j workspace delete by UID API96*/97func (a *Client) PostRemoteAPIJWorkspaceDeleteByUID(params *PostRemoteAPIJWorkspaceDeleteByUIDParams) (*PostRemoteAPIJWorkspaceDeleteByUIDOK, error) {98 // TODO: Validate the params before sending99 if params == nil {100 params = NewPostRemoteAPIJWorkspaceDeleteByUIDParams()101 }102 result, err := a.transport.Submit(&runtime.ClientOperation{103 ID: "PostRemoteAPIJWorkspaceDeleteByUID",104 Method: "POST",105 PathPattern: "/remote.api/JWorkspace.deleteByUid",106 ProducesMediaTypes: []string{""},107 ConsumesMediaTypes: []string{"application/json"},108 Schemes: []string{"http", "https"},109 Params: params,110 Reader: &PostRemoteAPIJWorkspaceDeleteByUIDReader{formats: a.formats},111 Context: params.Context,112 Client: params.HTTPClient,113 })114 if err != nil {115 return nil, err116 }117 return result.(*PostRemoteAPIJWorkspaceDeleteByUIDOK), nil118}119/*120PostRemoteAPIJWorkspaceDeleteID post remote API j workspace delete ID API121*/122func (a *Client) PostRemoteAPIJWorkspaceDeleteID(params *PostRemoteAPIJWorkspaceDeleteIDParams) (*PostRemoteAPIJWorkspaceDeleteIDOK, error) {123 // TODO: Validate the params before sending124 if params == nil {125 params = NewPostRemoteAPIJWorkspaceDeleteIDParams()126 }127 result, err := a.transport.Submit(&runtime.ClientOperation{128 ID: "PostRemoteAPIJWorkspaceDeleteID",129 Method: "POST",130 PathPattern: "/remote.api/JWorkspace.delete/{id}",131 ProducesMediaTypes: []string{""},132 ConsumesMediaTypes: []string{"application/json"},133 Schemes: []string{"http", "https"},134 Params: params,135 Reader: &PostRemoteAPIJWorkspaceDeleteIDReader{formats: a.formats},136 Context: params.Context,137 Client: params.HTTPClient,138 })139 if err != nil {140 return nil, err141 }142 return result.(*PostRemoteAPIJWorkspaceDeleteIDOK), nil143}144/*145PostRemoteAPIJWorkspaceFetchByMachines post remote API j workspace fetch by machines API146*/147func (a *Client) PostRemoteAPIJWorkspaceFetchByMachines(params *PostRemoteAPIJWorkspaceFetchByMachinesParams) (*PostRemoteAPIJWorkspaceFetchByMachinesOK, error) {148 // TODO: Validate the params before sending149 if params == nil {150 params = NewPostRemoteAPIJWorkspaceFetchByMachinesParams()151 }152 result, err := a.transport.Submit(&runtime.ClientOperation{153 ID: "PostRemoteAPIJWorkspaceFetchByMachines",154 Method: "POST",155 PathPattern: "/remote.api/JWorkspace.fetchByMachines",156 ProducesMediaTypes: []string{""},157 ConsumesMediaTypes: []string{"application/json"},158 Schemes: []string{"http", "https"},159 Params: params,160 Reader: &PostRemoteAPIJWorkspaceFetchByMachinesReader{formats: a.formats},161 Context: params.Context,162 Client: params.HTTPClient,163 })164 if err != nil {165 return nil, err166 }167 return result.(*PostRemoteAPIJWorkspaceFetchByMachinesOK), nil168}169/*170PostRemoteAPIJWorkspaceUpdate post remote API j workspace update API171*/172func (a *Client) PostRemoteAPIJWorkspaceUpdate(params *PostRemoteAPIJWorkspaceUpdateParams) (*PostRemoteAPIJWorkspaceUpdateOK, error) {173 // TODO: Validate the params before sending174 if params == nil {175 params = NewPostRemoteAPIJWorkspaceUpdateParams()176 }177 result, err := a.transport.Submit(&runtime.ClientOperation{178 ID: "PostRemoteAPIJWorkspaceUpdate",179 Method: "POST",180 PathPattern: "/remote.api/JWorkspace.update",181 ProducesMediaTypes: []string{""},182 ConsumesMediaTypes: []string{"application/json"},183 Schemes: []string{"http", "https"},184 Params: params,185 Reader: &PostRemoteAPIJWorkspaceUpdateReader{formats: a.formats},186 Context: params.Context,187 Client: params.HTTPClient,188 })189 if err != nil {190 return nil, err191 }192 return result.(*PostRemoteAPIJWorkspaceUpdateOK), nil193}194// SetTransport changes the transport on the client195func (a *Client) SetTransport(transport runtime.ClientTransport) {196 a.transport = transport197}...

Full Screen

Full Screen

Post

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 payload := strings.NewReader("Hello World")4 req, _ := http.NewRequest("POST", url, payload)5 req.Header.Add("content-type", "application/x-www-form-urlencoded")6 req.Header.Add("cache-control", "no-cache")7 res, _ := http.DefaultClient.Do(req)8 defer res.Body.Close()9 body, _ := ioutil.ReadAll(res.Body)10 fmt.Println(res)11 fmt.Println(string(body))12}

Full Screen

Full Screen

Post

Using AI Code Generation

copy

Full Screen

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, strings.NewReader(string(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, 18 May 2017 06:48:22 GMT] Content-Length:[48]]20response Body: {"id":1,"title":"Buy cheese and bread for breakfast."}21import (22func main() {23 fmt.Println("URL:>", url)24 var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`)25 req, err := http.NewRequest("POST", url, strings.NewReader(string(jsonStr)))26 req.Header.Set("X-Custom-Header", "myvalue")27 req.Header.Set("Content-Type", "application/json")28 client := &http.Client{}

Full Screen

Full Screen

Post

Using AI Code Generation

copy

Full Screen

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:[text/plain; charset=utf-8] Date:[Thu, 11 Jul 2019 11:53:28 GMT] Content-Length:[34]]20response Body: {"title":"Buy cheese and bread for breakfast."}21import (22func main() {23 fmt.Println("URL:>", url)24 var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`)25 req, err := http.NewRequest("PUT", url, bytes.NewBuffer(jsonStr))26 req.Header.Set("X-Custom-Header", "myvalue")27 req.Header.Set("Content-Type", "application/json")28 client := &http.Client{}29 resp, err := client.Do(req)30 if err != nil {31 panic(err)32 }33 defer resp.Body.Close()34 fmt.Println("response Status:", resp.Status)35 fmt.Println("response Headers:", resp.Header)36 body, _ := ioutil.ReadAll(resp.Body)37 fmt.Println("response Body:", string(body))38}39response Headers: map[Content-Type:[text/plain; charset=utf-8] Date:[Thu, 11 Jul 2019 11:54:15 GMT] Content-Length:[34]]40response Body: {"title":"Buy cheese and bread for breakfast."}

Full Screen

Full Screen

Post

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 data := map[string]string{"name": "John", "age": "30"}4 jsonValue, _ := json.Marshal(data)5 response, err := http.Post(url, "application/json", bytes.NewBuffer(jsonValue))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 }12}13{"success":true}14import (15func main() {16 response, err := http.Get(url)17 if err != nil {18 fmt.Printf("The HTTP request failed with error %s19 } else {20 data, _ := ioutil.ReadAll(response.Body)21 fmt.Println(string(data))22 }23}24{"success":true}25import (26func main() {27 data := map[string]string{"name": "John", "age": "30"}28 jsonValue, _ := json.Marshal(data)29 response, err := http.Put(url, "application/json", bytes.NewBuffer(jsonValue))30 if err != nil {31 fmt.Printf("The HTTP request failed with error %s32 } else {33 data, _ := ioutil.ReadAll(response.Body)34 fmt.Println(string(data))35 }36}37{"success":true}38import (39func main() {40 request, err := http.NewRequest("DELETE", url, nil)41 if err != nil {

Full Screen

Full Screen

Post

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := &http.Client{}4 if err != nil {5 fmt.Println(err)6 }7 response, err := client.Do(request)8 if err != nil {9 fmt.Println(err)10 }11 defer response.Body.Close()12 responseData, err := ioutil.ReadAll(response.Body)13 if err != nil {14 fmt.Println(err)15 }16 fmt.Println(string(responseData))17}

Full Screen

Full Screen

Post

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := &http.Client{}4 if err != nil {5 fmt.Println(err)6 }7 form := url.Values{}8 form.Add("name", "Sakshi")9 form.Add("age", "22")10 response, err := client.Do(request)11 if err != nil {12 fmt.Println(err)13 }14 defer response.Body.Close()15 data, err := ioutil.ReadAll(response.Body)16 if err != nil {17 fmt.Println(err)18 }19 fmt.Println(string(data))20}

Full Screen

Full Screen

Automation Testing Tutorials

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

LambdaTest Learning Hubs:

YouTube

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

Run Testkube automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful