github.com/turgay/mattermost-server@v5.3.2-0.20181002173352-2945e8a2b0ce+incompatible/api4/apitestlib.go (about) 1 // Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved. 2 // See License.txt for license information. 3 4 package api4 5 6 import ( 7 "bytes" 8 "fmt" 9 "io" 10 "io/ioutil" 11 "net" 12 "net/http" 13 "os" 14 "path/filepath" 15 "reflect" 16 "strconv" 17 "strings" 18 "sync" 19 "testing" 20 "time" 21 22 "github.com/mattermost/mattermost-server/app" 23 "github.com/mattermost/mattermost-server/mlog" 24 "github.com/mattermost/mattermost-server/model" 25 "github.com/mattermost/mattermost-server/store" 26 "github.com/mattermost/mattermost-server/store/sqlstore" 27 "github.com/mattermost/mattermost-server/store/storetest" 28 "github.com/mattermost/mattermost-server/utils" 29 "github.com/mattermost/mattermost-server/web" 30 "github.com/mattermost/mattermost-server/wsapi" 31 32 s3 "github.com/minio/minio-go" 33 "github.com/minio/minio-go/pkg/credentials" 34 ) 35 36 type TestHelper struct { 37 App *app.App 38 tempConfigPath string 39 40 Client *model.Client4 41 BasicUser *model.User 42 BasicUser2 *model.User 43 TeamAdminUser *model.User 44 BasicTeam *model.Team 45 BasicChannel *model.Channel 46 BasicPrivateChannel *model.Channel 47 BasicDeletedChannel *model.Channel 48 BasicChannel2 *model.Channel 49 BasicPost *model.Post 50 51 SystemAdminClient *model.Client4 52 SystemAdminUser *model.User 53 tempWorkspace string 54 } 55 56 type persistentTestStore struct { 57 store.Store 58 } 59 60 func (*persistentTestStore) Close() {} 61 62 var testStoreContainer *storetest.RunningContainer 63 var testStore *persistentTestStore 64 65 // UseTestStore sets the container and corresponding settings to use for tests. Once the tests are 66 // complete (e.g. at the end of your TestMain implementation), you should call StopTestStore. 67 func UseTestStore(container *storetest.RunningContainer, settings *model.SqlSettings) { 68 testStoreContainer = container 69 testStore = &persistentTestStore{store.NewLayeredStore(sqlstore.NewSqlSupplier(*settings, nil), nil, nil)} 70 } 71 72 func StopTestStore() { 73 if testStoreContainer != nil { 74 testStoreContainer.Stop() 75 testStoreContainer = nil 76 } 77 } 78 79 func setupTestHelper(enterprise bool, updateConfig func(*model.Config)) *TestHelper { 80 permConfig, err := os.Open(utils.FindConfigFile("config.json")) 81 if err != nil { 82 panic(err) 83 } 84 defer permConfig.Close() 85 tempConfig, err := ioutil.TempFile("", "") 86 if err != nil { 87 panic(err) 88 } 89 _, err = io.Copy(tempConfig, permConfig) 90 tempConfig.Close() 91 if err != nil { 92 panic(err) 93 } 94 95 options := []app.Option{app.ConfigFile(tempConfig.Name()), app.DisableConfigWatch} 96 if testStore != nil { 97 options = append(options, app.StoreOverride(testStore)) 98 } 99 100 a, err := app.New(options...) 101 if err != nil { 102 panic(err) 103 } 104 105 th := &TestHelper{ 106 App: a, 107 tempConfigPath: tempConfig.Name(), 108 } 109 110 th.App.UpdateConfig(func(cfg *model.Config) { 111 *cfg.TeamSettings.MaxUsersPerTeam = 50 112 *cfg.RateLimitSettings.Enable = false 113 cfg.EmailSettings.SendEmailNotifications = true 114 }) 115 prevListenAddress := *th.App.Config().ServiceSettings.ListenAddress 116 if testStore != nil { 117 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = ":0" }) 118 } 119 if updateConfig != nil { 120 th.App.UpdateConfig(updateConfig) 121 } 122 serverErr := th.App.StartServer() 123 if serverErr != nil { 124 panic(serverErr) 125 } 126 127 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = prevListenAddress }) 128 Init(th.App, th.App.Srv.Router) 129 web.NewWeb(th.App, th.App.Srv.Router) 130 wsapi.Init(th.App, th.App.Srv.WebSocketRouter) 131 th.App.Srv.Store.MarkSystemRanUnitTests() 132 th.App.DoAdvancedPermissionsMigration() 133 th.App.DoEmojisPermissionsMigration() 134 135 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true }) 136 137 if enterprise { 138 th.App.SetLicense(model.NewTestLicense()) 139 } else { 140 th.App.SetLicense(nil) 141 } 142 143 th.Client = th.CreateClient() 144 th.SystemAdminClient = th.CreateClient() 145 146 if th.tempWorkspace == "" { 147 dir, err := ioutil.TempDir("", "apptest") 148 if err != nil { 149 panic(err) 150 } 151 th.tempWorkspace = dir 152 } 153 154 pluginDir := filepath.Join(th.tempWorkspace, "plugins") 155 webappDir := filepath.Join(th.tempWorkspace, "webapp") 156 157 th.App.UpdateConfig(func(cfg *model.Config) { 158 *cfg.PluginSettings.Directory = pluginDir 159 *cfg.PluginSettings.ClientDirectory = webappDir 160 }) 161 162 th.App.InitPlugins(pluginDir, webappDir) 163 164 return th 165 } 166 167 func SetupEnterprise() *TestHelper { 168 return setupTestHelper(true, nil) 169 } 170 171 func Setup() *TestHelper { 172 return setupTestHelper(false, nil) 173 } 174 175 func SetupConfig(updateConfig func(cfg *model.Config)) *TestHelper { 176 return setupTestHelper(false, updateConfig) 177 } 178 179 func (me *TestHelper) TearDown() { 180 utils.DisableDebugLogForTest() 181 182 var wg sync.WaitGroup 183 wg.Add(3) 184 185 go func() { 186 defer wg.Done() 187 options := map[string]bool{} 188 options[store.USER_SEARCH_OPTION_NAMES_ONLY_NO_FULL_NAME] = true 189 if result := <-me.App.Srv.Store.User().Search("", "fakeuser", options); result.Err != nil { 190 mlog.Error("Error tearing down test users") 191 } else { 192 users := result.Data.([]*model.User) 193 194 for _, u := range users { 195 if err := me.App.PermanentDeleteUser(u); err != nil { 196 mlog.Error(err.Error()) 197 } 198 } 199 } 200 }() 201 202 go func() { 203 defer wg.Done() 204 if result := <-me.App.Srv.Store.Team().SearchByName("faketeam"); result.Err != nil { 205 mlog.Error("Error tearing down test teams") 206 } else { 207 teams := result.Data.([]*model.Team) 208 209 for _, t := range teams { 210 if err := me.App.PermanentDeleteTeam(t); err != nil { 211 mlog.Error(err.Error()) 212 } 213 } 214 } 215 }() 216 217 go func() { 218 defer wg.Done() 219 if result := <-me.App.Srv.Store.OAuth().GetApps(0, 1000); result.Err != nil { 220 mlog.Error("Error tearing down test oauth apps") 221 } else { 222 apps := result.Data.([]*model.OAuthApp) 223 224 for _, a := range apps { 225 if strings.HasPrefix(a.Name, "fakeoauthapp") { 226 <-me.App.Srv.Store.OAuth().DeleteApp(a.Id) 227 } 228 } 229 } 230 }() 231 232 wg.Wait() 233 234 me.App.Shutdown() 235 os.Remove(me.tempConfigPath) 236 237 utils.EnableDebugLogForTest() 238 239 if err := recover(); err != nil { 240 StopTestStore() 241 panic(err) 242 } 243 } 244 245 func (me *TestHelper) InitBasic() *TestHelper { 246 me.waitForConnectivity() 247 248 me.TeamAdminUser = me.CreateUser() 249 me.App.UpdateUserRoles(me.TeamAdminUser.Id, model.SYSTEM_USER_ROLE_ID, false) 250 me.LoginTeamAdmin() 251 me.BasicTeam = me.CreateTeam() 252 me.BasicChannel = me.CreatePublicChannel() 253 me.BasicPrivateChannel = me.CreatePrivateChannel() 254 me.BasicDeletedChannel = me.CreatePublicChannel() 255 me.BasicChannel2 = me.CreatePublicChannel() 256 me.BasicPost = me.CreatePost() 257 me.BasicUser = me.CreateUser() 258 me.LinkUserToTeam(me.BasicUser, me.BasicTeam) 259 me.BasicUser2 = me.CreateUser() 260 me.LinkUserToTeam(me.BasicUser2, me.BasicTeam) 261 me.App.AddUserToChannel(me.BasicUser, me.BasicChannel) 262 me.App.AddUserToChannel(me.BasicUser2, me.BasicChannel) 263 me.App.AddUserToChannel(me.BasicUser, me.BasicChannel2) 264 me.App.AddUserToChannel(me.BasicUser2, me.BasicChannel2) 265 me.App.AddUserToChannel(me.BasicUser, me.BasicPrivateChannel) 266 me.App.AddUserToChannel(me.BasicUser2, me.BasicPrivateChannel) 267 me.App.AddUserToChannel(me.BasicUser, me.BasicDeletedChannel) 268 me.App.AddUserToChannel(me.BasicUser2, me.BasicDeletedChannel) 269 me.App.UpdateUserRoles(me.BasicUser.Id, model.SYSTEM_USER_ROLE_ID, false) 270 me.Client.DeleteChannel(me.BasicDeletedChannel.Id) 271 me.LoginBasic() 272 273 return me 274 } 275 276 func (me *TestHelper) InitSystemAdmin() *TestHelper { 277 me.waitForConnectivity() 278 279 me.SystemAdminUser = me.CreateUser() 280 me.App.UpdateUserRoles(me.SystemAdminUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID, false) 281 me.LoginSystemAdmin() 282 283 return me 284 } 285 286 func (me *TestHelper) waitForConnectivity() { 287 for i := 0; i < 1000; i++ { 288 conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%v", me.App.Srv.ListenAddr.Port)) 289 if err == nil { 290 conn.Close() 291 return 292 } 293 time.Sleep(time.Millisecond * 20) 294 } 295 panic("unable to connect") 296 } 297 298 func (me *TestHelper) CreateClient() *model.Client4 { 299 return model.NewAPIv4Client(fmt.Sprintf("http://localhost:%v", me.App.Srv.ListenAddr.Port)) 300 } 301 302 func (me *TestHelper) CreateWebSocketClient() (*model.WebSocketClient, *model.AppError) { 303 return model.NewWebSocketClient4(fmt.Sprintf("ws://localhost:%v", me.App.Srv.ListenAddr.Port), me.Client.AuthToken) 304 } 305 306 func (me *TestHelper) CreateWebSocketSystemAdminClient() (*model.WebSocketClient, *model.AppError) { 307 return model.NewWebSocketClient4(fmt.Sprintf("ws://localhost:%v", me.App.Srv.ListenAddr.Port), me.SystemAdminClient.AuthToken) 308 } 309 310 func (me *TestHelper) CreateUser() *model.User { 311 return me.CreateUserWithClient(me.Client) 312 } 313 314 func (me *TestHelper) CreateTeam() *model.Team { 315 return me.CreateTeamWithClient(me.Client) 316 } 317 318 func (me *TestHelper) CreateTeamWithClient(client *model.Client4) *model.Team { 319 id := model.NewId() 320 team := &model.Team{ 321 DisplayName: "dn_" + id, 322 Name: GenerateTestTeamName(), 323 Email: me.GenerateTestEmail(), 324 Type: model.TEAM_OPEN, 325 } 326 327 utils.DisableDebugLogForTest() 328 rteam, _ := client.CreateTeam(team) 329 utils.EnableDebugLogForTest() 330 return rteam 331 } 332 333 func (me *TestHelper) CreateUserWithClient(client *model.Client4) *model.User { 334 id := model.NewId() 335 336 user := &model.User{ 337 Email: me.GenerateTestEmail(), 338 Username: GenerateTestUsername(), 339 Nickname: "nn_" + id, 340 FirstName: "f_" + id, 341 LastName: "l_" + id, 342 Password: "Password1", 343 } 344 345 utils.DisableDebugLogForTest() 346 ruser, response := client.CreateUser(user) 347 if response.Error != nil { 348 panic(response.Error) 349 } 350 351 ruser.Password = "Password1" 352 store.Must(me.App.Srv.Store.User().VerifyEmail(ruser.Id)) 353 utils.EnableDebugLogForTest() 354 return ruser 355 } 356 357 func (me *TestHelper) CreatePublicChannel() *model.Channel { 358 return me.CreateChannelWithClient(me.Client, model.CHANNEL_OPEN) 359 } 360 361 func (me *TestHelper) CreatePrivateChannel() *model.Channel { 362 return me.CreateChannelWithClient(me.Client, model.CHANNEL_PRIVATE) 363 } 364 365 func (me *TestHelper) CreateChannelWithClient(client *model.Client4, channelType string) *model.Channel { 366 return me.CreateChannelWithClientAndTeam(client, channelType, me.BasicTeam.Id) 367 } 368 369 func (me *TestHelper) CreateChannelWithClientAndTeam(client *model.Client4, channelType string, teamId string) *model.Channel { 370 id := model.NewId() 371 372 channel := &model.Channel{ 373 DisplayName: "dn_" + id, 374 Name: GenerateTestChannelName(), 375 Type: channelType, 376 TeamId: teamId, 377 } 378 379 utils.DisableDebugLogForTest() 380 rchannel, _ := client.CreateChannel(channel) 381 utils.EnableDebugLogForTest() 382 return rchannel 383 } 384 385 func (me *TestHelper) CreatePost() *model.Post { 386 return me.CreatePostWithClient(me.Client, me.BasicChannel) 387 } 388 389 func (me *TestHelper) CreatePinnedPost() *model.Post { 390 return me.CreatePinnedPostWithClient(me.Client, me.BasicChannel) 391 } 392 393 func (me *TestHelper) CreateMessagePost(message string) *model.Post { 394 return me.CreateMessagePostWithClient(me.Client, me.BasicChannel, message) 395 } 396 397 func (me *TestHelper) CreatePostWithClient(client *model.Client4, channel *model.Channel) *model.Post { 398 id := model.NewId() 399 400 post := &model.Post{ 401 ChannelId: channel.Id, 402 Message: "message_" + id, 403 } 404 405 utils.DisableDebugLogForTest() 406 rpost, resp := client.CreatePost(post) 407 if resp.Error != nil { 408 panic(resp.Error) 409 } 410 utils.EnableDebugLogForTest() 411 return rpost 412 } 413 414 func (me *TestHelper) CreatePinnedPostWithClient(client *model.Client4, channel *model.Channel) *model.Post { 415 id := model.NewId() 416 417 post := &model.Post{ 418 ChannelId: channel.Id, 419 Message: "message_" + id, 420 IsPinned: true, 421 } 422 423 utils.DisableDebugLogForTest() 424 rpost, resp := client.CreatePost(post) 425 if resp.Error != nil { 426 panic(resp.Error) 427 } 428 utils.EnableDebugLogForTest() 429 return rpost 430 } 431 432 func (me *TestHelper) CreateMessagePostWithClient(client *model.Client4, channel *model.Channel, message string) *model.Post { 433 post := &model.Post{ 434 ChannelId: channel.Id, 435 Message: message, 436 } 437 438 utils.DisableDebugLogForTest() 439 rpost, resp := client.CreatePost(post) 440 if resp.Error != nil { 441 panic(resp.Error) 442 } 443 utils.EnableDebugLogForTest() 444 return rpost 445 } 446 447 func (me *TestHelper) CreateMessagePostNoClient(channel *model.Channel, message string, createAtTime int64) *model.Post { 448 post := store.Must(me.App.Srv.Store.Post().Save(&model.Post{ 449 UserId: me.BasicUser.Id, 450 ChannelId: channel.Id, 451 Message: message, 452 CreateAt: createAtTime, 453 })).(*model.Post) 454 455 return post 456 } 457 458 func (me *TestHelper) CreateDmChannel(user *model.User) *model.Channel { 459 utils.DisableDebugLogForTest() 460 var err *model.AppError 461 var channel *model.Channel 462 if channel, err = me.App.CreateDirectChannel(me.BasicUser.Id, user.Id); err != nil { 463 mlog.Error(err.Error()) 464 465 time.Sleep(time.Second) 466 panic(err) 467 } 468 utils.EnableDebugLogForTest() 469 return channel 470 } 471 472 func (me *TestHelper) LoginBasic() { 473 me.LoginBasicWithClient(me.Client) 474 } 475 476 func (me *TestHelper) LoginBasic2() { 477 me.LoginBasic2WithClient(me.Client) 478 } 479 480 func (me *TestHelper) LoginTeamAdmin() { 481 me.LoginTeamAdminWithClient(me.Client) 482 } 483 484 func (me *TestHelper) LoginSystemAdmin() { 485 me.LoginSystemAdminWithClient(me.SystemAdminClient) 486 } 487 488 func (me *TestHelper) LoginBasicWithClient(client *model.Client4) { 489 utils.DisableDebugLogForTest() 490 client.Login(me.BasicUser.Email, me.BasicUser.Password) 491 utils.EnableDebugLogForTest() 492 } 493 494 func (me *TestHelper) LoginBasic2WithClient(client *model.Client4) { 495 utils.DisableDebugLogForTest() 496 client.Login(me.BasicUser2.Email, me.BasicUser2.Password) 497 utils.EnableDebugLogForTest() 498 } 499 500 func (me *TestHelper) LoginTeamAdminWithClient(client *model.Client4) { 501 utils.DisableDebugLogForTest() 502 client.Login(me.TeamAdminUser.Email, me.TeamAdminUser.Password) 503 utils.EnableDebugLogForTest() 504 } 505 506 func (me *TestHelper) LoginSystemAdminWithClient(client *model.Client4) { 507 utils.DisableDebugLogForTest() 508 client.Login(me.SystemAdminUser.Email, me.SystemAdminUser.Password) 509 utils.EnableDebugLogForTest() 510 } 511 512 func (me *TestHelper) UpdateActiveUser(user *model.User, active bool) { 513 utils.DisableDebugLogForTest() 514 515 _, err := me.App.UpdateActive(user, active) 516 if err != nil { 517 mlog.Error(err.Error()) 518 519 time.Sleep(time.Second) 520 panic(err) 521 } 522 523 utils.EnableDebugLogForTest() 524 } 525 526 func (me *TestHelper) LinkUserToTeam(user *model.User, team *model.Team) { 527 utils.DisableDebugLogForTest() 528 529 err := me.App.JoinUserToTeam(team, user, "") 530 if err != nil { 531 mlog.Error(err.Error()) 532 533 time.Sleep(time.Second) 534 panic(err) 535 } 536 537 utils.EnableDebugLogForTest() 538 } 539 540 func (me *TestHelper) AddUserToChannel(user *model.User, channel *model.Channel) *model.ChannelMember { 541 utils.DisableDebugLogForTest() 542 543 member, err := me.App.AddUserToChannel(user, channel) 544 if err != nil { 545 mlog.Error(err.Error()) 546 547 time.Sleep(time.Second) 548 panic(err) 549 } 550 551 utils.EnableDebugLogForTest() 552 553 return member 554 } 555 556 func (me *TestHelper) GenerateTestEmail() string { 557 if me.App.Config().EmailSettings.SMTPServer != "dockerhost" && os.Getenv("CI_INBUCKET_PORT") == "" { 558 return strings.ToLower("success+" + model.NewId() + "@simulator.amazonses.com") 559 } 560 return strings.ToLower(model.NewId() + "@dockerhost") 561 } 562 563 func GenerateTestUsername() string { 564 return "fakeuser" + model.NewRandomString(10) 565 } 566 567 func GenerateTestTeamName() string { 568 return "faketeam" + model.NewRandomString(6) 569 } 570 571 func GenerateTestChannelName() string { 572 return "fakechannel" + model.NewRandomString(10) 573 } 574 575 func GenerateTestAppName() string { 576 return "fakeoauthapp" + model.NewRandomString(10) 577 } 578 579 func GenerateTestId() string { 580 return model.NewId() 581 } 582 583 func CheckUserSanitization(t *testing.T, user *model.User) { 584 t.Helper() 585 586 if user.Password != "" { 587 t.Fatal("password wasn't blank") 588 } 589 590 if user.AuthData != nil && *user.AuthData != "" { 591 t.Fatal("auth data wasn't blank") 592 } 593 594 if user.MfaSecret != "" { 595 t.Fatal("mfa secret wasn't blank") 596 } 597 } 598 599 func CheckEtag(t *testing.T, data interface{}, resp *model.Response) { 600 t.Helper() 601 602 if !reflect.ValueOf(data).IsNil() { 603 t.Fatal("etag data was not nil") 604 } 605 606 if resp.StatusCode != http.StatusNotModified { 607 t.Log("actual: " + strconv.Itoa(resp.StatusCode)) 608 t.Log("expected: " + strconv.Itoa(http.StatusNotModified)) 609 t.Fatal("wrong status code for etag") 610 } 611 } 612 613 func CheckNoError(t *testing.T, resp *model.Response) { 614 t.Helper() 615 616 if resp.Error != nil { 617 t.Fatal("Expected no error, got " + resp.Error.Error()) 618 } 619 } 620 621 func CheckCreatedStatus(t *testing.T, resp *model.Response) { 622 t.Helper() 623 624 if resp.StatusCode != http.StatusCreated { 625 t.Log("actual: " + strconv.Itoa(resp.StatusCode)) 626 t.Log("expected: " + strconv.Itoa(http.StatusCreated)) 627 t.Fatal("wrong status code") 628 } 629 } 630 631 func CheckForbiddenStatus(t *testing.T, resp *model.Response) { 632 t.Helper() 633 634 if resp.Error == nil { 635 t.Fatal("should have errored with status:" + strconv.Itoa(http.StatusForbidden)) 636 return 637 } 638 639 if resp.StatusCode != http.StatusForbidden { 640 t.Log("actual: " + strconv.Itoa(resp.StatusCode)) 641 t.Log("expected: " + strconv.Itoa(http.StatusForbidden)) 642 t.Fatal("wrong status code") 643 } 644 } 645 646 func CheckUnauthorizedStatus(t *testing.T, resp *model.Response) { 647 t.Helper() 648 649 if resp.Error == nil { 650 t.Fatal("should have errored with status:" + strconv.Itoa(http.StatusUnauthorized)) 651 return 652 } 653 654 if resp.StatusCode != http.StatusUnauthorized { 655 t.Log("actual: " + strconv.Itoa(resp.StatusCode)) 656 t.Log("expected: " + strconv.Itoa(http.StatusUnauthorized)) 657 t.Fatal("wrong status code") 658 } 659 } 660 661 func CheckNotFoundStatus(t *testing.T, resp *model.Response) { 662 t.Helper() 663 664 if resp.Error == nil { 665 t.Fatal("should have errored with status:" + strconv.Itoa(http.StatusNotFound)) 666 return 667 } 668 669 if resp.StatusCode != http.StatusNotFound { 670 t.Log("actual: " + strconv.Itoa(resp.StatusCode)) 671 t.Log("expected: " + strconv.Itoa(http.StatusNotFound)) 672 t.Fatal("wrong status code") 673 } 674 } 675 676 func CheckBadRequestStatus(t *testing.T, resp *model.Response) { 677 t.Helper() 678 679 if resp.Error == nil { 680 t.Fatal("should have errored with status:" + strconv.Itoa(http.StatusBadRequest)) 681 return 682 } 683 684 if resp.StatusCode != http.StatusBadRequest { 685 t.Log("actual: " + strconv.Itoa(resp.StatusCode)) 686 t.Log("expected: " + strconv.Itoa(http.StatusBadRequest)) 687 t.Fatal("wrong status code") 688 } 689 } 690 691 func CheckNotImplementedStatus(t *testing.T, resp *model.Response) { 692 t.Helper() 693 694 if resp.Error == nil { 695 t.Fatal("should have errored with status:" + strconv.Itoa(http.StatusNotImplemented)) 696 return 697 } 698 699 if resp.StatusCode != http.StatusNotImplemented { 700 t.Log("actual: " + strconv.Itoa(resp.StatusCode)) 701 t.Log("expected: " + strconv.Itoa(http.StatusNotImplemented)) 702 t.Fatal("wrong status code") 703 } 704 } 705 706 func CheckOKStatus(t *testing.T, resp *model.Response) { 707 t.Helper() 708 709 CheckNoError(t, resp) 710 711 if resp.StatusCode != http.StatusOK { 712 t.Fatalf("wrong status code. expected %d got %d", http.StatusOK, resp.StatusCode) 713 } 714 } 715 716 func CheckErrorMessage(t *testing.T, resp *model.Response, errorId string) { 717 t.Helper() 718 719 if resp.Error == nil { 720 t.Fatal("should have errored with message:" + errorId) 721 return 722 } 723 724 if resp.Error.Id != errorId { 725 t.Log("actual: " + resp.Error.Id) 726 t.Log("expected: " + errorId) 727 t.Fatal("incorrect error message") 728 } 729 } 730 731 func CheckInternalErrorStatus(t *testing.T, resp *model.Response) { 732 t.Helper() 733 734 if resp.Error == nil { 735 t.Fatal("should have errored with status:" + strconv.Itoa(http.StatusInternalServerError)) 736 return 737 } 738 739 if resp.StatusCode != http.StatusInternalServerError { 740 t.Log("actual: " + strconv.Itoa(resp.StatusCode)) 741 t.Log("expected: " + strconv.Itoa(http.StatusInternalServerError)) 742 t.Fatal("wrong status code") 743 } 744 } 745 746 func readTestFile(name string) ([]byte, error) { 747 path, _ := utils.FindDir("tests") 748 file, err := os.Open(filepath.Join(path, name)) 749 if err != nil { 750 return nil, err 751 } 752 defer file.Close() 753 754 data := &bytes.Buffer{} 755 if _, err := io.Copy(data, file); err != nil { 756 return nil, err 757 } else { 758 return data.Bytes(), nil 759 } 760 } 761 762 // Similar to s3.New() but allows initialization of signature v2 or signature v4 client. 763 // If signV2 input is false, function always returns signature v4. 764 // 765 // Additionally this function also takes a user defined region, if set 766 // disables automatic region lookup. 767 func s3New(endpoint, accessKey, secretKey string, secure bool, signV2 bool, region string) (*s3.Client, error) { 768 var creds *credentials.Credentials 769 if signV2 { 770 creds = credentials.NewStatic(accessKey, secretKey, "", credentials.SignatureV2) 771 } else { 772 creds = credentials.NewStatic(accessKey, secretKey, "", credentials.SignatureV4) 773 } 774 return s3.NewWithCredentials(endpoint, creds, secure, region) 775 } 776 777 func (me *TestHelper) cleanupTestFile(info *model.FileInfo) error { 778 cfg := me.App.Config() 779 if *cfg.FileSettings.DriverName == model.IMAGE_DRIVER_S3 { 780 endpoint := cfg.FileSettings.AmazonS3Endpoint 781 accessKey := cfg.FileSettings.AmazonS3AccessKeyId 782 secretKey := cfg.FileSettings.AmazonS3SecretAccessKey 783 secure := *cfg.FileSettings.AmazonS3SSL 784 signV2 := *cfg.FileSettings.AmazonS3SignV2 785 region := cfg.FileSettings.AmazonS3Region 786 s3Clnt, err := s3New(endpoint, accessKey, secretKey, secure, signV2, region) 787 if err != nil { 788 return err 789 } 790 bucket := cfg.FileSettings.AmazonS3Bucket 791 if err := s3Clnt.RemoveObject(bucket, info.Path); err != nil { 792 return err 793 } 794 795 if info.ThumbnailPath != "" { 796 if err := s3Clnt.RemoveObject(bucket, info.ThumbnailPath); err != nil { 797 return err 798 } 799 } 800 801 if info.PreviewPath != "" { 802 if err := s3Clnt.RemoveObject(bucket, info.PreviewPath); err != nil { 803 return err 804 } 805 } 806 } else if *cfg.FileSettings.DriverName == model.IMAGE_DRIVER_LOCAL { 807 if err := os.Remove(cfg.FileSettings.Directory + info.Path); err != nil { 808 return err 809 } 810 811 if info.ThumbnailPath != "" { 812 if err := os.Remove(cfg.FileSettings.Directory + info.ThumbnailPath); err != nil { 813 return err 814 } 815 } 816 817 if info.PreviewPath != "" { 818 if err := os.Remove(cfg.FileSettings.Directory + info.PreviewPath); err != nil { 819 return err 820 } 821 } 822 } 823 824 return nil 825 } 826 827 func (me *TestHelper) MakeUserChannelAdmin(user *model.User, channel *model.Channel) { 828 utils.DisableDebugLogForTest() 829 830 if cmr := <-me.App.Srv.Store.Channel().GetMember(channel.Id, user.Id); cmr.Err == nil { 831 cm := cmr.Data.(*model.ChannelMember) 832 cm.SchemeAdmin = true 833 if sr := <-me.App.Srv.Store.Channel().UpdateMember(cm); sr.Err != nil { 834 utils.EnableDebugLogForTest() 835 panic(sr.Err) 836 } 837 } else { 838 utils.EnableDebugLogForTest() 839 panic(cmr.Err) 840 } 841 842 utils.EnableDebugLogForTest() 843 } 844 845 func (me *TestHelper) UpdateUserToTeamAdmin(user *model.User, team *model.Team) { 846 utils.DisableDebugLogForTest() 847 848 if tmr := <-me.App.Srv.Store.Team().GetMember(team.Id, user.Id); tmr.Err == nil { 849 tm := tmr.Data.(*model.TeamMember) 850 tm.SchemeAdmin = true 851 if sr := <-me.App.Srv.Store.Team().UpdateMember(tm); sr.Err != nil { 852 utils.EnableDebugLogForTest() 853 panic(sr.Err) 854 } 855 } else { 856 utils.EnableDebugLogForTest() 857 mlog.Error(tmr.Err.Error()) 858 859 time.Sleep(time.Second) 860 panic(tmr.Err) 861 } 862 863 utils.EnableDebugLogForTest() 864 } 865 866 func (me *TestHelper) UpdateUserToNonTeamAdmin(user *model.User, team *model.Team) { 867 utils.DisableDebugLogForTest() 868 869 if tmr := <-me.App.Srv.Store.Team().GetMember(team.Id, user.Id); tmr.Err == nil { 870 tm := tmr.Data.(*model.TeamMember) 871 tm.SchemeAdmin = false 872 if sr := <-me.App.Srv.Store.Team().UpdateMember(tm); sr.Err != nil { 873 utils.EnableDebugLogForTest() 874 panic(sr.Err) 875 } 876 } else { 877 utils.EnableDebugLogForTest() 878 mlog.Error(tmr.Err.Error()) 879 880 time.Sleep(time.Second) 881 panic(tmr.Err) 882 } 883 884 utils.EnableDebugLogForTest() 885 } 886 887 func (me *TestHelper) SaveDefaultRolePermissions() map[string][]string { 888 utils.DisableDebugLogForTest() 889 890 results := make(map[string][]string) 891 892 for _, roleName := range []string{ 893 "system_user", 894 "system_admin", 895 "team_user", 896 "team_admin", 897 "channel_user", 898 "channel_admin", 899 } { 900 role, err1 := me.App.GetRoleByName(roleName) 901 if err1 != nil { 902 utils.EnableDebugLogForTest() 903 panic(err1) 904 } 905 906 results[roleName] = role.Permissions 907 } 908 909 utils.EnableDebugLogForTest() 910 return results 911 } 912 913 func (me *TestHelper) RestoreDefaultRolePermissions(data map[string][]string) { 914 utils.DisableDebugLogForTest() 915 916 for roleName, permissions := range data { 917 role, err1 := me.App.GetRoleByName(roleName) 918 if err1 != nil { 919 utils.EnableDebugLogForTest() 920 panic(err1) 921 } 922 923 if strings.Join(role.Permissions, " ") == strings.Join(permissions, " ") { 924 continue 925 } 926 927 role.Permissions = permissions 928 929 _, err2 := me.App.UpdateRole(role) 930 if err2 != nil { 931 utils.EnableDebugLogForTest() 932 panic(err2) 933 } 934 } 935 936 utils.EnableDebugLogForTest() 937 } 938 939 func (me *TestHelper) RemovePermissionFromRole(permission string, roleName string) { 940 utils.DisableDebugLogForTest() 941 942 role, err1 := me.App.GetRoleByName(roleName) 943 if err1 != nil { 944 utils.EnableDebugLogForTest() 945 panic(err1) 946 } 947 948 var newPermissions []string 949 for _, p := range role.Permissions { 950 if p != permission { 951 newPermissions = append(newPermissions, p) 952 } 953 } 954 955 if strings.Join(role.Permissions, " ") == strings.Join(newPermissions, " ") { 956 utils.EnableDebugLogForTest() 957 return 958 } 959 960 role.Permissions = newPermissions 961 962 _, err2 := me.App.UpdateRole(role) 963 if err2 != nil { 964 utils.EnableDebugLogForTest() 965 panic(err2) 966 } 967 968 utils.EnableDebugLogForTest() 969 } 970 971 func (me *TestHelper) AddPermissionToRole(permission string, roleName string) { 972 utils.DisableDebugLogForTest() 973 974 role, err1 := me.App.GetRoleByName(roleName) 975 if err1 != nil { 976 utils.EnableDebugLogForTest() 977 panic(err1) 978 } 979 980 for _, existingPermission := range role.Permissions { 981 if existingPermission == permission { 982 utils.EnableDebugLogForTest() 983 return 984 } 985 } 986 987 role.Permissions = append(role.Permissions, permission) 988 989 _, err2 := me.App.UpdateRole(role) 990 if err2 != nil { 991 utils.EnableDebugLogForTest() 992 panic(err2) 993 } 994 995 utils.EnableDebugLogForTest() 996 }