github.com/nhannv/mattermost-server@v5.11.1+incompatible/app/helper_test.go (about) 1 // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. 2 // See License.txt for license information. 3 4 package app 5 6 import ( 7 "io/ioutil" 8 "os" 9 "path/filepath" 10 "strings" 11 "time" 12 13 "testing" 14 15 "github.com/mattermost/mattermost-server/config" 16 "github.com/mattermost/mattermost-server/mlog" 17 "github.com/mattermost/mattermost-server/model" 18 "github.com/mattermost/mattermost-server/utils" 19 ) 20 21 type TestHelper struct { 22 App *App 23 Server *Server 24 BasicTeam *model.Team 25 BasicUser *model.User 26 BasicUser2 *model.User 27 BasicChannel *model.Channel 28 BasicPost *model.Post 29 30 SystemAdminUser *model.User 31 32 tempWorkspace string 33 } 34 35 func setupTestHelper(enterprise bool, tb testing.TB) *TestHelper { 36 store := mainHelper.GetStore() 37 store.DropAllTables() 38 39 memoryStore, err := config.NewMemoryStore() 40 if err != nil { 41 panic("failed to initialize memory store: " + err.Error()) 42 } 43 44 var options []Option 45 options = append(options, ConfigStore(memoryStore)) 46 options = append(options, StoreOverride(mainHelper.Store)) 47 options = append(options, SetLogger(mlog.NewTestingLogger(tb))) 48 49 s, err := NewServer(options...) 50 if err != nil { 51 panic(err) 52 } 53 54 th := &TestHelper{ 55 App: s.FakeApp(), 56 Server: s, 57 } 58 59 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.MaxUsersPerTeam = 50 }) 60 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.RateLimitSettings.Enable = false }) 61 prevListenAddress := *th.App.Config().ServiceSettings.ListenAddress 62 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = ":0" }) 63 serverErr := th.Server.Start() 64 if serverErr != nil { 65 panic(serverErr) 66 } 67 68 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = prevListenAddress }) 69 70 th.App.Srv.Store.MarkSystemRanUnitTests() 71 72 th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true }) 73 74 if enterprise { 75 th.App.SetLicense(model.NewTestLicense()) 76 } else { 77 th.App.SetLicense(nil) 78 } 79 80 if th.tempWorkspace == "" { 81 dir, err := ioutil.TempDir("", "apptest") 82 if err != nil { 83 panic(err) 84 } 85 th.tempWorkspace = dir 86 } 87 88 pluginDir := filepath.Join(th.tempWorkspace, "plugins") 89 webappDir := filepath.Join(th.tempWorkspace, "webapp") 90 91 th.App.InitPlugins(pluginDir, webappDir) 92 93 return th 94 } 95 96 func SetupEnterprise(tb testing.TB) *TestHelper { 97 return setupTestHelper(true, tb) 98 } 99 100 func Setup(tb testing.TB) *TestHelper { 101 return setupTestHelper(false, tb) 102 } 103 104 func (me *TestHelper) InitBasic() *TestHelper { 105 me.SystemAdminUser = me.CreateUser() 106 me.App.UpdateUserRoles(me.SystemAdminUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID, false) 107 me.SystemAdminUser, _ = me.App.GetUser(me.SystemAdminUser.Id) 108 109 me.BasicTeam = me.CreateTeam() 110 me.BasicUser = me.CreateUser() 111 112 me.LinkUserToTeam(me.BasicUser, me.BasicTeam) 113 me.BasicUser2 = me.CreateUser() 114 me.LinkUserToTeam(me.BasicUser2, me.BasicTeam) 115 me.BasicChannel = me.CreateChannel(me.BasicTeam) 116 me.BasicPost = me.CreatePost(me.BasicChannel) 117 118 return me 119 } 120 121 func (me *TestHelper) MakeEmail() string { 122 return "success_" + model.NewId() + "@simulator.amazonses.com" 123 } 124 125 func (me *TestHelper) CreateTeam() *model.Team { 126 id := model.NewId() 127 team := &model.Team{ 128 DisplayName: "dn_" + id, 129 Name: "name" + id, 130 Email: "success+" + id + "@simulator.amazonses.com", 131 Type: model.TEAM_OPEN, 132 } 133 134 utils.DisableDebugLogForTest() 135 var err *model.AppError 136 if team, err = me.App.CreateTeam(team); err != nil { 137 mlog.Error(err.Error()) 138 139 time.Sleep(time.Second) 140 panic(err) 141 } 142 utils.EnableDebugLogForTest() 143 return team 144 } 145 146 func (me *TestHelper) CreateUser() *model.User { 147 id := model.NewId() 148 149 user := &model.User{ 150 Email: "success+" + id + "@simulator.amazonses.com", 151 Username: "un_" + id, 152 Nickname: "nn_" + id, 153 Password: "Password1", 154 EmailVerified: true, 155 } 156 157 utils.DisableDebugLogForTest() 158 var err *model.AppError 159 if user, err = me.App.CreateUser(user); err != nil { 160 mlog.Error(err.Error()) 161 162 time.Sleep(time.Second) 163 panic(err) 164 } 165 utils.EnableDebugLogForTest() 166 return user 167 } 168 169 func (me *TestHelper) CreateChannel(team *model.Team) *model.Channel { 170 return me.createChannel(team, model.CHANNEL_OPEN) 171 } 172 173 func (me *TestHelper) CreatePrivateChannel(team *model.Team) *model.Channel { 174 return me.createChannel(team, model.CHANNEL_PRIVATE) 175 } 176 177 func (me *TestHelper) createChannel(team *model.Team, channelType string) *model.Channel { 178 id := model.NewId() 179 180 channel := &model.Channel{ 181 DisplayName: "dn_" + id, 182 Name: "name_" + id, 183 Type: channelType, 184 TeamId: team.Id, 185 CreatorId: me.BasicUser.Id, 186 } 187 188 utils.DisableDebugLogForTest() 189 var err *model.AppError 190 if channel, err = me.App.CreateChannel(channel, true); err != nil { 191 mlog.Error(err.Error()) 192 193 time.Sleep(time.Second) 194 panic(err) 195 } 196 utils.EnableDebugLogForTest() 197 return channel 198 } 199 200 func (me *TestHelper) createChannelWithAnotherUser(team *model.Team, channelType, userId string) *model.Channel { 201 id := model.NewId() 202 203 channel := &model.Channel{ 204 DisplayName: "dn_" + id, 205 Name: "name_" + id, 206 Type: channelType, 207 TeamId: team.Id, 208 CreatorId: userId, 209 } 210 211 utils.DisableDebugLogForTest() 212 var err *model.AppError 213 if channel, err = me.App.CreateChannel(channel, true); err != nil { 214 mlog.Error(err.Error()) 215 216 time.Sleep(time.Second) 217 panic(err) 218 } 219 utils.EnableDebugLogForTest() 220 return channel 221 } 222 223 func (me *TestHelper) CreateDmChannel(user *model.User) *model.Channel { 224 utils.DisableDebugLogForTest() 225 var err *model.AppError 226 var channel *model.Channel 227 if channel, err = me.App.GetOrCreateDirectChannel(me.BasicUser.Id, user.Id); err != nil { 228 mlog.Error(err.Error()) 229 230 time.Sleep(time.Second) 231 panic(err) 232 } 233 utils.EnableDebugLogForTest() 234 return channel 235 } 236 237 func (me *TestHelper) CreateGroupChannel(user1 *model.User, user2 *model.User) *model.Channel { 238 utils.DisableDebugLogForTest() 239 var err *model.AppError 240 var channel *model.Channel 241 if channel, err = me.App.CreateGroupChannel([]string{me.BasicUser.Id, user1.Id, user2.Id}, me.BasicUser.Id); err != nil { 242 mlog.Error(err.Error()) 243 244 time.Sleep(time.Second) 245 panic(err) 246 } 247 utils.EnableDebugLogForTest() 248 return channel 249 } 250 251 func (me *TestHelper) CreatePost(channel *model.Channel) *model.Post { 252 id := model.NewId() 253 254 post := &model.Post{ 255 UserId: me.BasicUser.Id, 256 ChannelId: channel.Id, 257 Message: "message_" + id, 258 CreateAt: model.GetMillis() - 10000, 259 } 260 261 utils.DisableDebugLogForTest() 262 var err *model.AppError 263 if post, err = me.App.CreatePost(post, channel, false); err != nil { 264 mlog.Error(err.Error()) 265 266 time.Sleep(time.Second) 267 panic(err) 268 } 269 utils.EnableDebugLogForTest() 270 return post 271 } 272 273 func (me *TestHelper) LinkUserToTeam(user *model.User, team *model.Team) { 274 utils.DisableDebugLogForTest() 275 276 err := me.App.JoinUserToTeam(team, user, "") 277 if err != nil { 278 mlog.Error(err.Error()) 279 280 time.Sleep(time.Second) 281 panic(err) 282 } 283 284 utils.EnableDebugLogForTest() 285 } 286 287 func (me *TestHelper) AddUserToChannel(user *model.User, channel *model.Channel) *model.ChannelMember { 288 utils.DisableDebugLogForTest() 289 290 member, err := me.App.AddUserToChannel(user, channel) 291 if err != nil { 292 mlog.Error(err.Error()) 293 294 time.Sleep(time.Second) 295 panic(err) 296 } 297 298 utils.EnableDebugLogForTest() 299 300 return member 301 } 302 303 func (me *TestHelper) CreateScheme() (*model.Scheme, []*model.Role) { 304 utils.DisableDebugLogForTest() 305 306 scheme, err := me.App.CreateScheme(&model.Scheme{ 307 DisplayName: "Test Scheme Display Name", 308 Name: model.NewId(), 309 Description: "Test scheme description", 310 Scope: model.SCHEME_SCOPE_TEAM, 311 }) 312 if err != nil { 313 panic(err) 314 } 315 316 roleNames := []string{ 317 scheme.DefaultTeamAdminRole, 318 scheme.DefaultTeamUserRole, 319 scheme.DefaultChannelAdminRole, 320 scheme.DefaultChannelUserRole, 321 } 322 323 var roles []*model.Role 324 for _, roleName := range roleNames { 325 role, err := me.App.GetRoleByName(roleName) 326 if err != nil { 327 panic(err) 328 } 329 roles = append(roles, role) 330 } 331 332 utils.EnableDebugLogForTest() 333 334 return scheme, roles 335 } 336 337 func (me *TestHelper) CreateGroup() *model.Group { 338 id := model.NewId() 339 group := &model.Group{ 340 DisplayName: "dn_" + id, 341 Name: "name" + id, 342 Source: model.GroupSourceLdap, 343 Description: "description_" + id, 344 RemoteId: model.NewId(), 345 } 346 347 utils.DisableDebugLogForTest() 348 var err *model.AppError 349 if group, err = me.App.CreateGroup(group); err != nil { 350 mlog.Error(err.Error()) 351 352 time.Sleep(time.Second) 353 panic(err) 354 } 355 utils.EnableDebugLogForTest() 356 return group 357 } 358 359 func (me *TestHelper) CreateEmoji() *model.Emoji { 360 utils.DisableDebugLogForTest() 361 362 result := <-me.App.Srv.Store.Emoji().Save(&model.Emoji{ 363 CreatorId: me.BasicUser.Id, 364 Name: model.NewRandomString(10), 365 }) 366 if result.Err != nil { 367 panic(result.Err) 368 } 369 370 utils.EnableDebugLogForTest() 371 372 return result.Data.(*model.Emoji) 373 } 374 375 func (me *TestHelper) AddReactionToPost(post *model.Post, user *model.User, emojiName string) *model.Reaction { 376 utils.DisableDebugLogForTest() 377 378 reaction, err := me.App.SaveReactionForPost(&model.Reaction{ 379 UserId: user.Id, 380 PostId: post.Id, 381 EmojiName: emojiName, 382 }) 383 if err != nil { 384 panic(err) 385 } 386 387 utils.EnableDebugLogForTest() 388 389 return reaction 390 } 391 392 func (me *TestHelper) ShutdownApp() { 393 done := make(chan bool) 394 go func() { 395 me.Server.Shutdown() 396 close(done) 397 }() 398 399 select { 400 case <-done: 401 case <-time.After(30 * time.Second): 402 // panic instead of t.Fatal to terminate all tests in this package, otherwise the 403 // still running App could spuriously fail subsequent tests. 404 panic("failed to shutdown App within 30 seconds") 405 } 406 } 407 408 func (me *TestHelper) TearDown() { 409 me.ShutdownApp() 410 if err := recover(); err != nil { 411 panic(err) 412 } 413 if me.tempWorkspace != "" { 414 os.RemoveAll(me.tempWorkspace) 415 } 416 } 417 418 func (me *TestHelper) ResetRoleMigration() { 419 sqlSupplier := mainHelper.GetSqlSupplier() 420 if _, err := sqlSupplier.GetMaster().Exec("DELETE from Roles"); err != nil { 421 panic(err) 422 } 423 424 mainHelper.GetClusterInterface().SendClearRoleCacheMessage() 425 426 if _, err := sqlSupplier.GetMaster().Exec("DELETE from Systems where Name = :Name", map[string]interface{}{"Name": ADVANCED_PERMISSIONS_MIGRATION_KEY}); err != nil { 427 panic(err) 428 } 429 } 430 431 func (me *TestHelper) ResetEmojisMigration() { 432 sqlSupplier := mainHelper.GetSqlSupplier() 433 if _, err := sqlSupplier.GetMaster().Exec("UPDATE Roles SET Permissions=REPLACE(Permissions, ' create_emojis', '') WHERE builtin=True"); err != nil { 434 panic(err) 435 } 436 437 if _, err := sqlSupplier.GetMaster().Exec("UPDATE Roles SET Permissions=REPLACE(Permissions, ' delete_emojis', '') WHERE builtin=True"); err != nil { 438 panic(err) 439 } 440 441 if _, err := sqlSupplier.GetMaster().Exec("UPDATE Roles SET Permissions=REPLACE(Permissions, ' delete_others_emojis', '') WHERE builtin=True"); err != nil { 442 panic(err) 443 } 444 445 mainHelper.GetClusterInterface().SendClearRoleCacheMessage() 446 447 if _, err := sqlSupplier.GetMaster().Exec("DELETE from Systems where Name = :Name", map[string]interface{}{"Name": EMOJIS_PERMISSIONS_MIGRATION_KEY}); err != nil { 448 panic(err) 449 } 450 } 451 452 func (me *TestHelper) CheckTeamCount(t *testing.T, expected int64) { 453 if r := <-me.App.Srv.Store.Team().AnalyticsTeamCount(); r.Err == nil { 454 if r.Data.(int64) != expected { 455 t.Fatalf("Unexpected number of teams. Expected: %v, found: %v", expected, r.Data.(int64)) 456 } 457 } else { 458 t.Fatalf("Failed to get team count.") 459 } 460 } 461 462 func (me *TestHelper) CheckChannelsCount(t *testing.T, expected int64) { 463 if r := <-me.App.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { 464 if r.Data.(int64) != expected { 465 t.Fatalf("Unexpected number of channels. Expected: %v, found: %v", expected, r.Data.(int64)) 466 } 467 } else { 468 t.Fatalf("Failed to get channel count.") 469 } 470 } 471 472 func (me *TestHelper) SetupTeamScheme() *model.Scheme { 473 scheme := model.Scheme{ 474 Name: model.NewId(), 475 DisplayName: model.NewId(), 476 Scope: model.SCHEME_SCOPE_TEAM, 477 } 478 479 if scheme, err := me.App.CreateScheme(&scheme); err == nil { 480 return scheme 481 } else { 482 panic(err) 483 } 484 } 485 486 func (me *TestHelper) SetupChannelScheme() *model.Scheme { 487 scheme := model.Scheme{ 488 Name: model.NewId(), 489 DisplayName: model.NewId(), 490 Scope: model.SCHEME_SCOPE_CHANNEL, 491 } 492 493 if scheme, err := me.App.CreateScheme(&scheme); err == nil { 494 return scheme 495 } else { 496 panic(err) 497 } 498 } 499 500 func (me *TestHelper) SetupPluginAPI() *PluginAPI { 501 manifest := &model.Manifest{ 502 Id: "pluginid", 503 } 504 505 return NewPluginAPI(me.App, manifest) 506 } 507 508 func (me *TestHelper) RemovePermissionFromRole(permission string, roleName string) { 509 utils.DisableDebugLogForTest() 510 511 role, err1 := me.App.GetRoleByName(roleName) 512 if err1 != nil { 513 utils.EnableDebugLogForTest() 514 panic(err1) 515 } 516 517 var newPermissions []string 518 for _, p := range role.Permissions { 519 if p != permission { 520 newPermissions = append(newPermissions, p) 521 } 522 } 523 524 if strings.Join(role.Permissions, " ") == strings.Join(newPermissions, " ") { 525 utils.EnableDebugLogForTest() 526 return 527 } 528 529 role.Permissions = newPermissions 530 531 _, err2 := me.App.UpdateRole(role) 532 if err2 != nil { 533 utils.EnableDebugLogForTest() 534 panic(err2) 535 } 536 537 utils.EnableDebugLogForTest() 538 } 539 540 func (me *TestHelper) AddPermissionToRole(permission string, roleName string) { 541 utils.DisableDebugLogForTest() 542 543 role, err1 := me.App.GetRoleByName(roleName) 544 if err1 != nil { 545 utils.EnableDebugLogForTest() 546 panic(err1) 547 } 548 549 for _, existingPermission := range role.Permissions { 550 if existingPermission == permission { 551 utils.EnableDebugLogForTest() 552 return 553 } 554 } 555 556 role.Permissions = append(role.Permissions, permission) 557 558 _, err2 := me.App.UpdateRole(role) 559 if err2 != nil { 560 utils.EnableDebugLogForTest() 561 panic(err2) 562 } 563 564 utils.EnableDebugLogForTest() 565 }