From b066b6df138e88e75cb40f1ec3e58fbd13e61909 Mon Sep 17 00:00:00 2001 From: Chris Date: Tue, 12 Sep 2017 09:19:52 -0500 Subject: Remove global app references (#7433) * remove global app references * test fix * fix api4 test compilation --- api/api.go | 15 +- api/apitestlib.go | 62 ++-- api/emoji_test.go | 10 +- api4/api.go | 15 +- api4/apitestlib.go | 66 ++-- api4/plugin_test.go | 2 +- app/apptestlib.go | 58 ++-- app/authorization_test.go | 3 +- app/channel_test.go | 50 ++- app/cluster_discovery_test.go | 3 +- app/command_channel_rename_test.go | 3 +- app/diagnostics_test.go | 7 +- app/email_batching_test.go | 42 ++- app/email_test.go | 639 ------------------------------------- app/file_test.go | 15 +- app/import_test.go | 524 +++++++++++++++--------------- app/job_test.go | 20 +- app/license_test.go | 15 +- app/notification_test.go | 72 ++--- app/oauth_test.go | 26 +- app/post_test.go | 25 +- app/team_test.go | 62 ++-- app/user_test.go | 34 +- app/webhook_test.go | 11 +- cmd/platform/channel.go | 69 ++-- cmd/platform/import.go | 11 +- cmd/platform/init.go | 22 +- cmd/platform/ldap.go | 2 +- cmd/platform/license.go | 7 +- cmd/platform/mattermost.go | 6 +- cmd/platform/roles.go | 11 +- cmd/platform/server.go | 76 +++-- cmd/platform/team.go | 32 +- cmd/platform/test.go | 27 +- cmd/platform/user.go | 62 ++-- cmd/platform/version.go | 9 +- web/web_test.go | 45 ++- 37 files changed, 724 insertions(+), 1434 deletions(-) delete mode 100644 app/email_test.go diff --git a/api/api.go b/api/api.go index 8e8064731..313cbc7e1 100644 --- a/api/api.go +++ b/api/api.go @@ -59,15 +59,16 @@ type Routes struct { var BaseRoutes *Routes -func InitRouter() { - app.Global().Srv.Router = mux.NewRouter() - app.Global().Srv.Router.NotFoundHandler = http.HandlerFunc(Handle404) +func NewRouter() *mux.Router { + ret := mux.NewRouter() + ret.NotFoundHandler = http.HandlerFunc(Handle404) + return ret } -func InitApi() { +func InitApi(root *mux.Router) { BaseRoutes = &Routes{} - BaseRoutes.Root = app.Global().Srv.Router - BaseRoutes.ApiRoot = app.Global().Srv.Router.PathPrefix(model.API_URL_SUFFIX_V3).Subrouter() + BaseRoutes.Root = root + BaseRoutes.ApiRoot = root.PathPrefix(model.API_URL_SUFFIX_V3).Subrouter() BaseRoutes.Users = BaseRoutes.ApiRoot.PathPrefix("/users").Subrouter() BaseRoutes.NeedUser = BaseRoutes.Users.PathPrefix("/{user_id:[A-Za-z0-9]+}").Subrouter() BaseRoutes.Teams = BaseRoutes.ApiRoot.PathPrefix("/teams").Subrouter() @@ -111,7 +112,7 @@ func InitApi() { InitDeprecated() // 404 on any api route before web.go has a chance to serve it - app.Global().Srv.Router.Handle("/api/{anything:.*}", http.HandlerFunc(Handle404)) + root.Handle("/api/{anything:.*}", http.HandlerFunc(Handle404)) utils.InitHTML() diff --git a/api/apitestlib.go b/api/apitestlib.go index 71a1f59c2..3f63f3ffc 100644 --- a/api/apitestlib.go +++ b/api/apitestlib.go @@ -33,35 +33,12 @@ type TestHelper struct { SystemAdminChannel *model.Channel } -func SetupEnterprise() *TestHelper { - if app.Global().Srv == nil { - utils.TranslationsPreInit() - utils.LoadConfig("config.json") - utils.InitTranslations(utils.Cfg.LocalizationSettings) - *utils.Cfg.TeamSettings.MaxUsersPerTeam = 50 - *utils.Cfg.RateLimitSettings.Enable = false - utils.DisableDebugLogForTest() - utils.License().Features.SetDefaults() - app.Global().NewServer() - app.Global().InitStores() - InitRouter() - wsapi.InitRouter() - app.Global().StartServer() - utils.InitHTML() - api4.InitApi(false) - InitApi() - wsapi.InitApi() - utils.EnableDebugLogForTest() - app.Global().Srv.Store.MarkSystemRanUnitTests() - - *utils.Cfg.TeamSettings.EnableOpenServer = true +func setupTestHelper(enterprise bool) *TestHelper { + th := &TestHelper{ + App: app.Global(), } - return &TestHelper{} -} - -func Setup() *TestHelper { - if app.Global().Srv == nil { + if th.App.Srv == nil { utils.TranslationsPreInit() utils.LoadConfig("config.json") utils.InitTranslations(utils.Cfg.LocalizationSettings) @@ -69,21 +46,32 @@ func Setup() *TestHelper { *utils.Cfg.RateLimitSettings.Enable = false utils.Cfg.EmailSettings.SendEmailNotifications = true utils.DisableDebugLogForTest() - app.Global().NewServer() - app.Global().InitStores() - InitRouter() + if enterprise { + utils.License().Features.SetDefaults() + } + th.App.NewServer() + th.App.InitStores() + th.App.Srv.Router = NewRouter() wsapi.InitRouter() - app.Global().StartServer() - api4.InitApi(false) - InitApi() + th.App.StartServer() + api4.InitApi(th.App.Srv.Router, false) + InitApi(th.App.Srv.Router) wsapi.InitApi() utils.EnableDebugLogForTest() - app.Global().Srv.Store.MarkSystemRanUnitTests() + th.App.Srv.Store.MarkSystemRanUnitTests() *utils.Cfg.TeamSettings.EnableOpenServer = true } - return &TestHelper{} + return th +} + +func SetupEnterprise() *TestHelper { + return setupTestHelper(true) +} + +func Setup() *TestHelper { + return setupTestHelper(false) } func ReloadConfigForSetup() { @@ -96,7 +84,6 @@ func ReloadConfigForSetup() { } func (me *TestHelper) InitBasic() *TestHelper { - me.App = app.Global() me.BasicClient = me.CreateClient() me.BasicUser = me.CreateUser(me.BasicClient) me.LoginBasic() @@ -116,7 +103,6 @@ func (me *TestHelper) InitBasic() *TestHelper { } func (me *TestHelper) InitSystemAdmin() *TestHelper { - me.App = app.Global() me.SystemAdminClient = me.CreateClient() me.SystemAdminUser = me.CreateUser(me.SystemAdminClient) me.SystemAdminUser.Password = "Password1" @@ -166,7 +152,7 @@ func (me *TestHelper) CreateUser(client *model.Client) *model.User { utils.DisableDebugLogForTest() ruser := client.Must(client.CreateUser(user, "")).Data.(*model.User) ruser.Password = "Password1" - store.Must(app.Global().Srv.Store.User().VerifyEmail(ruser.Id)) + store.Must(me.App.Srv.Store.User().VerifyEmail(ruser.Id)) utils.EnableDebugLogForTest() return ruser } diff --git a/api/emoji_test.go b/api/emoji_test.go index 01fd9411c..443fe7758 100644 --- a/api/emoji_test.go +++ b/api/emoji_test.go @@ -226,7 +226,7 @@ func TestDeleteEmoji(t *testing.T) { }() *utils.Cfg.ServiceSettings.EnableCustomEmoji = false - emoji1 := createTestEmoji(t, &model.Emoji{ + emoji1 := createTestEmoji(t, th.App, &model.Emoji{ CreatorId: th.BasicUser.Id, Name: model.NewId(), }, utils.CreateTestGif(t, 10, 10)) @@ -247,7 +247,7 @@ func TestDeleteEmoji(t *testing.T) { t.Fatal("shouldn't be able to delete an already-deleted emoji") } - emoji2 := createTestEmoji(t, &model.Emoji{ + emoji2 := createTestEmoji(t, th.App, &model.Emoji{ CreatorId: th.BasicUser2.Id, Name: model.NewId(), }, utils.CreateTestGif(t, 10, 10)) @@ -263,11 +263,11 @@ func TestDeleteEmoji(t *testing.T) { } } -func createTestEmoji(t *testing.T, emoji *model.Emoji, imageData []byte) *model.Emoji { - emoji = store.Must(app.Global().Srv.Store.Emoji().Save(emoji)).(*model.Emoji) +func createTestEmoji(t *testing.T, a *app.App, emoji *model.Emoji, imageData []byte) *model.Emoji { + emoji = store.Must(a.Srv.Store.Emoji().Save(emoji)).(*model.Emoji) if err := utils.WriteFile(imageData, "emoji/"+emoji.Id+"/image"); err != nil { - store.Must(app.Global().Srv.Store.Emoji().Delete(emoji.Id, time.Now().Unix())) + store.Must(a.Srv.Store.Emoji().Delete(emoji.Id, time.Now().Unix())) t.Fatalf("failed to write image: %v", err.Error()) } diff --git a/api4/api.go b/api4/api.go index 50c56ca0b..7b3beaf40 100644 --- a/api4/api.go +++ b/api4/api.go @@ -105,15 +105,16 @@ type Routes struct { var BaseRoutes *Routes -func InitRouter() { - app.Global().Srv.Router = mux.NewRouter() - app.Global().Srv.Router.NotFoundHandler = http.HandlerFunc(Handle404) +func NewRouter() *mux.Router { + ret := mux.NewRouter() + ret.NotFoundHandler = http.HandlerFunc(Handle404) + return ret } -func InitApi(full bool) { +func InitApi(root *mux.Router, full bool) { BaseRoutes = &Routes{} - BaseRoutes.Root = app.Global().Srv.Router - BaseRoutes.ApiRoot = app.Global().Srv.Router.PathPrefix(model.API_URL_SUFFIX).Subrouter() + BaseRoutes.Root = root + BaseRoutes.ApiRoot = root.PathPrefix(model.API_URL_SUFFIX).Subrouter() BaseRoutes.Users = BaseRoutes.ApiRoot.PathPrefix("/users").Subrouter() BaseRoutes.User = BaseRoutes.ApiRoot.PathPrefix("/users/{user_id:[A-Za-z0-9]+}").Subrouter() @@ -213,7 +214,7 @@ func InitApi(full bool) { InitOpenGraph() InitPlugin() - app.Global().Srv.Router.Handle("/api/v4/{anything:.*}", http.HandlerFunc(Handle404)) + root.Handle("/api/v4/{anything:.*}", http.HandlerFunc(Handle404)) // REMOVE CONDITION WHEN APIv3 REMOVED if full { diff --git a/api4/apitestlib.go b/api4/apitestlib.go index e647d659c..d98683d32 100644 --- a/api4/apitestlib.go +++ b/api4/apitestlib.go @@ -45,8 +45,12 @@ type TestHelper struct { SystemAdminUser *model.User } -func SetupEnterprise() *TestHelper { - if app.Global().Srv == nil { +func setupTestHelper(enterprise bool) *TestHelper { + th := &TestHelper{ + App: app.Global(), + } + + if th.App.Srv == nil { utils.TranslationsPreInit() utils.LoadConfig("config.json") utils.InitTranslations(utils.Cfg.LocalizationSettings) @@ -54,63 +58,37 @@ func SetupEnterprise() *TestHelper { *utils.Cfg.RateLimitSettings.Enable = false utils.Cfg.EmailSettings.SendEmailNotifications = true utils.DisableDebugLogForTest() - utils.License().Features.SetDefaults() - app.Global().NewServer() - app.Global().InitStores() - InitRouter() + if enterprise { + utils.License().Features.SetDefaults() + } + th.App.NewServer() + th.App.InitStores() + th.App.Srv.Router = NewRouter() wsapi.InitRouter() - app.Global().StartServer() - utils.InitHTML() - InitApi(true) + th.App.StartServer() + InitApi(th.App.Srv.Router, true) wsapi.InitApi() utils.EnableDebugLogForTest() - app.Global().Srv.Store.MarkSystemRanUnitTests() + th.App.Srv.Store.MarkSystemRanUnitTests() *utils.Cfg.TeamSettings.EnableOpenServer = true } if jobs.Srv.Store == nil { - jobs.Srv.Store = app.Global().Srv.Store + jobs.Srv.Store = th.App.Srv.Store } - th := &TestHelper{} - th.App = app.Global() th.Client = th.CreateClient() th.SystemAdminClient = th.CreateClient() return th } -func Setup() *TestHelper { - if app.Global().Srv == nil { - utils.TranslationsPreInit() - utils.LoadConfig("config.json") - utils.InitTranslations(utils.Cfg.LocalizationSettings) - *utils.Cfg.TeamSettings.MaxUsersPerTeam = 50 - *utils.Cfg.RateLimitSettings.Enable = false - utils.Cfg.EmailSettings.SendEmailNotifications = true - utils.DisableDebugLogForTest() - app.Global().NewServer() - app.Global().InitStores() - InitRouter() - wsapi.InitRouter() - app.Global().StartServer() - InitApi(true) - wsapi.InitApi() - utils.EnableDebugLogForTest() - app.Global().Srv.Store.MarkSystemRanUnitTests() - - *utils.Cfg.TeamSettings.EnableOpenServer = true - } - - if jobs.Srv.Store == nil { - jobs.Srv.Store = app.Global().Srv.Store - } +func SetupEnterprise() *TestHelper { + return setupTestHelper(true) +} - th := &TestHelper{} - th.App = app.Global() - th.Client = th.CreateClient() - th.SystemAdminClient = th.CreateClient() - return th +func Setup() *TestHelper { + return setupTestHelper(false) } func StopServer() { @@ -389,7 +367,7 @@ func (me *TestHelper) LoginSystemAdminWithClient(client *model.Client4) { func (me *TestHelper) UpdateActiveUser(user *model.User, active bool) { utils.DisableDebugLogForTest() - _, err := app.Global().UpdateActive(user, active) + _, err := me.App.UpdateActive(user, active) if err != nil { l4g.Error(err.Error()) l4g.Close() diff --git a/api4/plugin_test.go b/api4/plugin_test.go index 0e8c0638c..898649f56 100644 --- a/api4/plugin_test.go +++ b/api4/plugin_test.go @@ -29,7 +29,7 @@ func TestPlugin(t *testing.T) { th := Setup().InitBasic().InitSystemAdmin() defer TearDown() - th.App.StartupPlugins(pluginDir, webappDir) + th.App.InitPlugins(pluginDir, webappDir) enablePlugins := *utils.Cfg.PluginSettings.Enable defer func() { diff --git a/app/apptestlib.go b/app/apptestlib.go index d07d9457d..a640ff391 100644 --- a/app/apptestlib.go +++ b/app/apptestlib.go @@ -13,6 +13,7 @@ import ( ) type TestHelper struct { + App *App BasicTeam *model.Team BasicUser *model.User BasicUser2 *model.User @@ -20,55 +21,48 @@ type TestHelper struct { BasicPost *model.Post } -func (a *App) SetupEnterprise() *TestHelper { - if a.Srv == nil { +func setupTestHelper(enterprise bool) *TestHelper { + th := &TestHelper{ + App: Global(), + } + + if th.App.Srv == nil { utils.TranslationsPreInit() utils.LoadConfig("config.json") utils.InitTranslations(utils.Cfg.LocalizationSettings) *utils.Cfg.TeamSettings.MaxUsersPerTeam = 50 *utils.Cfg.RateLimitSettings.Enable = false utils.DisableDebugLogForTest() - utils.License().Features.SetDefaults() - a.NewServer() - a.InitStores() - a.StartServer() + if enterprise { + utils.License().Features.SetDefaults() + } + th.App.NewServer() + th.App.InitStores() + th.App.StartServer() utils.InitHTML() utils.EnableDebugLogForTest() - a.Srv.Store.MarkSystemRanUnitTests() + th.App.Srv.Store.MarkSystemRanUnitTests() *utils.Cfg.TeamSettings.EnableOpenServer = true } - return &TestHelper{} + return th } -func (a *App) Setup() *TestHelper { - if a.Srv == nil { - utils.TranslationsPreInit() - utils.LoadConfig("config.json") - utils.InitTranslations(utils.Cfg.LocalizationSettings) - *utils.Cfg.TeamSettings.MaxUsersPerTeam = 50 - *utils.Cfg.RateLimitSettings.Enable = false - utils.DisableDebugLogForTest() - a.NewServer() - a.InitStores() - a.StartServer() - utils.InitHTML() - utils.EnableDebugLogForTest() - a.Srv.Store.MarkSystemRanUnitTests() - - *utils.Cfg.TeamSettings.EnableOpenServer = true - } +func SetupEnterprise() *TestHelper { + return setupTestHelper(true) +} - return &TestHelper{} +func Setup() *TestHelper { + return setupTestHelper(false) } func (me *TestHelper) InitBasic() *TestHelper { me.BasicTeam = me.CreateTeam() me.BasicUser = me.CreateUser() - Global().LinkUserToTeam(me.BasicUser, me.BasicTeam) + me.App.LinkUserToTeam(me.BasicUser, me.BasicTeam) me.BasicUser2 = me.CreateUser() - Global().LinkUserToTeam(me.BasicUser2, me.BasicTeam) + me.App.LinkUserToTeam(me.BasicUser2, me.BasicTeam) me.BasicChannel = me.CreateChannel(me.BasicTeam) me.BasicPost = me.CreatePost(me.BasicChannel) @@ -94,7 +88,7 @@ func (me *TestHelper) CreateTeam() *model.Team { utils.DisableDebugLogForTest() var err *model.AppError - if team, err = Global().CreateTeam(team); err != nil { + if team, err = me.App.CreateTeam(team); err != nil { l4g.Error(err.Error()) l4g.Close() time.Sleep(time.Second) @@ -117,7 +111,7 @@ func (me *TestHelper) CreateUser() *model.User { utils.DisableDebugLogForTest() var err *model.AppError - if user, err = Global().CreateUser(user); err != nil { + if user, err = me.App.CreateUser(user); err != nil { l4g.Error(err.Error()) l4g.Close() time.Sleep(time.Second) @@ -148,7 +142,7 @@ func (me *TestHelper) createChannel(team *model.Team, channelType string) *model utils.DisableDebugLogForTest() var err *model.AppError - if channel, err = Global().CreateChannel(channel, true); err != nil { + if channel, err = me.App.CreateChannel(channel, true); err != nil { l4g.Error(err.Error()) l4g.Close() time.Sleep(time.Second) @@ -169,7 +163,7 @@ func (me *TestHelper) CreatePost(channel *model.Channel) *model.Post { utils.DisableDebugLogForTest() var err *model.AppError - if post, err = Global().CreatePost(post, channel, false); err != nil { + if post, err = me.App.CreatePost(post, channel, false); err != nil { l4g.Error(err.Error()) l4g.Close() time.Sleep(time.Second) diff --git a/app/authorization_test.go b/app/authorization_test.go index 6ff5d551b..279bf17dc 100644 --- a/app/authorization_test.go +++ b/app/authorization_test.go @@ -10,8 +10,7 @@ import ( ) func TestCheckIfRolesGrantPermission(t *testing.T) { - a := Global() - a.Setup() + Setup() cases := []struct { roles []string diff --git a/app/channel_test.go b/app/channel_test.go index baf299830..34a9d8150 100644 --- a/app/channel_test.go +++ b/app/channel_test.go @@ -8,8 +8,7 @@ import ( ) func TestPermanentDeleteChannel(t *testing.T) { - a := Global() - th := a.Setup().InitBasic() + th := Setup().InitBasic() incomingWasEnabled := utils.Cfg.ServiceSettings.EnableIncomingWebhooks outgoingWasEnabled := utils.Cfg.ServiceSettings.EnableOutgoingWebhooks @@ -20,25 +19,25 @@ func TestPermanentDeleteChannel(t *testing.T) { utils.Cfg.ServiceSettings.EnableOutgoingWebhooks = outgoingWasEnabled }() - channel, err := a.CreateChannel(&model.Channel{DisplayName: "deletion-test", Name: "deletion-test", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) + channel, err := th.App.CreateChannel(&model.Channel{DisplayName: "deletion-test", Name: "deletion-test", Type: model.CHANNEL_OPEN, TeamId: th.BasicTeam.Id}, false) if err != nil { t.Fatal(err.Error()) } defer func() { - a.PermanentDeleteChannel(channel) + th.App.PermanentDeleteChannel(channel) }() - incoming, err := a.CreateIncomingWebhookForChannel(th.BasicUser.Id, channel, &model.IncomingWebhook{ChannelId: channel.Id}) + incoming, err := th.App.CreateIncomingWebhookForChannel(th.BasicUser.Id, channel, &model.IncomingWebhook{ChannelId: channel.Id}) if err != nil { t.Fatal(err.Error()) } - defer a.DeleteIncomingWebhook(incoming.Id) + defer th.App.DeleteIncomingWebhook(incoming.Id) - if incoming, err = a.GetIncomingWebhook(incoming.Id); incoming == nil || err != nil { + if incoming, err = th.App.GetIncomingWebhook(incoming.Id); incoming == nil || err != nil { t.Fatal("unable to get new incoming webhook") } - outgoing, err := a.CreateOutgoingWebhook(&model.OutgoingWebhook{ + outgoing, err := th.App.CreateOutgoingWebhook(&model.OutgoingWebhook{ ChannelId: channel.Id, TeamId: channel.TeamId, CreatorId: th.BasicUser.Id, @@ -47,65 +46,64 @@ func TestPermanentDeleteChannel(t *testing.T) { if err != nil { t.Fatal(err.Error()) } - defer a.DeleteOutgoingWebhook(outgoing.Id) + defer th.App.DeleteOutgoingWebhook(outgoing.Id) - if outgoing, err = a.GetOutgoingWebhook(outgoing.Id); outgoing == nil || err != nil { + if outgoing, err = th.App.GetOutgoingWebhook(outgoing.Id); outgoing == nil || err != nil { t.Fatal("unable to get new outgoing webhook") } - if err := a.PermanentDeleteChannel(channel); err != nil { + if err := th.App.PermanentDeleteChannel(channel); err != nil { t.Fatal(err.Error()) } - if incoming, err = a.GetIncomingWebhook(incoming.Id); incoming != nil || err == nil { + if incoming, err = th.App.GetIncomingWebhook(incoming.Id); incoming != nil || err == nil { t.Error("incoming webhook wasn't deleted") } - if outgoing, err = a.GetOutgoingWebhook(outgoing.Id); outgoing != nil || err == nil { + if outgoing, err = th.App.GetOutgoingWebhook(outgoing.Id); outgoing != nil || err == nil { t.Error("outgoing webhook wasn't deleted") } } func TestMoveChannel(t *testing.T) { - a := Global() - th := a.Setup().InitBasic() + th := Setup().InitBasic() sourceTeam := th.CreateTeam() targetTeam := th.CreateTeam() channel1 := th.CreateChannel(sourceTeam) defer func() { - a.PermanentDeleteChannel(channel1) - a.PermanentDeleteTeam(sourceTeam) - a.PermanentDeleteTeam(targetTeam) + th.App.PermanentDeleteChannel(channel1) + th.App.PermanentDeleteTeam(sourceTeam) + th.App.PermanentDeleteTeam(targetTeam) }() - if _, err := a.AddUserToTeam(sourceTeam.Id, th.BasicUser.Id, ""); err != nil { + if _, err := th.App.AddUserToTeam(sourceTeam.Id, th.BasicUser.Id, ""); err != nil { t.Fatal(err) } - if _, err := a.AddUserToTeam(sourceTeam.Id, th.BasicUser2.Id, ""); err != nil { + if _, err := th.App.AddUserToTeam(sourceTeam.Id, th.BasicUser2.Id, ""); err != nil { t.Fatal(err) } - if _, err := a.AddUserToTeam(targetTeam.Id, th.BasicUser.Id, ""); err != nil { + if _, err := th.App.AddUserToTeam(targetTeam.Id, th.BasicUser.Id, ""); err != nil { t.Fatal(err) } - if _, err := a.AddUserToChannel(th.BasicUser, channel1); err != nil { + if _, err := th.App.AddUserToChannel(th.BasicUser, channel1); err != nil { t.Fatal(err) } - if _, err := a.AddUserToChannel(th.BasicUser2, channel1); err != nil { + if _, err := th.App.AddUserToChannel(th.BasicUser2, channel1); err != nil { t.Fatal(err) } - if err := a.MoveChannel(targetTeam, channel1); err == nil { + if err := th.App.MoveChannel(targetTeam, channel1); err == nil { t.Fatal("Should have failed due to mismatched members.") } - if _, err := a.AddUserToTeam(targetTeam.Id, th.BasicUser2.Id, ""); err != nil { + if _, err := th.App.AddUserToTeam(targetTeam.Id, th.BasicUser2.Id, ""); err != nil { t.Fatal(err) } - if err := a.MoveChannel(targetTeam, channel1); err != nil { + if err := th.App.MoveChannel(targetTeam, channel1); err != nil { t.Fatal(err) } } diff --git a/app/cluster_discovery_test.go b/app/cluster_discovery_test.go index 2df70798b..e8ce62b5c 100644 --- a/app/cluster_discovery_test.go +++ b/app/cluster_discovery_test.go @@ -12,8 +12,7 @@ import ( ) func TestClusterDiscoveryService(t *testing.T) { - a := Global() - a.Setup() + Setup() ds := NewClusterDiscoveryService() ds.Type = model.CDS_TYPE_APP diff --git a/app/command_channel_rename_test.go b/app/command_channel_rename_test.go index 96af6e452..070462036 100644 --- a/app/command_channel_rename_test.go +++ b/app/command_channel_rename_test.go @@ -8,8 +8,7 @@ import ( ) func TestRenameProviderDoCommand(t *testing.T) { - a := Global() - th := a.Setup().InitBasic() + th := Setup().InitBasic() rp := RenameProvider{} args := &model.CommandArgs{ diff --git a/app/diagnostics_test.go b/app/diagnostics_test.go index 0d8bb613e..034b4cc9d 100644 --- a/app/diagnostics_test.go +++ b/app/diagnostics_test.go @@ -47,8 +47,7 @@ func TestPluginSetting(t *testing.T) { } func TestDiagnostics(t *testing.T) { - a := Global() - a.Setup().InitBasic() + th := Setup().InitBasic() if testing.Short() { t.SkipNow() @@ -92,7 +91,7 @@ func TestDiagnostics(t *testing.T) { }) t.Run("SendDailyDiagnostics", func(t *testing.T) { - a.SendDailyDiagnostics() + th.App.SendDailyDiagnostics() info := "" // Collect the info sent. @@ -152,7 +151,7 @@ func TestDiagnostics(t *testing.T) { *utils.Cfg.LogSettings.EnableDiagnostics = oldSetting }() - a.SendDailyDiagnostics() + th.App.SendDailyDiagnostics() select { case <-data: diff --git a/app/email_batching_test.go b/app/email_batching_test.go index 1d01d1772..2c58d43f8 100644 --- a/app/email_batching_test.go +++ b/app/email_batching_test.go @@ -13,8 +13,7 @@ import ( ) func TestHandleNewNotifications(t *testing.T) { - a := Global() - a.Setup() + Setup() id1 := model.NewId() id2 := model.NewId() @@ -94,8 +93,7 @@ func TestHandleNewNotifications(t *testing.T) { } func TestCheckPendingNotifications(t *testing.T) { - a := Global() - th := a.Setup().InitBasic() + th := Setup().InitBasic() job := MakeEmailBatchingJob(128) job.pendingNotifications[th.BasicUser.Id] = []*batchedNotification{ @@ -109,11 +107,11 @@ func TestCheckPendingNotifications(t *testing.T) { }, } - channelMember := store.Must(a.Srv.Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id)).(*model.ChannelMember) + channelMember := store.Must(th.App.Srv.Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id)).(*model.ChannelMember) channelMember.LastViewedAt = 9999999 - store.Must(a.Srv.Store.Channel().UpdateMember(channelMember)) + store.Must(th.App.Srv.Store.Channel().UpdateMember(channelMember)) - store.Must(a.Srv.Store.Preference().Save(&model.Preferences{{ + store.Must(th.App.Srv.Store.Preference().Save(&model.Preferences{{ UserId: th.BasicUser.Id, Category: model.PREFERENCE_CATEGORY_NOTIFICATIONS, Name: model.PREFERENCE_NAME_EMAIL_INTERVAL, @@ -128,9 +126,9 @@ func TestCheckPendingNotifications(t *testing.T) { } // test that notifications are cleared if the user has acted - channelMember = store.Must(a.Srv.Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id)).(*model.ChannelMember) + channelMember = store.Must(th.App.Srv.Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id)).(*model.ChannelMember) channelMember.LastViewedAt = 10001000 - store.Must(a.Srv.Store.Channel().UpdateMember(channelMember)) + store.Must(th.App.Srv.Store.Channel().UpdateMember(channelMember)) job.checkPendingNotifications(time.Unix(10002, 0), func(string, []*batchedNotification) {}) @@ -202,14 +200,13 @@ func TestCheckPendingNotifications(t *testing.T) { * Ensures that email batch interval defaults to 15 minutes for users that haven't explicitly set this preference */ func TestCheckPendingNotificationsDefaultInterval(t *testing.T) { - a := Global() - th := a.Setup().InitBasic() + th := Setup().InitBasic() job := MakeEmailBatchingJob(128) // bypasses recent user activity check - channelMember := store.Must(a.Srv.Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id)).(*model.ChannelMember) + channelMember := store.Must(th.App.Srv.Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id)).(*model.ChannelMember) channelMember.LastViewedAt = 9999000 - store.Must(a.Srv.Store.Channel().UpdateMember(channelMember)) + store.Must(th.App.Srv.Store.Channel().UpdateMember(channelMember)) job.pendingNotifications[th.BasicUser.Id] = []*batchedNotification{ { @@ -239,17 +236,16 @@ func TestCheckPendingNotificationsDefaultInterval(t *testing.T) { * Ensures that email batch interval defaults to 15 minutes if user preference is invalid */ func TestCheckPendingNotificationsCantParseInterval(t *testing.T) { - a := Global() - th := a.Setup().InitBasic() + th := Setup().InitBasic() job := MakeEmailBatchingJob(128) // bypasses recent user activity check - channelMember := store.Must(a.Srv.Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id)).(*model.ChannelMember) + channelMember := store.Must(th.App.Srv.Store.Channel().GetMember(th.BasicChannel.Id, th.BasicUser.Id)).(*model.ChannelMember) channelMember.LastViewedAt = 9999000 - store.Must(a.Srv.Store.Channel().UpdateMember(channelMember)) + store.Must(th.App.Srv.Store.Channel().UpdateMember(channelMember)) // preference value is not an integer, so we'll fall back to the default 15min value - store.Must(a.Srv.Store.Preference().Save(&model.Preferences{{ + store.Must(th.App.Srv.Store.Preference().Save(&model.Preferences{{ UserId: th.BasicUser.Id, Category: model.PREFERENCE_CATEGORY_NOTIFICATIONS, Name: model.PREFERENCE_NAME_EMAIL_INTERVAL, @@ -284,8 +280,7 @@ func TestCheckPendingNotificationsCantParseInterval(t *testing.T) { * Ensures that post contents are not included in notification email when email notification content type is set to generic */ func TestRenderBatchedPostGeneric(t *testing.T) { - a := Global() - a.Setup() + th := Setup() var post = &model.Post{} post.Message = "This is the message" var notification = &batchedNotification{} @@ -300,7 +295,7 @@ func TestRenderBatchedPostGeneric(t *testing.T) { return translationID } - var rendered = a.renderBatchedPost(notification, channel, sender, "http://localhost:8065", "", translateFunc, "en", model.EMAIL_NOTIFICATION_CONTENTS_GENERIC) + var rendered = th.App.renderBatchedPost(notification, channel, sender, "http://localhost:8065", "", translateFunc, "en", model.EMAIL_NOTIFICATION_CONTENTS_GENERIC) if strings.Contains(rendered, post.Message) { t.Fatal("Rendered email should not contain post contents when email notification contents type is set to Generic.") } @@ -310,8 +305,7 @@ func TestRenderBatchedPostGeneric(t *testing.T) { * Ensures that post contents included in notification email when email notification content type is set to full */ func TestRenderBatchedPostFull(t *testing.T) { - a := Global() - a.Setup() + th := Setup() var post = &model.Post{} post.Message = "This is the message" var notification = &batchedNotification{} @@ -326,7 +320,7 @@ func TestRenderBatchedPostFull(t *testing.T) { return translationID } - var rendered = a.renderBatchedPost(notification, channel, sender, "http://localhost:8065", "", translateFunc, "en", model.EMAIL_NOTIFICATION_CONTENTS_FULL) + var rendered = th.App.renderBatchedPost(notification, channel, sender, "http://localhost:8065", "", translateFunc, "en", model.EMAIL_NOTIFICATION_CONTENTS_FULL) if !strings.Contains(rendered, post.Message) { t.Fatal("Rendered email should contain post contents when email notification contents type is set to Full.") } diff --git a/app/email_test.go b/app/email_test.go deleted file mode 100644 index 0ad3a54b1..000000000 --- a/app/email_test.go +++ /dev/null @@ -1,639 +0,0 @@ -// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved. -// See License.txt for license information. - -package app - -/*func TestSendChangeUsernameEmail(t *testing.T) { - a := Global() - if testing.Short() { - t.SkipNow() - } - a.Setup() - - var emailTo string = "test@example.com" - var oldUsername string = "myoldusername" - var newUsername string = "fancyusername" - var locale string = "en" - var siteURL string = "" - var expectedPartialMessage string = "Your username for " + utils.Cfg.TeamSettings.SiteName + " has been changed to " + newUsername + "." - var expectedSubject string = "[" + utils.Cfg.TeamSettings.SiteName + "] Your username has changed" - - //Delete all the messages before check the sample email - utils.DeleteMailBox(emailTo) - - if err := SendChangeUsernameEmail(oldUsername, newUsername, emailTo, locale, siteURL); err != nil { - t.Log(err) - t.Fatal("Should send change username email") - } else { - //Check if the email was send to the rigth email address - var resultsMailbox utils.JSONMessageHeaderInbucket - err := utils.RetryInbucket(5, func() error { - var err error - resultsMailbox, err = utils.GetMailBox(emailTo) - return err - }) - if err != nil { - t.Log(err) - t.Log("No email was received, maybe due load on the server. Disabling this verification") - } - if err == nil && len(resultsMailbox) > 0 { - if !strings.ContainsAny(resultsMailbox[0].To[0], emailTo) { - t.Fatal("Wrong To recipient") - } else { - if resultsEmail, err := utils.GetMessageFromMailbox(emailTo, resultsMailbox[0].ID); err == nil { - if resultsEmail.Subject != expectedSubject { - t.Log(resultsEmail.Subject) - t.Fatal("Wrong Subject") - } - if !strings.Contains(resultsEmail.Body.Text, expectedPartialMessage) { - t.Log(resultsEmail.Body.Text) - t.Fatal("Wrong Body message") - } - } - } - } - } -} - -func TestSendEmailChangeVerifyEmail(t *testing.T) { - a := Global() - if testing.Short() { - t.SkipNow() - } - a.Setup() - - var newUserEmail string = "newtest@example.com" - var locale string = "en" - var siteURL string = "http://localhost:8065" - var expectedPartialMessage string = "You updated your email" - var expectedSubject string = "[" + utils.Cfg.TeamSettings.SiteName + "] Verify new email address" - var token string = "TEST_TOKEN" - - //Delete all the messages before check the sample email - utils.DeleteMailBox(newUserEmail) - - if err := SendEmailChangeVerifyEmail(newUserEmail, locale, siteURL, token); err != nil { - t.Log(err) - t.Fatal("Should send change username email") - } else { - //Check if the email was send to the rigth email address - var resultsMailbox utils.JSONMessageHeaderInbucket - err := utils.RetryInbucket(5, func() error { - var err error - resultsMailbox, err = utils.GetMailBox(newUserEmail) - return err - }) - if err != nil { - t.Log(err) - t.Log("No email was received, maybe due load on the server. Disabling this verification") - } - if err == nil && len(resultsMailbox) > 0 { - if !strings.ContainsAny(resultsMailbox[0].To[0], newUserEmail) { - t.Fatal("Wrong To recipient") - } else { - if resultsEmail, err := utils.GetMessageFromMailbox(newUserEmail, resultsMailbox[0].ID); err == nil { - if resultsEmail.Subject != expectedSubject { - t.Log(resultsEmail.Subject) - t.Fatal("Wrong Subject") - } - if !strings.Contains(resultsEmail.Body.Text, expectedPartialMessage) { - t.Log(resultsEmail.Body.Text) - t.Fatal("Wrong Body message") - } - if !strings.Contains(resultsEmail.Body.Text, utils.UrlEncode(newUserEmail)) { - t.Log(resultsEmail.Body.Text) - t.Fatal("Wrong new email in the message") - } - } - } - } - } -} - -func TestSendEmailChangeEmail(t *testing.T) { - a := Global() - if testing.Short() { - t.SkipNow() - } - a.Setup() - - var oldEmail string = "test@example.com" - var newUserEmail string = "newtest@example.com" - var locale string = "en" - var siteURL string = "" - var expectedPartialMessage string = "Your email address for Mattermost has been changed to " + newUserEmail - var expectedSubject string = "[" + utils.Cfg.TeamSettings.SiteName + "] Your email address has changed" - - //Delete all the messages before check the sample email - utils.DeleteMailBox(oldEmail) - - if err := SendEmailChangeEmail(oldEmail, newUserEmail, locale, siteURL); err != nil { - t.Log(err) - t.Fatal("Should send change username email") - } else { - //Check if the email was send to the rigth email address - var resultsMailbox utils.JSONMessageHeaderInbucket - err := utils.RetryInbucket(5, func() error { - var err error - resultsMailbox, err = utils.GetMailBox(oldEmail) - return err - }) - if err != nil { - t.Log(err) - t.Log("No email was received, maybe due load on the server. Disabling this verification") - } - if err == nil && len(resultsMailbox) > 0 { - if !strings.ContainsAny(resultsMailbox[0].To[0], oldEmail) { - t.Fatal("Wrong To recipient") - } else { - if resultsEmail, err := utils.GetMessageFromMailbox(oldEmail, resultsMailbox[0].ID); err == nil { - if resultsEmail.Subject != expectedSubject { - t.Log(resultsEmail.Subject) - t.Fatal("Wrong Subject") - } - if !strings.Contains(resultsEmail.Body.Text, expectedPartialMessage) { - t.Log(resultsEmail.Body.Text) - t.Fatal("Wrong Body message") - } - } - } - } - } -} - -func TestSendVerifyEmail(t *testing.T) { - a := Global() - if testing.Short() { - t.SkipNow() - } - a.Setup() - - var userEmail string = "test@example.com" - var locale string = "en" - var siteURL string = "http://localhost:8605" - var expectedPartialMessage string = "Please verify your email address by clicking below" - var expectedSubject string = "[" + utils.Cfg.TeamSettings.SiteName + "] Email Verification" - var token string = "TEST_TOKEN" - - //Delete all the messages before check the sample email - utils.DeleteMailBox(userEmail) - - if err := SendVerifyEmail(userEmail, locale, siteURL, token); err != nil { - t.Log(err) - t.Fatal("Should send change username email") - } else { - //Check if the email was send to the rigth email address - var resultsMailbox utils.JSONMessageHeaderInbucket - err := utils.RetryInbucket(5, func() error { - var err error - resultsMailbox, err = utils.GetMailBox(userEmail) - return err - }) - if err != nil { - t.Log(err) - t.Log("No email was received, maybe due load on the server. Disabling this verification") - } - if err == nil && len(resultsMailbox) > 0 { - if !strings.ContainsAny(resultsMailbox[0].To[0], userEmail) { - t.Fatal("Wrong To recipient") - } else { - if resultsEmail, err := utils.GetMessageFromMailbox(userEmail, resultsMailbox[0].ID); err == nil { - if resultsEmail.Subject != expectedSubject { - t.Log(resultsEmail.Subject) - t.Fatal("Wrong Subject") - } - if !strings.Contains(resultsEmail.Body.Text, expectedPartialMessage) { - t.Log(resultsEmail.Body.Text) - t.Fatal("Wrong Body message") - } - if !strings.Contains(resultsEmail.Body.Text, utils.UrlEncode(userEmail)) { - t.Log(resultsEmail.Body.Text) - t.Fatal("Wrong new email in the message") - } - } - } - } - } -} - -func TestSendSignInChangeEmail(t *testing.T) { - a := Global() - if testing.Short() { - t.SkipNow() - } - a.Setup() - - var email string = "test@example.com" - var locale string = "en" - var siteURL string = "" - var method string = "AD/LDAP" - var expectedPartialMessage string = "You updated your sign-in method on Mattermost to " + method + "." - var expectedSubject string = "[" + utils.Cfg.TeamSettings.SiteName + "] Your sign-in method has been updated" - - //Delete all the messages before check the sample email - utils.DeleteMailBox(email) - - if err := SendSignInChangeEmail(email, method, locale, siteURL); err != nil { - t.Log(err) - t.Fatal("Should send change username email") - } else { - //Check if the email was send to the rigth email address - var resultsMailbox utils.JSONMessageHeaderInbucket - err := utils.RetryInbucket(5, func() error { - var err error - resultsMailbox, err = utils.GetMailBox(email) - return err - }) - if err != nil { - t.Log(err) - t.Log("No email was received, maybe due load on the server. Disabling this verification") - } - if err == nil && len(resultsMailbox) > 0 { - if !strings.ContainsAny(resultsMailbox[0].To[0], email) { - t.Fatal("Wrong To recipient") - } else { - if resultsEmail, err := utils.GetMessageFromMailbox(email, resultsMailbox[0].ID); err == nil { - if resultsEmail.Subject != expectedSubject { - t.Log(resultsEmail.Subject) - t.Fatal("Wrong Subject") - } - if !strings.Contains(resultsEmail.Body.Text, expectedPartialMessage) { - t.Log(resultsEmail.Body.Text) - t.Fatal("Wrong Body message") - } - } - } - } - } -} - -func TestSendWelcomeEmail(t *testing.T) { - a := Global() - if testing.Short() { - t.SkipNow() - } - a.Setup() - - var userId string = "32432nkjnijn432uj32" - var email string = "test@example.com" - var locale string = "en" - var siteURL string = "http://test.mattermost.io" - var verified bool = true - var expectedPartialMessage string = "Mattermost lets you share messages and files from your PC or phone, with instant search and archiving" - var expectedSubject string = "[" + utils.Cfg.TeamSettings.SiteName + "] You joined test.mattermost.io" - - //Delete all the messages before check the sample email - utils.DeleteMailBox(email) - - if err := a.SendWelcomeEmail(userId, email, verified, locale, siteURL); err != nil { - t.Log(err) - t.Fatal("Should send change username email") - } else { - //Check if the email was send to the rigth email address - var resultsMailbox utils.JSONMessageHeaderInbucket - err := utils.RetryInbucket(5, func() error { - var err error - resultsMailbox, err = utils.GetMailBox(email) - return err - }) - if err != nil { - t.Log(err) - t.Log("No email was received, maybe due load on the server. Disabling this verification") - } - if err == nil && len(resultsMailbox) > 0 { - if !strings.ContainsAny(resultsMailbox[0].To[0], email) { - t.Fatal("Wrong To recipient") - } else { - if resultsEmail, err := utils.GetMessageFromMailbox(email, resultsMailbox[0].ID); err == nil { - if resultsEmail.Subject != expectedSubject { - t.Log(resultsEmail.Subject) - t.Fatal("Wrong Subject") - } - if !strings.Contains(resultsEmail.Body.Text, expectedPartialMessage) { - t.Log(resultsEmail.Body.Text) - t.Fatal("Wrong Body message") - } - } - } - } - } - - utils.DeleteMailBox(email) - verified = false - var expectedVerifyEmail string = "Please verify your email address by clicking below." - - if err := a.SendWelcomeEmail(userId, email, verified, locale, siteURL); err != nil { - t.Log(err) - t.Fatal("Should send change username email") - } else { - //Check if the email was send to the rigth email address - var resultsMailbox utils.JSONMessageHeaderInbucket - err := utils.RetryInbucket(5, func() error { - var err error - resultsMailbox, err = utils.GetMailBox(email) - return err - }) - if err != nil { - t.Log(err) - t.Log("No email was received, maybe due load on the server. Disabling this verification") - } - if err == nil && len(resultsMailbox) > 0 { - if !strings.ContainsAny(resultsMailbox[0].To[0], email) { - t.Fatal("Wrong To recipient") - } else { - if resultsEmail, err := utils.GetMessageFromMailbox(email, resultsMailbox[0].ID); err == nil { - if !strings.Contains(resultsEmail.Subject, expectedSubject) { - t.Log(resultsEmail.Subject) - t.Fatal("Wrong Subject") - } - if !strings.Contains(resultsEmail.Body.Text, expectedPartialMessage) { - t.Log(resultsEmail.Body.Text) - t.Fatal("Wrong Body message") - } - if !strings.Contains(resultsEmail.Body.Text, expectedVerifyEmail) { - t.Log(resultsEmail.Body.Text) - t.Fatal("Wrong Body message") - } - if !strings.Contains(resultsEmail.Body.Text, utils.UrlEncode(email)) { - t.Log(resultsEmail.Body.Text) - t.Fatal("Wrong email in the message") - } - } - } - } - } -} - -func TestSendPasswordChangeEmail(t *testing.T) { - a := Global() - if testing.Short() { - t.SkipNow() - } - a.Setup() - - var email string = "test@example.com" - var locale string = "en" - var siteURL string = "http://test.mattermost.io" - var method string = "using a reset password link" - var expectedPartialMessage string = "Your password has been updated for " + utils.Cfg.TeamSettings.SiteName + " on " + siteURL + " by " + method - var expectedSubject string = "[" + utils.Cfg.TeamSettings.SiteName + "] Your password has been updated" - - //Delete all the messages before check the sample email - utils.DeleteMailBox(email) - - if err := SendPasswordChangeEmail(email, method, locale, siteURL); err != nil { - t.Log(err) - t.Fatal("Should send change username email") - } else { - //Check if the email was send to the rigth email address - var resultsMailbox utils.JSONMessageHeaderInbucket - err := utils.RetryInbucket(5, func() error { - var err error - resultsMailbox, err = utils.GetMailBox(email) - return err - }) - if err != nil { - t.Log(err) - t.Log("No email was received, maybe due load on the server. Disabling this verification") - } - if err == nil && len(resultsMailbox) > 0 { - if !strings.ContainsAny(resultsMailbox[0].To[0], email) { - t.Fatal("Wrong To recipient") - } else { - if resultsEmail, err := utils.GetMessageFromMailbox(email, resultsMailbox[0].ID); err == nil { - if resultsEmail.Subject != expectedSubject { - t.Log(resultsEmail.Subject) - t.Fatal("Wrong Subject") - } - if !strings.Contains(resultsEmail.Body.Text, expectedPartialMessage) { - t.Log(resultsEmail.Body.Text) - t.Fatal("Wrong Body message") - } - } - } - } - } -} - -func TestSendMfaChangeEmail(t *testing.T) { - a := Global() - if testing.Short() { - t.SkipNow() - } - a.Setup() - - var email string = "test@example.com" - var locale string = "en" - var siteURL string = "http://test.mattermost.io" - var activated bool = true - var expectedPartialMessage string = "Multi-factor authentication has been added to your account on " + siteURL + "." - var expectedSubject string = "[" + utils.Cfg.TeamSettings.SiteName + "] Your MFA has been updated" - - //Delete all the messages before check the sample email - utils.DeleteMailBox(email) - - if err := SendMfaChangeEmail(email, activated, locale, siteURL); err != nil { - t.Log(err) - t.Fatal("Should send change username email") - } else { - //Check if the email was send to the rigth email address - var resultsMailbox utils.JSONMessageHeaderInbucket - err := utils.RetryInbucket(5, func() error { - var err error - resultsMailbox, err = utils.GetMailBox(email) - return err - }) - if err != nil { - t.Log(err) - t.Log("No email was received, maybe due load on the server. Disabling this verification") - } - if err == nil && len(resultsMailbox) > 0 { - if !strings.ContainsAny(resultsMailbox[0].To[0], email) { - t.Fatal("Wrong To recipient") - } else { - if resultsEmail, err := utils.GetMessageFromMailbox(email, resultsMailbox[0].ID); err == nil { - if resultsEmail.Subject != expectedSubject { - t.Log(resultsEmail.Subject) - t.Fatal("Wrong Subject") - } - if !strings.Contains(resultsEmail.Body.Text, expectedPartialMessage) { - t.Log(resultsEmail.Body.Text) - t.Fatal("Wrong Body message") - } - } - } - } - } - - activated = false - expectedPartialMessage = "Multi-factor authentication has been removed from your account on " + siteURL + "." - utils.DeleteMailBox(email) - - if err := SendMfaChangeEmail(email, activated, locale, siteURL); err != nil { - t.Log(err) - t.Fatal("Should send change username email") - } else { - //Check if the email was send to the rigth email address - var resultsMailbox utils.JSONMessageHeaderInbucket - err := utils.RetryInbucket(5, func() error { - var err error - resultsMailbox, err = utils.GetMailBox(email) - return err - }) - if err != nil { - t.Log(err) - t.Log("No email was received, maybe due load on the server. Disabling this verification") - } - if err == nil && len(resultsMailbox) > 0 { - if !strings.ContainsAny(resultsMailbox[0].To[0], email) { - t.Fatal("Wrong To recipient") - } else { - if resultsEmail, err := utils.GetMessageFromMailbox(email, resultsMailbox[0].ID); err == nil { - if !strings.Contains(resultsEmail.Subject, expectedSubject) { - t.Log(resultsEmail.Subject) - t.Fatal("Wrong Subject") - } - if !strings.Contains(resultsEmail.Body.Text, expectedPartialMessage) { - t.Log(resultsEmail.Body.Text) - t.Fatal("Wrong Body message") - } - } - } - } - } -} - -func TestSendInviteEmails(t *testing.T) { - a := Global() - if testing.Short() { - t.SkipNow() - } - th := a.Setup().InitBasic() - - var email1 string = "test1@example.com" - var email2 string = "test2@example.com" - var senderName string = "TheBoss" - var siteURL string = "http://test.mattermost.io" - invites := []string{email1, email2} - var expectedPartialMessage string = "The team member *" + senderName + "* , has invited you to join *" + th.BasicTeam.DisplayName + "*" - var expectedSubject string = "[" + utils.Cfg.TeamSettings.SiteName + "] " + senderName + " invited you to join " + th.BasicTeam.DisplayName + " Team" - - //Delete all the messages before check the sample email - utils.DeleteMailBox(email1) - utils.DeleteMailBox(email2) - - SendInviteEmails(th.BasicTeam, senderName, invites, siteURL) - - //Check if the email was send to the rigth email address to email1 - var resultsMailbox utils.JSONMessageHeaderInbucket - err := utils.RetryInbucket(5, func() error { - var err error - resultsMailbox, err = utils.GetMailBox(email1) - return err - }) - if err != nil { - t.Log(err) - t.Log("No email was received, maybe due load on the server. Disabling this verification") - } - if err == nil && len(resultsMailbox) > 0 { - if !strings.ContainsAny(resultsMailbox[0].To[0], email1) { - t.Fatal("Wrong To recipient") - } else { - if resultsEmail, err := utils.GetMessageFromMailbox(email1, resultsMailbox[0].ID); err == nil { - if resultsEmail.Subject != expectedSubject { - t.Log(resultsEmail.Subject) - t.Log(expectedSubject) - t.Fatal("Wrong Subject") - } - if !strings.Contains(resultsEmail.Body.Text, expectedPartialMessage) { - t.Log(resultsEmail.Body.Text) - t.Fatal("Wrong Body message") - } - } - } - } - - //Check if the email was send to the rigth email address to email2 - err = utils.RetryInbucket(5, func() error { - var err error - resultsMailbox, err = utils.GetMailBox(email2) - return err - }) - if err != nil { - t.Log(err) - t.Log("No email was received, maybe due load on the server. Disabling this verification") - } - if err == nil && len(resultsMailbox) > 0 { - if !strings.ContainsAny(resultsMailbox[0].To[0], email2) { - t.Fatal("Wrong To recipient") - } else { - if resultsEmail, err := utils.GetMessageFromMailbox(email2, resultsMailbox[0].ID); err == nil { - if !strings.Contains(resultsEmail.Subject, expectedSubject) { - t.Log(resultsEmail.Subject) - t.Log(expectedSubject) - t.Fatal("Wrong Subject") - } - if !strings.Contains(resultsEmail.Body.Text, expectedPartialMessage) { - t.Log(resultsEmail.Body.Text) - t.Fatal("Wrong Body message") - } - } - } - } -} - -func TestSendPasswordReset(t *testing.T) { - a := Global() - if testing.Short() { - t.SkipNow() - } - th := a.Setup().InitBasic() - - var siteURL string = "http://test.mattermost.io" - // var locale string = "en" - var expectedPartialMessage string = "To change your password" - var expectedSubject string = "[" + utils.Cfg.TeamSettings.SiteName + "] Reset your password" - - //Delete all the messages before check the sample email - utils.DeleteMailBox(th.BasicUser.Email) - - if _, err := a.SendPasswordReset(th.BasicUser.Email, siteURL); err != nil { - t.Log(err) - t.Fatal("Should send change username email") - } else { - //Check if the email was send to the rigth email address - if resultsMailbox, err := utils.GetMailBox(th.BasicUser.Email); err != nil && !strings.ContainsAny(resultsMailbox[0].To[0], th.BasicUser.Email) { - t.Fatal("Wrong To recipient") - } else { - if resultsEmail, err := utils.GetMessageFromMailbox(th.BasicUser.Email, resultsMailbox[0].ID); err == nil { - if resultsEmail.Subject != expectedSubject { - t.Log(resultsEmail.Subject) - t.Fatal("Wrong Subject") - } - if !strings.Contains(resultsEmail.Body.Text, expectedPartialMessage) { - t.Log(resultsEmail.Body.Text) - t.Fatal("Wrong Body message") - } - loc := strings.Index(resultsEmail.Body.Text, "token=") - if loc == -1 { - t.Log(resultsEmail.Body.Text) - t.Fatal("Code not found in email") - } - loc += 6 - recoveryTokenString := resultsEmail.Body.Text[loc : loc+model.TOKEN_SIZE] - var recoveryToken *model.Token - if result := <-a.Srv.Store.Token().GetByToken(recoveryTokenString); result.Err != nil { - t.Log(recoveryTokenString) - t.Fatal(result.Err) - } else { - recoveryToken = result.Data.(*model.Token) - if !strings.Contains(resultsEmail.Body.Text, recoveryToken.Token) { - t.Log(resultsEmail.Body.Text) - t.Log(recoveryToken.Token) - t.Fatal("Received wrong recovery code") - } - } - } - } - } -}*/ diff --git a/app/file_test.go b/app/file_test.go index e921eb4d9..62511ceea 100644 --- a/app/file_test.go +++ b/app/file_test.go @@ -36,8 +36,7 @@ func TestGeneratePublicLinkHash(t *testing.T) { } func TestDoUploadFile(t *testing.T) { - a := Global() - a.Setup() + th := Setup() teamId := model.NewId() channelId := model.NewId() @@ -45,12 +44,12 @@ func TestDoUploadFile(t *testing.T) { filename := "test" data := []byte("abcd") - info1, err := a.DoUploadFile(time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamId, channelId, userId, filename, data) + info1, err := th.App.DoUploadFile(time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamId, channelId, userId, filename, data) if err != nil { t.Fatal(err) } else { defer func() { - <-a.Srv.Store.FileInfo().PermanentDelete(info1.Id) + <-th.App.Srv.Store.FileInfo().PermanentDelete(info1.Id) utils.RemoveFile(info1.Path) }() } @@ -59,12 +58,12 @@ func TestDoUploadFile(t *testing.T) { t.Fatal("stored file at incorrect path", info1.Path) } - info2, err := a.DoUploadFile(time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamId, channelId, userId, filename, data) + info2, err := th.App.DoUploadFile(time.Date(2007, 2, 4, 1, 2, 3, 4, time.Local), teamId, channelId, userId, filename, data) if err != nil { t.Fatal(err) } else { defer func() { - <-a.Srv.Store.FileInfo().PermanentDelete(info2.Id) + <-th.App.Srv.Store.FileInfo().PermanentDelete(info2.Id) utils.RemoveFile(info2.Path) }() } @@ -73,12 +72,12 @@ func TestDoUploadFile(t *testing.T) { t.Fatal("stored file at incorrect path", info2.Path) } - info3, err := a.DoUploadFile(time.Date(2008, 3, 5, 1, 2, 3, 4, time.Local), teamId, channelId, userId, filename, data) + info3, err := th.App.DoUploadFile(time.Date(2008, 3, 5, 1, 2, 3, 4, time.Local), teamId, channelId, userId, filename, data) if err != nil { t.Fatal(err) } else { defer func() { - <-a.Srv.Store.FileInfo().PermanentDelete(info3.Id) + <-th.App.Srv.Store.FileInfo().PermanentDelete(info3.Id) utils.RemoveFile(info3.Path) }() } diff --git a/app/import_test.go b/app/import_test.go index 8ea49da20..86485900d 100644 --- a/app/import_test.go +++ b/app/import_test.go @@ -29,8 +29,7 @@ func ptrBool(b bool) *bool { return &b } -func checkPreference(t *testing.T, userId string, category string, name string, value string) { - a := Global() +func checkPreference(t *testing.T, a *App, userId string, category string, name string, value string) { if res := <-a.Srv.Store.Preference().GetCategory(userId, category); res.Err != nil { debug.PrintStack() t.Fatalf("Failed to get preferences for user %v with category %v", userId, category) @@ -966,12 +965,11 @@ func TestImportValidateDirectPostImportData(t *testing.T) { } func TestImportImportTeam(t *testing.T) { - a := Global() - _ = a.Setup() + th := Setup() // Check how many teams are in the database. var teamsCount int64 - if r := <-a.Srv.Store.Team().AnalyticsTeamCount(); r.Err == nil { + if r := <-th.App.Srv.Store.Team().AnalyticsTeamCount(); r.Err == nil { teamsCount = r.Data.(int64) } else { t.Fatalf("Failed to get team count.") @@ -986,18 +984,18 @@ func TestImportImportTeam(t *testing.T) { } // Try importing an invalid team in dryRun mode. - if err := a.ImportTeam(&data, true); err == nil { + if err := th.App.ImportTeam(&data, true); err == nil { t.Fatalf("Should have received an error importing an invalid team.") } // Do a valid team in dry-run mode. data.Type = ptrStr("O") - if err := a.ImportTeam(&data, true); err != nil { + if err := th.App.ImportTeam(&data, true); err != nil { t.Fatalf("Received an error validating valid team.") } // Check that no more teams are in the DB. - if r := <-a.Srv.Store.Team().AnalyticsTeamCount(); r.Err == nil { + if r := <-th.App.Srv.Store.Team().AnalyticsTeamCount(); r.Err == nil { if r.Data.(int64) != teamsCount { t.Fatalf("Teams got persisted in dry run mode.") } @@ -1007,12 +1005,12 @@ func TestImportImportTeam(t *testing.T) { // Do an invalid team in apply mode, check db changes. data.Type = ptrStr("XYZ") - if err := a.ImportTeam(&data, false); err == nil { + if err := th.App.ImportTeam(&data, false); err == nil { t.Fatalf("Import should have failed on invalid team.") } // Check that no more teams are in the DB. - if r := <-a.Srv.Store.Team().AnalyticsTeamCount(); r.Err == nil { + if r := <-th.App.Srv.Store.Team().AnalyticsTeamCount(); r.Err == nil { if r.Data.(int64) != teamsCount { t.Fatalf("Invalid team got persisted.") } @@ -1022,12 +1020,12 @@ func TestImportImportTeam(t *testing.T) { // Do a valid team in apply mode, check db changes. data.Type = ptrStr("O") - if err := a.ImportTeam(&data, false); err != nil { + if err := th.App.ImportTeam(&data, false); err != nil { t.Fatalf("Received an error importing valid team.") } // Check that one more team is in the DB. - if r := <-a.Srv.Store.Team().AnalyticsTeamCount(); r.Err == nil { + if r := <-th.App.Srv.Store.Team().AnalyticsTeamCount(); r.Err == nil { if r.Data.(int64)-1 != teamsCount { t.Fatalf("Team did not get saved in apply run mode. analytics=%v teamcount=%v", r.Data.(int64), teamsCount) } @@ -1036,7 +1034,7 @@ func TestImportImportTeam(t *testing.T) { } // Get the team and check that all the fields are correct. - if team, err := a.GetTeamByName(*data.Name); err != nil { + if team, err := th.App.GetTeamByName(*data.Name); err != nil { t.Fatalf("Failed to get team from database.") } else { if team.DisplayName != *data.DisplayName || team.Type != *data.Type || team.Description != *data.Description || team.AllowOpenInvite != *data.AllowOpenInvite { @@ -1052,11 +1050,11 @@ func TestImportImportTeam(t *testing.T) { // Check that the original number of teams are again in the DB (because this query doesn't include deleted). data.Type = ptrStr("O") - if err := a.ImportTeam(&data, false); err != nil { + if err := th.App.ImportTeam(&data, false); err != nil { t.Fatalf("Received an error importing updated valid team.") } - if r := <-a.Srv.Store.Team().AnalyticsTeamCount(); r.Err == nil { + if r := <-th.App.Srv.Store.Team().AnalyticsTeamCount(); r.Err == nil { if r.Data.(int64)-1 != teamsCount { t.Fatalf("Team alterations did not get saved in apply run mode. analytics=%v teamcount=%v", r.Data.(int64), teamsCount) } @@ -1065,7 +1063,7 @@ func TestImportImportTeam(t *testing.T) { } // Get the team and check that all fields are correct. - if team, err := a.GetTeamByName(*data.Name); err != nil { + if team, err := th.App.GetTeamByName(*data.Name); err != nil { t.Fatalf("Failed to get team from database.") } else { if team.DisplayName != *data.DisplayName || team.Type != *data.Type || team.Description != *data.Description || team.AllowOpenInvite != *data.AllowOpenInvite { @@ -1075,24 +1073,23 @@ func TestImportImportTeam(t *testing.T) { } func TestImportImportChannel(t *testing.T) { - a := Global() - _ = a.Setup() + th := Setup() // Import a Team. teamName := model.NewId() - a.ImportTeam(&TeamImportData{ + th.App.ImportTeam(&TeamImportData{ Name: &teamName, DisplayName: ptrStr("Display Name"), Type: ptrStr("O"), }, false) - team, err := a.GetTeamByName(teamName) + team, err := th.App.GetTeamByName(teamName) if err != nil { t.Fatalf("Failed to get team from database.") } // Check how many channels are in the database. var channelCount int64 - if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { + if r := <-th.App.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { channelCount = r.Data.(int64) } else { t.Fatalf("Failed to get team count.") @@ -1106,12 +1103,12 @@ func TestImportImportChannel(t *testing.T) { Header: ptrStr("Channe Header"), Purpose: ptrStr("Channel Purpose"), } - if err := a.ImportChannel(&data, true); err == nil { + if err := th.App.ImportChannel(&data, true); err == nil { t.Fatalf("Expected error due to invalid name.") } // Check that no more channels are in the DB. - if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { + if r := <-th.App.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { if r.Data.(int64) != channelCount { t.Fatalf("Channels got persisted in dry run mode.") } @@ -1122,12 +1119,12 @@ func TestImportImportChannel(t *testing.T) { // Do a valid channel with a nonexistent team in dry-run mode. data.Name = ptrStr("channelname") data.Team = ptrStr(model.NewId()) - if err := a.ImportChannel(&data, true); err != nil { + if err := th.App.ImportChannel(&data, true); err != nil { t.Fatalf("Expected success as cannot validate channel name in dry run mode.") } // Check that no more channels are in the DB. - if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { + if r := <-th.App.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { if r.Data.(int64) != channelCount { t.Fatalf("Channels got persisted in dry run mode.") } @@ -1137,12 +1134,12 @@ func TestImportImportChannel(t *testing.T) { // Do a valid channel in dry-run mode. data.Team = &teamName - if err := a.ImportChannel(&data, true); err != nil { + if err := th.App.ImportChannel(&data, true); err != nil { t.Fatalf("Expected success as valid team.") } // Check that no more channels are in the DB. - if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { + if r := <-th.App.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { if r.Data.(int64) != channelCount { t.Fatalf("Channels got persisted in dry run mode.") } @@ -1152,12 +1149,12 @@ func TestImportImportChannel(t *testing.T) { // Do an invalid channel in apply mode. data.Name = nil - if err := a.ImportChannel(&data, false); err == nil { + if err := th.App.ImportChannel(&data, false); err == nil { t.Fatalf("Expected error due to invalid name (apply mode).") } // Check that no more channels are in the DB. - if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { + if r := <-th.App.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { if r.Data.(int64) != channelCount { t.Fatalf("Invalid channel got persisted in apply mode.") } @@ -1168,12 +1165,12 @@ func TestImportImportChannel(t *testing.T) { // Do a valid channel in apply mode with a nonexistant team. data.Name = ptrStr("channelname") data.Team = ptrStr(model.NewId()) - if err := a.ImportChannel(&data, false); err == nil { + if err := th.App.ImportChannel(&data, false); err == nil { t.Fatalf("Expected error due to non-existant team (apply mode).") } // Check that no more channels are in the DB. - if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { + if r := <-th.App.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { if r.Data.(int64) != channelCount { t.Fatalf("Invalid team channel got persisted in apply mode.") } @@ -1183,12 +1180,12 @@ func TestImportImportChannel(t *testing.T) { // Do a valid channel in apply mode. data.Team = &teamName - if err := a.ImportChannel(&data, false); err != nil { + if err := th.App.ImportChannel(&data, false); err != nil { t.Fatalf("Expected success in apply mode: %v", err.Error()) } // Check that no more channels are in the DB. - if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { + if r := <-th.App.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { if r.Data.(int64) != channelCount+1 { t.Fatalf("Channels did not get persisted in apply mode: found %v expected %v + 1", r.Data.(int64), channelCount) } @@ -1197,7 +1194,7 @@ func TestImportImportChannel(t *testing.T) { } // Get the Channel and check all the fields are correct. - if channel, err := a.GetChannelByName(*data.Name, team.Id); err != nil { + if channel, err := th.App.GetChannelByName(*data.Name, team.Id); err != nil { t.Fatalf("Failed to get channel from database.") } else { if channel.Name != *data.Name || channel.DisplayName != *data.DisplayName || channel.Type != *data.Type || channel.Header != *data.Header || channel.Purpose != *data.Purpose { @@ -1210,12 +1207,12 @@ func TestImportImportChannel(t *testing.T) { data.Type = ptrStr(model.CHANNEL_PRIVATE) data.Header = ptrStr("New Header") data.Purpose = ptrStr("New Purpose") - if err := a.ImportChannel(&data, false); err != nil { + if err := th.App.ImportChannel(&data, false); err != nil { t.Fatalf("Expected success in apply mode: %v", err.Error()) } // Check channel count the same. - if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { + if r := <-th.App.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil { if r.Data.(int64) != channelCount { t.Fatalf("Updated channel did not get correctly persisted in apply mode.") } @@ -1224,7 +1221,7 @@ func TestImportImportChannel(t *testing.T) { } // Get the Channel and check all the fields are correct. - if channel, err := a.GetChannelByName(*data.Name, team.Id); err != nil { + if channel, err := th.App.GetChannelByName(*data.Name, team.Id); err != nil { t.Fatalf("Failed to get channel from database.") } else { if channel.Name != *data.Name || channel.DisplayName != *data.DisplayName || channel.Type != *data.Type || channel.Header != *data.Header || channel.Purpose != *data.Purpose { @@ -1235,12 +1232,11 @@ func TestImportImportChannel(t *testing.T) { } func TestImportImportUser(t *testing.T) { - a := Global() - _ = a.Setup() + th := Setup() // Check how many users are in the database. var userCount int64 - if r := <-a.Srv.Store.User().GetTotalUsersCount(); r.Err == nil { + if r := <-th.App.Srv.Store.User().GetTotalUsersCount(); r.Err == nil { userCount = r.Data.(int64) } else { t.Fatalf("Failed to get user count.") @@ -1250,12 +1246,12 @@ func TestImportImportUser(t *testing.T) { data := UserImportData{ Username: ptrStr(model.NewId()), } - if err := a.ImportUser(&data, true); err == nil { + if err := th.App.ImportUser(&data, true); err == nil { t.Fatalf("Should have failed to import invalid user.") } // Check that no more users are in the DB. - if r := <-a.Srv.Store.User().GetTotalUsersCount(); r.Err == nil { + if r := <-th.App.Srv.Store.User().GetTotalUsersCount(); r.Err == nil { if r.Data.(int64) != userCount { t.Fatalf("Unexpected number of users") } @@ -1268,12 +1264,12 @@ func TestImportImportUser(t *testing.T) { Username: ptrStr(model.NewId()), Email: ptrStr(model.NewId() + "@example.com"), } - if err := a.ImportUser(&data, true); err != nil { + if err := th.App.ImportUser(&data, true); err != nil { t.Fatalf("Should have succeeded to import valid user.") } // Check that no more users are in the DB. - if r := <-a.Srv.Store.User().GetTotalUsersCount(); r.Err == nil { + if r := <-th.App.Srv.Store.User().GetTotalUsersCount(); r.Err == nil { if r.Data.(int64) != userCount { t.Fatalf("Unexpected number of users") } @@ -1285,12 +1281,12 @@ func TestImportImportUser(t *testing.T) { data = UserImportData{ Username: ptrStr(model.NewId()), } - if err := a.ImportUser(&data, false); err == nil { + if err := th.App.ImportUser(&data, false); err == nil { t.Fatalf("Should have failed to import invalid user.") } // Check that no more users are in the DB. - if r := <-a.Srv.Store.User().GetTotalUsersCount(); r.Err == nil { + if r := <-th.App.Srv.Store.User().GetTotalUsersCount(); r.Err == nil { if r.Data.(int64) != userCount { t.Fatalf("Unexpected number of users") } @@ -1308,12 +1304,12 @@ func TestImportImportUser(t *testing.T) { LastName: ptrStr(model.NewId()), Position: ptrStr(model.NewId()), } - if err := a.ImportUser(&data, false); err != nil { + if err := th.App.ImportUser(&data, false); err != nil { t.Fatalf("Should have succeeded to import valid user.") } // Check that one more user is in the DB. - if r := <-a.Srv.Store.User().GetTotalUsersCount(); r.Err == nil { + if r := <-th.App.Srv.Store.User().GetTotalUsersCount(); r.Err == nil { if r.Data.(int64) != userCount+1 { t.Fatalf("Unexpected number of users") } @@ -1322,7 +1318,7 @@ func TestImportImportUser(t *testing.T) { } // Get the user and check all the fields are correct. - if user, err := a.GetUserByUsername(username); err != nil { + if user, err := th.App.GetUserByUsername(username); err != nil { t.Fatalf("Failed to get user from database.") } else { if user.Email != *data.Email || user.Nickname != *data.Nickname || user.FirstName != *data.FirstName || user.LastName != *data.LastName || user.Position != *data.Position { @@ -1364,12 +1360,12 @@ func TestImportImportUser(t *testing.T) { data.Position = ptrStr(model.NewId()) data.Roles = ptrStr("system_admin system_user") data.Locale = ptrStr("zh_CN") - if err := a.ImportUser(&data, false); err != nil { + if err := th.App.ImportUser(&data, false); err != nil { t.Fatalf("Should have succeeded to update valid user %v", err) } // Check user count the same. - if r := <-a.Srv.Store.User().GetTotalUsersCount(); r.Err == nil { + if r := <-th.App.Srv.Store.User().GetTotalUsersCount(); r.Err == nil { if r.Data.(int64) != userCount+1 { t.Fatalf("Unexpected number of users") } @@ -1378,7 +1374,7 @@ func TestImportImportUser(t *testing.T) { } // Get the user and check all the fields are correct. - if user, err := a.GetUserByUsername(username); err != nil { + if user, err := th.App.GetUserByUsername(username); err != nil { t.Fatalf("Failed to get user from database.") } else { if user.Email != *data.Email || user.Nickname != *data.Nickname || user.FirstName != *data.FirstName || user.LastName != *data.LastName || user.Position != *data.Position { @@ -1412,22 +1408,22 @@ func TestImportImportUser(t *testing.T) { // Check Password and AuthData together. data.Password = ptrStr("PasswordTest") - if err := a.ImportUser(&data, false); err == nil { + if err := th.App.ImportUser(&data, false); err == nil { t.Fatalf("Should have failed to import invalid user.") } data.AuthData = nil - if err := a.ImportUser(&data, false); err != nil { + if err := th.App.ImportUser(&data, false); err != nil { t.Fatalf("Should have succeeded to update valid user %v", err) } data.Password = ptrStr("") - if err := a.ImportUser(&data, false); err == nil { + if err := th.App.ImportUser(&data, false); err == nil { t.Fatalf("Should have failed to import invalid user.") } data.Password = ptrStr(strings.Repeat("0123456789", 10)) - if err := a.ImportUser(&data, false); err == nil { + if err := th.App.ImportUser(&data, false); err == nil { t.Fatalf("Should have failed to import invalid user.") } @@ -1435,24 +1431,24 @@ func TestImportImportUser(t *testing.T) { // Test team and channel memberships teamName := model.NewId() - a.ImportTeam(&TeamImportData{ + th.App.ImportTeam(&TeamImportData{ Name: &teamName, DisplayName: ptrStr("Display Name"), Type: ptrStr("O"), }, false) - team, err := a.GetTeamByName(teamName) + team, err := th.App.GetTeamByName(teamName) if err != nil { t.Fatalf("Failed to get team from database.") } channelName := model.NewId() - a.ImportChannel(&ChannelImportData{ + th.App.ImportChannel(&ChannelImportData{ Team: &teamName, Name: &channelName, DisplayName: ptrStr("Display Name"), Type: ptrStr("O"), }, false) - channel, err := a.GetChannelByName(channelName, team.Id) + channel, err := th.App.GetChannelByName(channelName, team.Id) if err != nil { t.Fatalf("Failed to get channel from database.") } @@ -1467,13 +1463,13 @@ func TestImportImportUser(t *testing.T) { Position: ptrStr(model.NewId()), } - teamMembers, err := a.GetTeamMembers(team.Id, 0, 1000) + teamMembers, err := th.App.GetTeamMembers(team.Id, 0, 1000) if err != nil { t.Fatalf("Failed to get team member count") } teamMemberCount := len(teamMembers) - channelMemberCount, err := a.GetChannelMemberCount(channel.Id) + channelMemberCount, err := th.App.GetChannelMemberCount(channel.Id) if err != nil { t.Fatalf("Failed to get channel member count") } @@ -1489,7 +1485,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - if err := a.ImportUser(&data, true); err == nil { + if err := th.App.ImportUser(&data, true); err == nil { t.Fatalf("Should have failed.") } @@ -1504,7 +1500,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - if err := a.ImportUser(&data, true); err == nil { + if err := th.App.ImportUser(&data, true); err == nil { t.Fatalf("Should have failed.") } @@ -1519,7 +1515,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - if err := a.ImportUser(&data, true); err == nil { + if err := th.App.ImportUser(&data, true); err == nil { t.Fatalf("Should have failed.") } @@ -1534,7 +1530,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - if err := a.ImportUser(&data, true); err != nil { + if err := th.App.ImportUser(&data, true); err != nil { t.Fatalf("Should have succeeded.") } @@ -1549,18 +1545,18 @@ func TestImportImportUser(t *testing.T) { }, }, } - if err := a.ImportUser(&data, true); err != nil { + if err := th.App.ImportUser(&data, true); err != nil { t.Fatalf("Should have succeeded.") } // Check no new member objects were created because dry run mode. - if tmc, err := a.GetTeamMembers(team.Id, 0, 1000); err != nil { + if tmc, err := th.App.GetTeamMembers(team.Id, 0, 1000); err != nil { t.Fatalf("Failed to get Team Member Count") } else if len(tmc) != teamMemberCount { t.Fatalf("Number of team members not as expected") } - if cmc, err := a.GetChannelMemberCount(channel.Id); err != nil { + if cmc, err := th.App.GetChannelMemberCount(channel.Id); err != nil { t.Fatalf("Failed to get Channel Member Count") } else if cmc != channelMemberCount { t.Fatalf("Number of channel members not as expected") @@ -1577,7 +1573,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - if err := a.ImportUser(&data, false); err == nil { + if err := th.App.ImportUser(&data, false); err == nil { t.Fatalf("Should have failed.") } @@ -1592,7 +1588,7 @@ func TestImportImportUser(t *testing.T) { }, }, } - if err := a.ImportUser(&data, false); err == nil { + if err := th.App.ImportUser(&data, false); err == nil { t.Fatalf("Should have failed.") } @@ -1607,18 +1603,18 @@ func TestImportImportUser(t *testing.T) { }, }, } - if err := a.ImportUser(&data, false); err == nil { + if err := th.App.ImportUser(&data, false); err == nil { t.Fatalf("Should have failed.") } // Check no new member objects were created because all tests should have failed so far. - if tmc, err := a.GetTeamMembers(team.Id, 0, 1000); err != nil { + if tmc, err := th.App.GetTeamMembers(team.Id, 0, 1000); err != nil { t.Fatalf("Failed to get Team Member Count") } else if len(tmc) != teamMemberCount { t.Fatalf("Number of team members not as expected") } - if cmc, err := a.GetChannelMemberCount(channel.Id); err != nil { + if cmc, err := th.App.GetChannelMemberCount(channel.Id); err != nil { t.Fatalf("Failed to get Channel Member Count") } else if cmc != channelMemberCount { t.Fatalf("Number of channel members not as expected") @@ -1635,29 +1631,29 @@ func TestImportImportUser(t *testing.T) { }, }, } - if err := a.ImportUser(&data, false); err == nil { + if err := th.App.ImportUser(&data, false); err == nil { t.Fatalf("Should have failed.") } // Check only new team member object created because dry run mode. - if tmc, err := a.GetTeamMembers(team.Id, 0, 1000); err != nil { + if tmc, err := th.App.GetTeamMembers(team.Id, 0, 1000); err != nil { t.Fatalf("Failed to get Team Member Count") } else if len(tmc) != teamMemberCount+1 { t.Fatalf("Number of team members not as expected") } - if cmc, err := a.GetChannelMemberCount(channel.Id); err != nil { + if cmc, err := th.App.GetChannelMemberCount(channel.Id); err != nil { t.Fatalf("Failed to get Channel Member Count") } else if cmc != channelMemberCount { t.Fatalf("Number of channel members not as expected") } // Check team member properties. - user, err := a.GetUserByUsername(username) + user, err := th.App.GetUserByUsername(username) if err != nil { t.Fatalf("Failed to get user from database.") } - if teamMember, err := a.GetTeamMember(team.Id, user.Id); err != nil { + if teamMember, err := th.App.GetTeamMember(team.Id, user.Id); err != nil { t.Fatalf("Failed to get team member from database.") } else if teamMember.Roles != "team_user" { t.Fatalf("Team member properties not as expected") @@ -1674,25 +1670,25 @@ func TestImportImportUser(t *testing.T) { }, }, } - if err := a.ImportUser(&data, false); err != nil { + if err := th.App.ImportUser(&data, false); err != nil { t.Fatalf("Should have succeeded.") } // Check only new channel member object created because dry run mode. - if tmc, err := a.GetTeamMembers(team.Id, 0, 1000); err != nil { + if tmc, err := th.App.GetTeamMembers(team.Id, 0, 1000); err != nil { t.Fatalf("Failed to get Team Member Count") } else if len(tmc) != teamMemberCount+1 { t.Fatalf("Number of team members not as expected") } - if cmc, err := a.GetChannelMemberCount(channel.Id); err != nil { + if cmc, err := th.App.GetChannelMemberCount(channel.Id); err != nil { t.Fatalf("Failed to get Channel Member Count") } else if cmc != channelMemberCount+1 { t.Fatalf("Number of channel members not as expected") } // Check channel member properties. - if channelMember, err := a.GetChannelMember(channel.Id, user.Id); err != nil { + if channelMember, err := th.App.GetChannelMember(channel.Id, user.Id); err != nil { t.Fatalf("Failed to get channel member from database.") } else if channelMember.Roles != "channel_user" || channelMember.NotifyProps[model.DESKTOP_NOTIFY_PROP] != "default" || channelMember.NotifyProps[model.PUSH_NOTIFY_PROP] != "default" || channelMember.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP] != "all" { t.Fatalf("Channel member properties not as expected") @@ -1717,33 +1713,33 @@ func TestImportImportUser(t *testing.T) { }, }, } - if err := a.ImportUser(&data, false); err != nil { + if err := th.App.ImportUser(&data, false); err != nil { t.Fatalf("Should have succeeded.") } // Check both member properties. - if teamMember, err := a.GetTeamMember(team.Id, user.Id); err != nil { + if teamMember, err := th.App.GetTeamMember(team.Id, user.Id); err != nil { t.Fatalf("Failed to get team member from database.") } else if teamMember.Roles != "team_user team_admin" { t.Fatalf("Team member properties not as expected: %v", teamMember.Roles) } - if channelMember, err := a.GetChannelMember(channel.Id, user.Id); err != nil { + if channelMember, err := th.App.GetChannelMember(channel.Id, user.Id); err != nil { t.Fatalf("Failed to get channel member Desktop from database.") } else if channelMember.Roles != "channel_user channel_admin" || channelMember.NotifyProps[model.DESKTOP_NOTIFY_PROP] != model.USER_NOTIFY_MENTION || channelMember.NotifyProps[model.PUSH_NOTIFY_PROP] != model.USER_NOTIFY_MENTION || channelMember.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP] != model.USER_NOTIFY_MENTION { t.Fatalf("Channel member properties not as expected") } - checkPreference(t, user.Id, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id, "true") + checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id, "true") // No more new member objects. - if tmc, err := a.GetTeamMembers(team.Id, 0, 1000); err != nil { + if tmc, err := th.App.GetTeamMembers(team.Id, 0, 1000); err != nil { t.Fatalf("Failed to get Team Member Count") } else if len(tmc) != teamMemberCount+1 { t.Fatalf("Number of team members not as expected") } - if cmc, err := a.GetChannelMemberCount(channel.Id); err != nil { + if cmc, err := th.App.GetChannelMemberCount(channel.Id); err != nil { t.Fatalf("Failed to get Channel Member Count") } else if cmc != channelMemberCount+1 { t.Fatalf("Number of channel members not as expected") @@ -1761,22 +1757,22 @@ func TestImportImportUser(t *testing.T) { ChannelDisplayMode: ptrStr("centered"), TutorialStep: ptrStr("3"), } - if err := a.ImportUser(&data, false); err != nil { + if err := th.App.ImportUser(&data, false); err != nil { t.Fatalf("Should have succeeded.") } // Check their values. - user, err = a.GetUserByUsername(username) + user, err = th.App.GetUserByUsername(username) if err != nil { t.Fatalf("Failed to get user from database.") } - checkPreference(t, user.Id, model.PREFERENCE_CATEGORY_THEME, "", *data.Theme) - checkPreference(t, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, "use_military_time", *data.UseMilitaryTime) - checkPreference(t, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, "collapse_previews", *data.CollapsePreviews) - checkPreference(t, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, "message_display", *data.MessageDisplay) - checkPreference(t, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, "channel_display_mode", *data.ChannelDisplayMode) - checkPreference(t, user.Id, model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, user.Id, *data.TutorialStep) + checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_THEME, "", *data.Theme) + checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, "use_military_time", *data.UseMilitaryTime) + checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, "collapse_previews", *data.CollapsePreviews) + checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, "message_display", *data.MessageDisplay) + checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, "channel_display_mode", *data.ChannelDisplayMode) + checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, user.Id, *data.TutorialStep) // Change those preferences. data = UserImportData{ @@ -1789,17 +1785,17 @@ func TestImportImportUser(t *testing.T) { ChannelDisplayMode: ptrStr("full"), TutorialStep: ptrStr("2"), } - if err := a.ImportUser(&data, false); err != nil { + if err := th.App.ImportUser(&data, false); err != nil { t.Fatalf("Should have succeeded.") } // Check their values again. - checkPreference(t, user.Id, model.PREFERENCE_CATEGORY_THEME, "", *data.Theme) - checkPreference(t, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, "use_military_time", *data.UseMilitaryTime) - checkPreference(t, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, "collapse_previews", *data.CollapsePreviews) - checkPreference(t, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, "message_display", *data.MessageDisplay) - checkPreference(t, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, "channel_display_mode", *data.ChannelDisplayMode) - checkPreference(t, user.Id, model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, user.Id, *data.TutorialStep) + checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_THEME, "", *data.Theme) + checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, "use_military_time", *data.UseMilitaryTime) + checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, "collapse_previews", *data.CollapsePreviews) + checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, "message_display", *data.MessageDisplay) + checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, "channel_display_mode", *data.ChannelDisplayMode) + checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, user.Id, *data.TutorialStep) // Set Notify Props data.NotifyProps = &UserNotifyPropsImportData{ @@ -1813,11 +1809,11 @@ func TestImportImportUser(t *testing.T) { CommentsTrigger: ptrStr(model.COMMENTS_NOTIFY_ROOT), MentionKeys: ptrStr("valid,misc"), } - if err := a.ImportUser(&data, false); err != nil { + if err := th.App.ImportUser(&data, false); err != nil { t.Fatalf("Should have succeeded.") } - user, err = a.GetUserByUsername(username) + user, err = th.App.GetUserByUsername(username) if err != nil { t.Fatalf("Failed to get user from database.") } @@ -1844,11 +1840,11 @@ func TestImportImportUser(t *testing.T) { CommentsTrigger: ptrStr(model.COMMENTS_NOTIFY_ANY), MentionKeys: ptrStr("misc"), } - if err := a.ImportUser(&data, false); err != nil { + if err := th.App.ImportUser(&data, false); err != nil { t.Fatalf("Should have succeeded.") } - user, err = a.GetUserByUsername(username) + user, err = th.App.GetUserByUsername(username) if err != nil { t.Fatalf("Failed to get user from database.") } @@ -1881,11 +1877,11 @@ func TestImportImportUser(t *testing.T) { MentionKeys: ptrStr("misc"), } - if err := a.ImportUser(&data, false); err != nil { + if err := th.App.ImportUser(&data, false); err != nil { t.Fatalf("Should have succeeded.") } - user, err = a.GetUserByUsername(username) + user, err = th.App.GetUserByUsername(username) if err != nil { t.Fatalf("Failed to get user from database.") } @@ -1901,8 +1897,7 @@ func TestImportImportUser(t *testing.T) { checkNotifyProp(t, user, model.MENTION_KEYS_NOTIFY_PROP, "misc") } -func AssertAllPostsCount(t *testing.T, initialCount int64, change int64, teamName string) { - a := Global() +func AssertAllPostsCount(t *testing.T, a *App, initialCount int64, change int64, teamName string) { if result := <-a.Srv.Store.Post().AnalyticsPostCount(teamName, false, false); result.Err != nil { t.Fatal(result.Err) } else { @@ -1914,48 +1909,47 @@ func AssertAllPostsCount(t *testing.T, initialCount int64, change int64, teamNam } func TestImportImportPost(t *testing.T) { - a := Global() - _ = a.Setup() + th := Setup() // Create a Team. teamName := model.NewId() - a.ImportTeam(&TeamImportData{ + th.App.ImportTeam(&TeamImportData{ Name: &teamName, DisplayName: ptrStr("Display Name"), Type: ptrStr("O"), }, false) - team, err := a.GetTeamByName(teamName) + team, err := th.App.GetTeamByName(teamName) if err != nil { t.Fatalf("Failed to get team from database.") } // Create a Channel. channelName := model.NewId() - a.ImportChannel(&ChannelImportData{ + th.App.ImportChannel(&ChannelImportData{ Team: &teamName, Name: &channelName, DisplayName: ptrStr("Display Name"), Type: ptrStr("O"), }, false) - channel, err := a.GetChannelByName(channelName, team.Id) + channel, err := th.App.GetChannelByName(channelName, team.Id) if err != nil { t.Fatalf("Failed to get channel from database.") } // Create a user. username := model.NewId() - a.ImportUser(&UserImportData{ + th.App.ImportUser(&UserImportData{ Username: &username, Email: ptrStr(model.NewId() + "@example.com"), }, false) - user, err := a.GetUserByUsername(username) + user, err := th.App.GetUserByUsername(username) if err != nil { t.Fatalf("Failed to get user from database.") } // Count the number of posts in the testing team. var initialPostCount int64 - if result := <-a.Srv.Store.Post().AnalyticsPostCount(team.Id, false, false); result.Err != nil { + if result := <-th.App.Srv.Store.Post().AnalyticsPostCount(team.Id, false, false); result.Err != nil { t.Fatal(result.Err) } else { initialPostCount = result.Data.(int64) @@ -1967,10 +1961,10 @@ func TestImportImportPost(t *testing.T) { Channel: &channelName, User: &username, } - if err := a.ImportPost(data, true); err == nil { + if err := th.App.ImportPost(data, true); err == nil { t.Fatalf("Expected error.") } - AssertAllPostsCount(t, initialPostCount, 0, team.Id) + AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id) // Try adding a valid post in dry run mode. data = &PostImportData{ @@ -1980,10 +1974,10 @@ func TestImportImportPost(t *testing.T) { Message: ptrStr("Hello"), CreateAt: ptrInt64(model.GetMillis()), } - if err := a.ImportPost(data, true); err != nil { + if err := th.App.ImportPost(data, true); err != nil { t.Fatalf("Expected success.") } - AssertAllPostsCount(t, initialPostCount, 0, team.Id) + AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id) // Try adding an invalid post in apply mode. data = &PostImportData{ @@ -1992,10 +1986,10 @@ func TestImportImportPost(t *testing.T) { User: &username, CreateAt: ptrInt64(model.GetMillis()), } - if err := a.ImportPost(data, false); err == nil { + if err := th.App.ImportPost(data, false); err == nil { t.Fatalf("Expected error.") } - AssertAllPostsCount(t, initialPostCount, 0, team.Id) + AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id) // Try adding a valid post with invalid team in apply mode. data = &PostImportData{ @@ -2005,10 +1999,10 @@ func TestImportImportPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: ptrInt64(model.GetMillis()), } - if err := a.ImportPost(data, false); err == nil { + if err := th.App.ImportPost(data, false); err == nil { t.Fatalf("Expected error.") } - AssertAllPostsCount(t, initialPostCount, 0, team.Id) + AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id) // Try adding a valid post with invalid channel in apply mode. data = &PostImportData{ @@ -2018,10 +2012,10 @@ func TestImportImportPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: ptrInt64(model.GetMillis()), } - if err := a.ImportPost(data, false); err == nil { + if err := th.App.ImportPost(data, false); err == nil { t.Fatalf("Expected error.") } - AssertAllPostsCount(t, initialPostCount, 0, team.Id) + AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id) // Try adding a valid post with invalid user in apply mode. data = &PostImportData{ @@ -2031,10 +2025,10 @@ func TestImportImportPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: ptrInt64(model.GetMillis()), } - if err := a.ImportPost(data, false); err == nil { + if err := th.App.ImportPost(data, false); err == nil { t.Fatalf("Expected error.") } - AssertAllPostsCount(t, initialPostCount, 0, team.Id) + AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id) // Try adding a valid post in apply mode. time := model.GetMillis() @@ -2045,13 +2039,13 @@ func TestImportImportPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: &time, } - if err := a.ImportPost(data, false); err != nil { + if err := th.App.ImportPost(data, false); err != nil { t.Fatalf("Expected success.") } - AssertAllPostsCount(t, initialPostCount, 1, team.Id) + AssertAllPostsCount(t, th.App, initialPostCount, 1, team.Id) // Check the post values. - if result := <-a.Srv.Store.Post().GetPostsCreatedAt(channel.Id, time); result.Err != nil { + if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(channel.Id, time); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2072,13 +2066,13 @@ func TestImportImportPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: &time, } - if err := a.ImportPost(data, false); err != nil { + if err := th.App.ImportPost(data, false); err != nil { t.Fatalf("Expected success.") } - AssertAllPostsCount(t, initialPostCount, 1, team.Id) + AssertAllPostsCount(t, th.App, initialPostCount, 1, team.Id) // Check the post values. - if result := <-a.Srv.Store.Post().GetPostsCreatedAt(channel.Id, time); result.Err != nil { + if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(channel.Id, time); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2100,10 +2094,10 @@ func TestImportImportPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: &newTime, } - if err := a.ImportPost(data, false); err != nil { + if err := th.App.ImportPost(data, false); err != nil { t.Fatalf("Expected success.") } - AssertAllPostsCount(t, initialPostCount, 2, team.Id) + AssertAllPostsCount(t, th.App, initialPostCount, 2, team.Id) // Save the post with a different message. data = &PostImportData{ @@ -2113,10 +2107,10 @@ func TestImportImportPost(t *testing.T) { Message: ptrStr("Message 2"), CreateAt: &time, } - if err := a.ImportPost(data, false); err != nil { + if err := th.App.ImportPost(data, false); err != nil { t.Fatalf("Expected success.") } - AssertAllPostsCount(t, initialPostCount, 3, team.Id) + AssertAllPostsCount(t, th.App, initialPostCount, 3, team.Id) // Test with hashtags hashtagTime := time + 2 @@ -2127,12 +2121,12 @@ func TestImportImportPost(t *testing.T) { Message: ptrStr("Message 2 #hashtagmashupcity"), CreateAt: &hashtagTime, } - if err := a.ImportPost(data, false); err != nil { + if err := th.App.ImportPost(data, false); err != nil { t.Fatalf("Expected success.") } - AssertAllPostsCount(t, initialPostCount, 4, team.Id) + AssertAllPostsCount(t, th.App, initialPostCount, 4, team.Id) - if result := <-a.Srv.Store.Post().GetPostsCreatedAt(channel.Id, hashtagTime); result.Err != nil { + if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(channel.Id, hashtagTime); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2150,11 +2144,11 @@ func TestImportImportPost(t *testing.T) { // Post with flags. username2 := model.NewId() - a.ImportUser(&UserImportData{ + th.App.ImportUser(&UserImportData{ Username: &username2, Email: ptrStr(model.NewId() + "@example.com"), }, false) - user2, err := a.GetUserByUsername(username2) + user2, err := th.App.GetUserByUsername(username2) if err != nil { t.Fatalf("Failed to get user from database.") } @@ -2171,13 +2165,13 @@ func TestImportImportPost(t *testing.T) { username2, }, } - if err := a.ImportPost(data, false); err != nil { + if err := th.App.ImportPost(data, false); err != nil { t.Fatalf("Expected success.") } - AssertAllPostsCount(t, initialPostCount, 5, team.Id) + AssertAllPostsCount(t, th.App, initialPostCount, 5, team.Id) // Check the post values. - if result := <-a.Srv.Store.Post().GetPostsCreatedAt(channel.Id, flagsTime); result.Err != nil { + if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(channel.Id, flagsTime); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2189,25 +2183,24 @@ func TestImportImportPost(t *testing.T) { t.Fatal("Post properties not as expected") } - checkPreference(t, user.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true") - checkPreference(t, user2.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true") + checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true") + checkPreference(t, th.App, user2.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true") } } func TestImportImportDirectChannel(t *testing.T) { - a := Global() - th := a.Setup().InitBasic() + th := Setup().InitBasic() // Check how many channels are in the database. var directChannelCount int64 - if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_DIRECT); r.Err == nil { + if r := <-th.App.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_DIRECT); r.Err == nil { directChannelCount = r.Data.(int64) } else { t.Fatalf("Failed to get direct channel count.") } var groupChannelCount int64 - if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_GROUP); r.Err == nil { + if r := <-th.App.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_GROUP); r.Err == nil { groupChannelCount = r.Data.(int64) } else { t.Fatalf("Failed to get group channel count.") @@ -2220,26 +2213,26 @@ func TestImportImportDirectChannel(t *testing.T) { }, Header: ptrStr("Channel Header"), } - if err := a.ImportDirectChannel(&data, true); err == nil { + if err := th.App.ImportDirectChannel(&data, true); err == nil { t.Fatalf("Expected error due to invalid name.") } // Check that no more channels are in the DB. - AssertChannelCount(t, model.CHANNEL_DIRECT, directChannelCount) - AssertChannelCount(t, model.CHANNEL_GROUP, groupChannelCount) + AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount) + AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount) // Do a valid DIRECT channel with a nonexistent member in dry-run mode. data.Members = &[]string{ model.NewId(), model.NewId(), } - if err := a.ImportDirectChannel(&data, true); err != nil { + if err := th.App.ImportDirectChannel(&data, true); err != nil { t.Fatalf("Expected success as cannot validate existance of channel members in dry run mode.") } // Check that no more channels are in the DB. - AssertChannelCount(t, model.CHANNEL_DIRECT, directChannelCount) - AssertChannelCount(t, model.CHANNEL_GROUP, groupChannelCount) + AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount) + AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount) // Do a valid GROUP channel with a nonexistent member in dry-run mode. data.Members = &[]string{ @@ -2247,60 +2240,60 @@ func TestImportImportDirectChannel(t *testing.T) { model.NewId(), model.NewId(), } - if err := a.ImportDirectChannel(&data, true); err != nil { + if err := th.App.ImportDirectChannel(&data, true); err != nil { t.Fatalf("Expected success as cannot validate existance of channel members in dry run mode.") } // Check that no more channels are in the DB. - AssertChannelCount(t, model.CHANNEL_DIRECT, directChannelCount) - AssertChannelCount(t, model.CHANNEL_GROUP, groupChannelCount) + AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount) + AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount) // Do an invalid channel in apply mode. data.Members = &[]string{ model.NewId(), } - if err := a.ImportDirectChannel(&data, false); err == nil { + if err := th.App.ImportDirectChannel(&data, false); err == nil { t.Fatalf("Expected error due to invalid member (apply mode).") } // Check that no more channels are in the DB. - AssertChannelCount(t, model.CHANNEL_DIRECT, directChannelCount) - AssertChannelCount(t, model.CHANNEL_GROUP, groupChannelCount) + AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount) + AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount) // Do a valid DIRECT channel. data.Members = &[]string{ th.BasicUser.Username, th.BasicUser2.Username, } - if err := a.ImportDirectChannel(&data, false); err != nil { + if err := th.App.ImportDirectChannel(&data, false); err != nil { t.Fatalf("Expected success: %v", err.Error()) } // Check that one more DIRECT channel is in the DB. - AssertChannelCount(t, model.CHANNEL_DIRECT, directChannelCount+1) - AssertChannelCount(t, model.CHANNEL_GROUP, groupChannelCount) + AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1) + AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount) // Do the same DIRECT channel again. - if err := a.ImportDirectChannel(&data, false); err != nil { + if err := th.App.ImportDirectChannel(&data, false); err != nil { t.Fatalf("Expected success.") } // Check that no more channels are in the DB. - AssertChannelCount(t, model.CHANNEL_DIRECT, directChannelCount+1) - AssertChannelCount(t, model.CHANNEL_GROUP, groupChannelCount) + AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1) + AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount) // Update the channel's HEADER data.Header = ptrStr("New Channel Header 2") - if err := a.ImportDirectChannel(&data, false); err != nil { + if err := th.App.ImportDirectChannel(&data, false); err != nil { t.Fatalf("Expected success.") } // Check that no more channels are in the DB. - AssertChannelCount(t, model.CHANNEL_DIRECT, directChannelCount+1) - AssertChannelCount(t, model.CHANNEL_GROUP, groupChannelCount) + AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1) + AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount) // Get the channel to check that the header was updated. - if channel, err := a.createDirectChannel(th.BasicUser.Id, th.BasicUser2.Id); err == nil || err.Id != store.CHANNEL_EXISTS_ERROR { + if channel, err := th.App.createDirectChannel(th.BasicUser.Id, th.BasicUser2.Id); err == nil || err.Id != store.CHANNEL_EXISTS_ERROR { t.Fatal("Should have got store.CHANNEL_EXISTS_ERROR") } else { if channel.Header != *data.Header { @@ -2316,13 +2309,13 @@ func TestImportImportDirectChannel(t *testing.T) { user3.Username, model.NewId(), } - if err := a.ImportDirectChannel(&data, false); err == nil { + if err := th.App.ImportDirectChannel(&data, false); err == nil { t.Fatalf("Should have failed due to invalid member in list.") } // Check that no more channels are in the DB. - AssertChannelCount(t, model.CHANNEL_DIRECT, directChannelCount+1) - AssertChannelCount(t, model.CHANNEL_GROUP, groupChannelCount) + AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1) + AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount) // Do a valid GROUP channel. data.Members = &[]string{ @@ -2330,32 +2323,32 @@ func TestImportImportDirectChannel(t *testing.T) { th.BasicUser2.Username, user3.Username, } - if err := a.ImportDirectChannel(&data, false); err != nil { + if err := th.App.ImportDirectChannel(&data, false); err != nil { t.Fatalf("Expected success.") } // Check that one more GROUP channel is in the DB. - AssertChannelCount(t, model.CHANNEL_DIRECT, directChannelCount+1) - AssertChannelCount(t, model.CHANNEL_GROUP, groupChannelCount+1) + AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1) + AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount+1) // Do the same DIRECT channel again. - if err := a.ImportDirectChannel(&data, false); err != nil { + if err := th.App.ImportDirectChannel(&data, false); err != nil { t.Fatalf("Expected success.") } // Check that no more channels are in the DB. - AssertChannelCount(t, model.CHANNEL_DIRECT, directChannelCount+1) - AssertChannelCount(t, model.CHANNEL_GROUP, groupChannelCount+1) + AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1) + AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount+1) // Update the channel's HEADER data.Header = ptrStr("New Channel Header 3") - if err := a.ImportDirectChannel(&data, false); err != nil { + if err := th.App.ImportDirectChannel(&data, false); err != nil { t.Fatalf("Expected success.") } // Check that no more channels are in the DB. - AssertChannelCount(t, model.CHANNEL_DIRECT, directChannelCount+1) - AssertChannelCount(t, model.CHANNEL_GROUP, groupChannelCount+1) + AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1) + AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount+1) // Get the channel to check that the header was updated. userIds := []string{ @@ -2363,7 +2356,7 @@ func TestImportImportDirectChannel(t *testing.T) { th.BasicUser2.Id, user3.Id, } - if channel, err := a.createGroupChannel(userIds, th.BasicUser.Id); err.Id != store.CHANNEL_EXISTS_ERROR { + if channel, err := th.App.createGroupChannel(userIds, th.BasicUser.Id); err.Id != store.CHANNEL_EXISTS_ERROR { t.Fatal("Should have got store.CHANNEL_EXISTS_ERROR") } else { if channel.Header != *data.Header { @@ -2380,20 +2373,19 @@ func TestImportImportDirectChannel(t *testing.T) { th.BasicUser.Username, th.BasicUser2.Username, } - if err := a.ImportDirectChannel(&data, false); err != nil { + if err := th.App.ImportDirectChannel(&data, false); err != nil { t.Fatal(err) } - if channel, err := a.createDirectChannel(th.BasicUser.Id, th.BasicUser2.Id); err == nil || err.Id != store.CHANNEL_EXISTS_ERROR { + if channel, err := th.App.createDirectChannel(th.BasicUser.Id, th.BasicUser2.Id); err == nil || err.Id != store.CHANNEL_EXISTS_ERROR { t.Fatal("Should have got store.CHANNEL_EXISTS_ERROR") } else { - checkPreference(t, th.BasicUser.Id, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id, "true") - checkPreference(t, th.BasicUser2.Id, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id, "true") + checkPreference(t, th.App, th.BasicUser.Id, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id, "true") + checkPreference(t, th.App, th.BasicUser2.Id, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id, "true") } } -func AssertChannelCount(t *testing.T, channelType string, expectedCount int64) { - a := Global() +func AssertChannelCount(t *testing.T, a *App, channelType string, expectedCount int64) { if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", channelType); r.Err == nil { count := r.Data.(int64) if count != expectedCount { @@ -2407,8 +2399,7 @@ func AssertChannelCount(t *testing.T, channelType string, expectedCount int64) { } func TestImportImportDirectPost(t *testing.T) { - a := Global() - th := a.Setup().InitBasic() + th := Setup().InitBasic() // Create the DIRECT channel. channelData := DirectChannelImportData{ @@ -2417,13 +2408,13 @@ func TestImportImportDirectPost(t *testing.T) { th.BasicUser2.Username, }, } - if err := a.ImportDirectChannel(&channelData, false); err != nil { + if err := th.App.ImportDirectChannel(&channelData, false); err != nil { t.Fatalf("Expected success: %v", err.Error()) } // Get the channel. var directChannel *model.Channel - if channel, err := a.createDirectChannel(th.BasicUser.Id, th.BasicUser2.Id); err.Id != store.CHANNEL_EXISTS_ERROR { + if channel, err := th.App.createDirectChannel(th.BasicUser.Id, th.BasicUser2.Id); err.Id != store.CHANNEL_EXISTS_ERROR { t.Fatal("Should have got store.CHANNEL_EXISTS_ERROR") } else { directChannel = channel @@ -2431,7 +2422,7 @@ func TestImportImportDirectPost(t *testing.T) { // Get the number of posts in the system. var initialPostCount int64 - if result := <-a.Srv.Store.Post().AnalyticsPostCount("", false, false); result.Err != nil { + if result := <-th.App.Srv.Store.Post().AnalyticsPostCount("", false, false); result.Err != nil { t.Fatal(result.Err) } else { initialPostCount = result.Data.(int64) @@ -2446,10 +2437,10 @@ func TestImportImportDirectPost(t *testing.T) { User: ptrStr(th.BasicUser.Username), CreateAt: ptrInt64(model.GetMillis()), } - if err := a.ImportDirectPost(data, true); err == nil { + if err := th.App.ImportDirectPost(data, true); err == nil { t.Fatalf("Expected error.") } - AssertAllPostsCount(t, initialPostCount, 0, "") + AssertAllPostsCount(t, th.App, initialPostCount, 0, "") // Try adding a valid post in dry run mode. data = &DirectPostImportData{ @@ -2461,10 +2452,10 @@ func TestImportImportDirectPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: ptrInt64(model.GetMillis()), } - if err := a.ImportDirectPost(data, true); err != nil { + if err := th.App.ImportDirectPost(data, true); err != nil { t.Fatalf("Expected success.") } - AssertAllPostsCount(t, initialPostCount, 0, "") + AssertAllPostsCount(t, th.App, initialPostCount, 0, "") // Try adding an invalid post in apply mode. data = &DirectPostImportData{ @@ -2476,10 +2467,10 @@ func TestImportImportDirectPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: ptrInt64(model.GetMillis()), } - if err := a.ImportDirectPost(data, false); err == nil { + if err := th.App.ImportDirectPost(data, false); err == nil { t.Fatalf("Expected error.") } - AssertAllPostsCount(t, initialPostCount, 0, "") + AssertAllPostsCount(t, th.App, initialPostCount, 0, "") // Try adding a valid post in apply mode. data = &DirectPostImportData{ @@ -2491,13 +2482,13 @@ func TestImportImportDirectPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: ptrInt64(model.GetMillis()), } - if err := a.ImportDirectPost(data, false); err != nil { + if err := th.App.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success: %v", err.Error()) } - AssertAllPostsCount(t, initialPostCount, 1, "") + AssertAllPostsCount(t, th.App, initialPostCount, 1, "") // Check the post values. - if result := <-a.Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt); result.Err != nil { + if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2511,13 +2502,13 @@ func TestImportImportDirectPost(t *testing.T) { } // Import the post again. - if err := a.ImportDirectPost(data, false); err != nil { + if err := th.App.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success.") } - AssertAllPostsCount(t, initialPostCount, 1, "") + AssertAllPostsCount(t, th.App, initialPostCount, 1, "") // Check the post values. - if result := <-a.Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt); result.Err != nil { + if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2532,27 +2523,27 @@ func TestImportImportDirectPost(t *testing.T) { // Save the post with a different time. data.CreateAt = ptrInt64(*data.CreateAt + 1) - if err := a.ImportDirectPost(data, false); err != nil { + if err := th.App.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success.") } - AssertAllPostsCount(t, initialPostCount, 2, "") + AssertAllPostsCount(t, th.App, initialPostCount, 2, "") // Save the post with a different message. data.Message = ptrStr("Message 2") - if err := a.ImportDirectPost(data, false); err != nil { + if err := th.App.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success.") } - AssertAllPostsCount(t, initialPostCount, 3, "") + AssertAllPostsCount(t, th.App, initialPostCount, 3, "") // Test with hashtags data.Message = ptrStr("Message 2 #hashtagmashupcity") data.CreateAt = ptrInt64(*data.CreateAt + 1) - if err := a.ImportDirectPost(data, false); err != nil { + if err := th.App.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success.") } - AssertAllPostsCount(t, initialPostCount, 4, "") + AssertAllPostsCount(t, th.App, initialPostCount, 4, "") - if result := <-a.Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt); result.Err != nil { + if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2583,12 +2574,12 @@ func TestImportImportDirectPost(t *testing.T) { CreateAt: ptrInt64(model.GetMillis()), } - if err := a.ImportDirectPost(data, false); err != nil { + if err := th.App.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success: %v", err.Error()) } // Check the post values. - if result := <-a.Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt); result.Err != nil { + if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2596,8 +2587,8 @@ func TestImportImportDirectPost(t *testing.T) { t.Fatal("Unexpected number of posts found.") } post := posts[0] - checkPreference(t, th.BasicUser.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true") - checkPreference(t, th.BasicUser2.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true") + checkPreference(t, th.App, th.BasicUser.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true") + checkPreference(t, th.App, th.BasicUser2.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true") } // ------------------ Group Channel ------------------------- @@ -2611,7 +2602,7 @@ func TestImportImportDirectPost(t *testing.T) { user3.Username, }, } - if err := a.ImportDirectChannel(&channelData, false); err != nil { + if err := th.App.ImportDirectChannel(&channelData, false); err != nil { t.Fatalf("Expected success: %v", err.Error()) } @@ -2622,14 +2613,14 @@ func TestImportImportDirectPost(t *testing.T) { th.BasicUser2.Id, user3.Id, } - if channel, err := a.createGroupChannel(userIds, th.BasicUser.Id); err.Id != store.CHANNEL_EXISTS_ERROR { + if channel, err := th.App.createGroupChannel(userIds, th.BasicUser.Id); err.Id != store.CHANNEL_EXISTS_ERROR { t.Fatal("Should have got store.CHANNEL_EXISTS_ERROR") } else { groupChannel = channel } // Get the number of posts in the system. - if result := <-a.Srv.Store.Post().AnalyticsPostCount("", false, false); result.Err != nil { + if result := <-th.App.Srv.Store.Post().AnalyticsPostCount("", false, false); result.Err != nil { t.Fatal(result.Err) } else { initialPostCount = result.Data.(int64) @@ -2645,10 +2636,10 @@ func TestImportImportDirectPost(t *testing.T) { User: ptrStr(th.BasicUser.Username), CreateAt: ptrInt64(model.GetMillis()), } - if err := a.ImportDirectPost(data, true); err == nil { + if err := th.App.ImportDirectPost(data, true); err == nil { t.Fatalf("Expected error.") } - AssertAllPostsCount(t, initialPostCount, 0, "") + AssertAllPostsCount(t, th.App, initialPostCount, 0, "") // Try adding a valid post in dry run mode. data = &DirectPostImportData{ @@ -2661,10 +2652,10 @@ func TestImportImportDirectPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: ptrInt64(model.GetMillis()), } - if err := a.ImportDirectPost(data, true); err != nil { + if err := th.App.ImportDirectPost(data, true); err != nil { t.Fatalf("Expected success.") } - AssertAllPostsCount(t, initialPostCount, 0, "") + AssertAllPostsCount(t, th.App, initialPostCount, 0, "") // Try adding an invalid post in apply mode. data = &DirectPostImportData{ @@ -2678,10 +2669,10 @@ func TestImportImportDirectPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: ptrInt64(model.GetMillis()), } - if err := a.ImportDirectPost(data, false); err == nil { + if err := th.App.ImportDirectPost(data, false); err == nil { t.Fatalf("Expected error.") } - AssertAllPostsCount(t, initialPostCount, 0, "") + AssertAllPostsCount(t, th.App, initialPostCount, 0, "") // Try adding a valid post in apply mode. data = &DirectPostImportData{ @@ -2694,13 +2685,13 @@ func TestImportImportDirectPost(t *testing.T) { Message: ptrStr("Message"), CreateAt: ptrInt64(model.GetMillis()), } - if err := a.ImportDirectPost(data, false); err != nil { + if err := th.App.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success: %v", err.Error()) } - AssertAllPostsCount(t, initialPostCount, 1, "") + AssertAllPostsCount(t, th.App, initialPostCount, 1, "") // Check the post values. - if result := <-a.Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt); result.Err != nil { + if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2714,13 +2705,13 @@ func TestImportImportDirectPost(t *testing.T) { } // Import the post again. - if err := a.ImportDirectPost(data, false); err != nil { + if err := th.App.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success.") } - AssertAllPostsCount(t, initialPostCount, 1, "") + AssertAllPostsCount(t, th.App, initialPostCount, 1, "") // Check the post values. - if result := <-a.Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt); result.Err != nil { + if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2735,27 +2726,27 @@ func TestImportImportDirectPost(t *testing.T) { // Save the post with a different time. data.CreateAt = ptrInt64(*data.CreateAt + 1) - if err := a.ImportDirectPost(data, false); err != nil { + if err := th.App.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success.") } - AssertAllPostsCount(t, initialPostCount, 2, "") + AssertAllPostsCount(t, th.App, initialPostCount, 2, "") // Save the post with a different message. data.Message = ptrStr("Message 2") - if err := a.ImportDirectPost(data, false); err != nil { + if err := th.App.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success.") } - AssertAllPostsCount(t, initialPostCount, 3, "") + AssertAllPostsCount(t, th.App, initialPostCount, 3, "") // Test with hashtags data.Message = ptrStr("Message 2 #hashtagmashupcity") data.CreateAt = ptrInt64(*data.CreateAt + 1) - if err := a.ImportDirectPost(data, false); err != nil { + if err := th.App.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success.") } - AssertAllPostsCount(t, initialPostCount, 4, "") + AssertAllPostsCount(t, th.App, initialPostCount, 4, "") - if result := <-a.Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt); result.Err != nil { + if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2787,12 +2778,12 @@ func TestImportImportDirectPost(t *testing.T) { CreateAt: ptrInt64(model.GetMillis()), } - if err := a.ImportDirectPost(data, false); err != nil { + if err := th.App.ImportDirectPost(data, false); err != nil { t.Fatalf("Expected success: %v", err.Error()) } // Check the post values. - if result := <-a.Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt); result.Err != nil { + if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt); result.Err != nil { t.Fatal(result.Err.Error()) } else { posts := result.Data.([]*model.Post) @@ -2800,64 +2791,62 @@ func TestImportImportDirectPost(t *testing.T) { t.Fatal("Unexpected number of posts found.") } post := posts[0] - checkPreference(t, th.BasicUser.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true") - checkPreference(t, th.BasicUser2.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true") + checkPreference(t, th.App, th.BasicUser.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true") + checkPreference(t, th.App, th.BasicUser2.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true") } } func TestImportImportLine(t *testing.T) { - a := Global() - _ = a.Setup() + th := Setup() // Try import line with an invalid type. line := LineImportData{ Type: "gibberish", } - if err := a.ImportLine(line, false); err == nil { + if err := th.App.ImportLine(line, false); err == nil { t.Fatalf("Expected an error when importing a line with invalid type.") } // Try import line with team type but nil team. line.Type = "team" - if err := a.ImportLine(line, false); err == nil { + if err := th.App.ImportLine(line, false); err == nil { t.Fatalf("Expected an error when importing a line of type team with a nil team.") } // Try import line with channel type but nil channel. line.Type = "channel" - if err := a.ImportLine(line, false); err == nil { + if err := th.App.ImportLine(line, false); err == nil { t.Fatalf("Expected an error when importing a line with type channel with a nil channel.") } // Try import line with user type but nil user. line.Type = "user" - if err := a.ImportLine(line, false); err == nil { + if err := th.App.ImportLine(line, false); err == nil { t.Fatalf("Expected an error when importing a line with type uesr with a nil user.") } // Try import line with post type but nil post. line.Type = "post" - if err := a.ImportLine(line, false); err == nil { + if err := th.App.ImportLine(line, false); err == nil { t.Fatalf("Expected an error when importing a line with type post with a nil post.") } // Try import line with direct_channel type but nil direct_channel. line.Type = "direct_channel" - if err := a.ImportLine(line, false); err == nil { + if err := th.App.ImportLine(line, false); err == nil { t.Fatalf("Expected an error when importing a line with type direct_channel with a nil direct_channel.") } // Try import line with direct_post type but nil direct_post. line.Type = "direct_post" - if err := a.ImportLine(line, false); err == nil { + if err := th.App.ImportLine(line, false); err == nil { t.Fatalf("Expected an error when importing a line with type direct_post with a nil direct_post.") } } func TestImportBulkImport(t *testing.T) { - a := Global() - _ = a.Setup() + th := Setup() teamName := model.NewId() channelName := model.NewId() @@ -2878,13 +2867,13 @@ func TestImportBulkImport(t *testing.T) { {"type": "direct_post", "direct_post": {"channel_members": ["` + username + `", "` + username2 + `"], "user": "` + username + `", "message": "Hello Direct Channel", "create_at": 123456789013}} {"type": "direct_post", "direct_post": {"channel_members": ["` + username + `", "` + username2 + `", "` + username3 + `"], "user": "` + username + `", "message": "Hello Group Channel", "create_at": 123456789014}}` - if err, line := a.BulkImport(strings.NewReader(data1), false, 2); err != nil || line != 0 { + if err, line := th.App.BulkImport(strings.NewReader(data1), false, 2); err != nil || line != 0 { t.Fatalf("BulkImport should have succeeded: %v, %v", err.Error(), line) } // Run bulk import using a string that contains a line with invalid json. data2 := `{"type": "version", "version": 1` - if err, line := a.BulkImport(strings.NewReader(data2), false, 2); err == nil || line != 1 { + if err, line := th.App.BulkImport(strings.NewReader(data2), false, 2); err == nil || line != 1 { t.Fatalf("Should have failed due to invalid JSON on line 1.") } @@ -2893,14 +2882,13 @@ func TestImportBulkImport(t *testing.T) { {"type": "channel", "channel": {"type": "O", "display_name": "xr6m6udffngark2uekvr3hoeny", "team": "` + teamName + `", "name": "` + channelName + `"}} {"type": "user", "user": {"username": "kufjgnkxkrhhfgbrip6qxkfsaa", "email": "kufjgnkxkrhhfgbrip6qxkfsaa@example.com"}} {"type": "user", "user": {"username": "bwshaim6qnc2ne7oqkd5b2s2rq", "email": "bwshaim6qnc2ne7oqkd5b2s2rq@example.com", "teams": [{"name": "` + teamName + `", "channels": [{"name": "` + channelName + `"}]}]}}` - if err, line := a.BulkImport(strings.NewReader(data3), false, 2); err == nil || line != 1 { + if err, line := th.App.BulkImport(strings.NewReader(data3), false, 2); err == nil || line != 1 { t.Fatalf("Should have failed due to missing version line on line 1.") } } func TestImportProcessImportDataFileVersionLine(t *testing.T) { - a := Global() - _ = a.Setup() + Setup() data := LineImportData{ Type: "version", diff --git a/app/job_test.go b/app/job_test.go index 1a8acb3ce..18186cc47 100644 --- a/app/job_test.go +++ b/app/job_test.go @@ -11,20 +11,19 @@ import ( ) func TestGetJob(t *testing.T) { - a := Global() - a.Setup() + th := Setup() status := &model.Job{ Id: model.NewId(), Status: model.NewId(), } - if result := <-a.Srv.Store.Job().Save(status); result.Err != nil { + if result := <-th.App.Srv.Store.Job().Save(status); result.Err != nil { t.Fatal(result.Err) } - defer a.Srv.Store.Job().Delete(status.Id) + defer th.App.Srv.Store.Job().Delete(status.Id) - if received, err := a.GetJob(status.Id); err != nil { + if received, err := th.App.GetJob(status.Id); err != nil { t.Fatal(err) } else if received.Id != status.Id || received.Status != status.Status { t.Fatal("inccorrect job status received") @@ -32,8 +31,7 @@ func TestGetJob(t *testing.T) { } func TestGetJobByType(t *testing.T) { - a := Global() - a.Setup() + th := Setup() jobType := model.NewId() @@ -56,11 +54,11 @@ func TestGetJobByType(t *testing.T) { } for _, status := range statuses { - store.Must(a.Srv.Store.Job().Save(status)) - defer a.Srv.Store.Job().Delete(status.Id) + store.Must(th.App.Srv.Store.Job().Save(status)) + defer th.App.Srv.Store.Job().Delete(status.Id) } - if received, err := a.GetJobsByType(jobType, 0, 2); err != nil { + if received, err := th.App.GetJobsByType(jobType, 0, 2); err != nil { t.Fatal(err) } else if len(received) != 2 { t.Fatal("received wrong number of statuses") @@ -70,7 +68,7 @@ func TestGetJobByType(t *testing.T) { t.Fatal("should've received second newest job second") } - if received, err := a.GetJobsByType(jobType, 2, 2); err != nil { + if received, err := th.App.GetJobsByType(jobType, 2, 2); err != nil { t.Fatal(err) } else if len(received) != 1 { t.Fatal("received wrong number of statuses") diff --git a/app/license_test.go b/app/license_test.go index fabd949cf..376972b2b 100644 --- a/app/license_test.go +++ b/app/license_test.go @@ -11,31 +11,28 @@ import ( ) func TestLoadLicense(t *testing.T) { - a := Global() - a.Setup() + th := Setup() - a.LoadLicense() + th.App.LoadLicense() if utils.IsLicensed() { t.Fatal("shouldn't have a valid license") } } func TestSaveLicense(t *testing.T) { - a := Global() - a.Setup() + th := Setup() b1 := []byte("junk") - if _, err := a.SaveLicense(b1); err == nil { + if _, err := th.App.SaveLicense(b1); err == nil { t.Fatal("shouldn't have saved license") } } func TestRemoveLicense(t *testing.T) { - a := Global() - a.Setup() + th := Setup() - if err := a.RemoveLicense(); err != nil { + if err := th.App.RemoveLicense(); err != nil { t.Fatal("should have removed license") } } diff --git a/app/notification_test.go b/app/notification_test.go index 915f57fd1..c262d068d 100644 --- a/app/notification_test.go +++ b/app/notification_test.go @@ -12,12 +12,11 @@ import ( ) func TestSendNotifications(t *testing.T) { - a := Global() - th := a.Setup().InitBasic() + th := Setup().InitBasic() - a.AddUserToChannel(th.BasicUser2, th.BasicChannel) + th.App.AddUserToChannel(th.BasicUser2, th.BasicChannel) - post1, err := a.CreatePostMissingChannel(&model.Post{ + post1, err := th.App.CreatePostMissingChannel(&model.Post{ UserId: th.BasicUser.Id, ChannelId: th.BasicChannel.Id, Message: "@" + th.BasicUser2.Username, @@ -27,7 +26,7 @@ func TestSendNotifications(t *testing.T) { t.Fatal(err) } - mentions, err := a.SendNotifications(post1, th.BasicTeam, th.BasicChannel, th.BasicUser, nil) + mentions, err := th.App.SendNotifications(post1, th.BasicTeam, th.BasicChannel, th.BasicUser, nil) if err != nil { t.Fatal(err) } else if mentions == nil { @@ -38,12 +37,12 @@ func TestSendNotifications(t *testing.T) { t.Fatal("user should have been mentioned") } - dm, err := a.CreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id) + dm, err := th.App.CreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id) if err != nil { t.Fatal(err) } - post2, err := a.CreatePostMissingChannel(&model.Post{ + post2, err := th.App.CreatePostMissingChannel(&model.Post{ UserId: th.BasicUser.Id, ChannelId: dm.Id, Message: "dm message", @@ -53,15 +52,15 @@ func TestSendNotifications(t *testing.T) { t.Fatal(err) } - _, err = a.SendNotifications(post2, th.BasicTeam, dm, th.BasicUser, nil) + _, err = th.App.SendNotifications(post2, th.BasicTeam, dm, th.BasicUser, nil) if err != nil { t.Fatal(err) } - a.UpdateActive(th.BasicUser2, false) - a.InvalidateAllCaches() + th.App.UpdateActive(th.BasicUser2, false) + th.App.InvalidateAllCaches() - post3, err := a.CreatePostMissingChannel(&model.Post{ + post3, err := th.App.CreatePostMissingChannel(&model.Post{ UserId: th.BasicUser.Id, ChannelId: dm.Id, Message: "dm message", @@ -71,7 +70,7 @@ func TestSendNotifications(t *testing.T) { t.Fatal(err) } - _, err = a.SendNotifications(post3, th.BasicTeam, dm, th.BasicUser, nil) + _, err = th.App.SendNotifications(post3, th.BasicTeam, dm, th.BasicUser, nil) if err != nil { t.Fatal(err) } @@ -409,8 +408,7 @@ func TestRemoveCodeFromMessage(t *testing.T) { } func TestGetMentionKeywords(t *testing.T) { - a := Global() - a.Setup() + Setup() // user with username or custom mentions enabled user1 := &model.User{ Id: model.NewId(), @@ -835,8 +833,7 @@ func TestDoesStatusAllowPushNotification(t *testing.T) { } func TestGetDirectMessageNotificationEmailSubject(t *testing.T) { - a := Global() - a.Setup() + Setup() expectedPrefix := "[http://localhost:8065] New Direct Message from sender on" post := &model.Post{ CreateAt: 1501804801000, @@ -849,8 +846,7 @@ func TestGetDirectMessageNotificationEmailSubject(t *testing.T) { } func TestGetNotificationEmailSubject(t *testing.T) { - a := Global() - a.Setup() + Setup() expectedPrefix := "[http://localhost:8065] Notification in team on" post := &model.Post{ CreateAt: 1501804801000, @@ -863,8 +859,7 @@ func TestGetNotificationEmailSubject(t *testing.T) { } func TestGetNotificationEmailBodyFullNotificationPublicChannel(t *testing.T) { - a := Global() - a.Setup() + th := Setup() recipient := &model.User{} post := &model.Post{ Message: "This is the message", @@ -879,7 +874,7 @@ func TestGetNotificationEmailBodyFullNotificationPublicChannel(t *testing.T) { emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL translateFunc := utils.GetUserTranslations("en") - body := a.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) + body := th.App.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) if !strings.Contains(body, "You have a new notification.") { t.Fatal("Expected email text 'You have a new notification. Got " + body) } @@ -898,8 +893,7 @@ func TestGetNotificationEmailBodyFullNotificationPublicChannel(t *testing.T) { } func TestGetNotificationEmailBodyFullNotificationGroupChannel(t *testing.T) { - a := Global() - a.Setup() + th := Setup() recipient := &model.User{} post := &model.Post{ Message: "This is the message", @@ -914,7 +908,7 @@ func TestGetNotificationEmailBodyFullNotificationGroupChannel(t *testing.T) { emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL translateFunc := utils.GetUserTranslations("en") - body := a.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) + body := th.App.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) if !strings.Contains(body, "You have a new notification.") { t.Fatal("Expected email text 'You have a new notification. Got " + body) } @@ -933,8 +927,7 @@ func TestGetNotificationEmailBodyFullNotificationGroupChannel(t *testing.T) { } func TestGetNotificationEmailBodyFullNotificationPrivateChannel(t *testing.T) { - a := Global() - a.Setup() + th := Setup() recipient := &model.User{} post := &model.Post{ Message: "This is the message", @@ -949,7 +942,7 @@ func TestGetNotificationEmailBodyFullNotificationPrivateChannel(t *testing.T) { emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL translateFunc := utils.GetUserTranslations("en") - body := a.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) + body := th.App.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) if !strings.Contains(body, "You have a new notification.") { t.Fatal("Expected email text 'You have a new notification. Got " + body) } @@ -968,8 +961,7 @@ func TestGetNotificationEmailBodyFullNotificationPrivateChannel(t *testing.T) { } func TestGetNotificationEmailBodyFullNotificationDirectChannel(t *testing.T) { - a := Global() - a.Setup() + th := Setup() recipient := &model.User{} post := &model.Post{ Message: "This is the message", @@ -984,7 +976,7 @@ func TestGetNotificationEmailBodyFullNotificationDirectChannel(t *testing.T) { emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_FULL translateFunc := utils.GetUserTranslations("en") - body := a.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) + body := th.App.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) if !strings.Contains(body, "You have a new direct message.") { t.Fatal("Expected email text 'You have a new direct message. Got " + body) } @@ -1001,8 +993,7 @@ func TestGetNotificationEmailBodyFullNotificationDirectChannel(t *testing.T) { // from here func TestGetNotificationEmailBodyGenericNotificationPublicChannel(t *testing.T) { - a := Global() - a.Setup() + th := Setup() recipient := &model.User{} post := &model.Post{ Message: "This is the message", @@ -1017,7 +1008,7 @@ func TestGetNotificationEmailBodyGenericNotificationPublicChannel(t *testing.T) emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_GENERIC translateFunc := utils.GetUserTranslations("en") - body := a.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) + body := th.App.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) if !strings.Contains(body, "You have a new notification from "+senderName) { t.Fatal("Expected email text 'You have a new notification from " + senderName + "'. Got " + body) } @@ -1033,8 +1024,7 @@ func TestGetNotificationEmailBodyGenericNotificationPublicChannel(t *testing.T) } func TestGetNotificationEmailBodyGenericNotificationGroupChannel(t *testing.T) { - a := Global() - a.Setup() + th := Setup() recipient := &model.User{} post := &model.Post{ Message: "This is the message", @@ -1049,7 +1039,7 @@ func TestGetNotificationEmailBodyGenericNotificationGroupChannel(t *testing.T) { emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_GENERIC translateFunc := utils.GetUserTranslations("en") - body := a.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) + body := th.App.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) if !strings.Contains(body, "You have a new notification from "+senderName) { t.Fatal("Expected email text 'You have a new notification from " + senderName + "'. Got " + body) } @@ -1065,8 +1055,7 @@ func TestGetNotificationEmailBodyGenericNotificationGroupChannel(t *testing.T) { } func TestGetNotificationEmailBodyGenericNotificationPrivateChannel(t *testing.T) { - a := Global() - a.Setup() + th := Setup() recipient := &model.User{} post := &model.Post{ Message: "This is the message", @@ -1081,7 +1070,7 @@ func TestGetNotificationEmailBodyGenericNotificationPrivateChannel(t *testing.T) emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_GENERIC translateFunc := utils.GetUserTranslations("en") - body := a.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) + body := th.App.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) if !strings.Contains(body, "You have a new notification from "+senderName) { t.Fatal("Expected email text 'You have a new notification from " + senderName + "'. Got " + body) } @@ -1097,8 +1086,7 @@ func TestGetNotificationEmailBodyGenericNotificationPrivateChannel(t *testing.T) } func TestGetNotificationEmailBodyGenericNotificationDirectChannel(t *testing.T) { - a := Global() - a.Setup() + th := Setup() recipient := &model.User{} post := &model.Post{ Message: "This is the message", @@ -1113,7 +1101,7 @@ func TestGetNotificationEmailBodyGenericNotificationDirectChannel(t *testing.T) emailNotificationContentsType := model.EMAIL_NOTIFICATION_CONTENTS_GENERIC translateFunc := utils.GetUserTranslations("en") - body := a.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) + body := th.App.getNotificationEmailBody(recipient, post, channel, senderName, teamName, teamURL, emailNotificationContentsType, translateFunc) if !strings.Contains(body, "You have a new direct message from "+senderName) { t.Fatal("Expected email text 'You have a new direct message from " + senderName + "'. Got " + body) } diff --git a/app/oauth_test.go b/app/oauth_test.go index 6a8ea7123..d756c0abe 100644 --- a/app/oauth_test.go +++ b/app/oauth_test.go @@ -11,9 +11,8 @@ import ( ) func TestOAuthRevokeAccessToken(t *testing.T) { - a := Global() - a.Setup() - if err := a.RevokeAccessToken(model.NewRandomString(16)); err == nil { + th := Setup() + if err := th.App.RevokeAccessToken(model.NewRandomString(16)); err == nil { t.Fatal("Should have failed bad token") } @@ -24,8 +23,8 @@ func TestOAuthRevokeAccessToken(t *testing.T) { session.Roles = model.ROLE_SYSTEM_USER.Id session.SetExpireInDays(1) - session, _ = a.CreateSession(session) - if err := a.RevokeAccessToken(session.Token); err == nil { + session, _ = th.App.CreateSession(session) + if err := th.App.RevokeAccessToken(session.Token); err == nil { t.Fatal("Should have failed does not have an access token") } @@ -36,18 +35,17 @@ func TestOAuthRevokeAccessToken(t *testing.T) { accessData.ClientId = model.NewId() accessData.ExpiresAt = session.ExpiresAt - if result := <-a.Srv.Store.OAuth().SaveAccessData(accessData); result.Err != nil { + if result := <-th.App.Srv.Store.OAuth().SaveAccessData(accessData); result.Err != nil { t.Fatal(result.Err) } - if err := a.RevokeAccessToken(accessData.Token); err != nil { + if err := th.App.RevokeAccessToken(accessData.Token); err != nil { t.Fatal(err) } } func TestOAuthDeleteApp(t *testing.T) { - a := Global() - a.Setup() + th := Setup() oldSetting := utils.Cfg.ServiceSettings.EnableOAuthServiceProvider defer func() { @@ -62,7 +60,7 @@ func TestOAuthDeleteApp(t *testing.T) { a1.Homepage = "https://nowhere.com" var err *model.AppError - a1, err = a.CreateOAuthApp(a1) + a1, err = th.App.CreateOAuthApp(a1) if err != nil { t.Fatal(err) } @@ -75,7 +73,7 @@ func TestOAuthDeleteApp(t *testing.T) { session.IsOAuth = true session.SetExpireInDays(1) - session, _ = a.CreateSession(session) + session, _ = th.App.CreateSession(session) accessData := &model.AccessData{} accessData.Token = session.Token @@ -84,15 +82,15 @@ func TestOAuthDeleteApp(t *testing.T) { accessData.ClientId = a1.Id accessData.ExpiresAt = session.ExpiresAt - if result := <-a.Srv.Store.OAuth().SaveAccessData(accessData); result.Err != nil { + if result := <-th.App.Srv.Store.OAuth().SaveAccessData(accessData); result.Err != nil { t.Fatal(result.Err) } - if err := a.DeleteOAuthApp(a1.Id); err != nil { + if err := th.App.DeleteOAuthApp(a1.Id); err != nil { t.Fatal(err) } - if _, err := a.GetSession(session.Token); err == nil { + if _, err := th.App.GetSession(session.Token); err == nil { t.Fatal("should not get session from cache or db") } } diff --git a/app/post_test.go b/app/post_test.go index e0e9b52b6..92eb8857e 100644 --- a/app/post_test.go +++ b/app/post_test.go @@ -19,14 +19,13 @@ import ( ) func TestUpdatePostEditAt(t *testing.T) { - a := Global() - th := a.Setup().InitBasic() + th := Setup().InitBasic() post := &model.Post{} *post = *th.BasicPost post.IsPinned = true - if saved, err := a.UpdatePost(post, true); err != nil { + if saved, err := th.App.UpdatePost(post, true); err != nil { t.Fatal(err) } else if saved.EditAt != post.EditAt { t.Fatal("shouldn't have updated post.EditAt when pinning post") @@ -37,7 +36,7 @@ func TestUpdatePostEditAt(t *testing.T) { time.Sleep(time.Millisecond * 100) post.Message = model.NewId() - if saved, err := a.UpdatePost(post, true); err != nil { + if saved, err := th.App.UpdatePost(post, true); err != nil { t.Fatal(err) } else if saved.EditAt == post.EditAt { t.Fatal("should have updated post.EditAt when updating post message") @@ -45,21 +44,20 @@ func TestUpdatePostEditAt(t *testing.T) { } func TestPostReplyToPostWhereRootPosterLeftChannel(t *testing.T) { - a := Global() // This test ensures that when replying to a root post made by a user who has since left the channel, the reply // post completes successfully. This is a regression test for PLT-6523. - th := a.Setup().InitBasic() + th := Setup().InitBasic() channel := th.BasicChannel userInChannel := th.BasicUser2 userNotInChannel := th.BasicUser rootPost := th.BasicPost - if _, err := a.AddUserToChannel(userInChannel, channel); err != nil { + if _, err := th.App.AddUserToChannel(userInChannel, channel); err != nil { t.Fatal(err) } - if err := a.RemoveUserFromChannel(userNotInChannel.Id, "", channel); err != nil { + if err := th.App.RemoveUserFromChannel(userNotInChannel.Id, "", channel); err != nil { t.Fatal(err) } @@ -73,14 +71,13 @@ func TestPostReplyToPostWhereRootPosterLeftChannel(t *testing.T) { CreateAt: 0, } - if _, err := a.CreatePostAsUser(&replyPost); err != nil { + if _, err := th.App.CreatePostAsUser(&replyPost); err != nil { t.Fatal(err) } } func TestPostAction(t *testing.T) { - a := Global() - th := a.Setup().InitBasic() + th := Setup().InitBasic() allowedInternalConnections := *utils.Cfg.ServiceSettings.AllowedUntrustedInternalConnections defer func() { @@ -125,7 +122,7 @@ func TestPostAction(t *testing.T) { }, } - post, err := a.CreatePostAsUser(&interactivePost) + post, err := th.App.CreatePostAsUser(&interactivePost) require.Nil(t, err) attachments, ok := post.Props["attachments"].([]*model.SlackAttachment) @@ -134,10 +131,10 @@ func TestPostAction(t *testing.T) { require.NotEmpty(t, attachments[0].Actions) require.NotEmpty(t, attachments[0].Actions[0].Id) - err = a.DoPostAction(post.Id, "notavalidid", th.BasicUser.Id) + err = th.App.DoPostAction(post.Id, "notavalidid", th.BasicUser.Id) require.NotNil(t, err) assert.Equal(t, http.StatusNotFound, err.StatusCode) - err = a.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id) + err = th.App.DoPostAction(post.Id, attachments[0].Actions[0].Id, th.BasicUser.Id) require.Nil(t, err) } diff --git a/app/team_test.go b/app/team_test.go index 547904aa5..b074ed14f 100644 --- a/app/team_test.go +++ b/app/team_test.go @@ -11,8 +11,7 @@ import ( ) func TestCreateTeam(t *testing.T) { - a := Global() - th := a.Setup().InitBasic() + th := Setup().InitBasic() id := model.NewId() team := &model.Team{ @@ -22,19 +21,18 @@ func TestCreateTeam(t *testing.T) { Type: model.TEAM_OPEN, } - if _, err := a.CreateTeam(team); err != nil { + if _, err := th.App.CreateTeam(team); err != nil { t.Log(err) t.Fatal("Should create a new team") } - if _, err := a.CreateTeam(th.BasicTeam); err == nil { + if _, err := th.App.CreateTeam(th.BasicTeam); err == nil { t.Fatal("Should not create a new team - team already exist") } } func TestCreateTeamWithUser(t *testing.T) { - a := Global() - th := a.Setup().InitBasic() + th := Setup().InitBasic() id := model.NewId() team := &model.Team{ @@ -44,17 +42,17 @@ func TestCreateTeamWithUser(t *testing.T) { Type: model.TEAM_OPEN, } - if _, err := a.CreateTeamWithUser(team, th.BasicUser.Id); err != nil { + if _, err := th.App.CreateTeamWithUser(team, th.BasicUser.Id); err != nil { t.Log(err) t.Fatal("Should create a new team with existing user") } - if _, err := a.CreateTeamWithUser(team, model.NewId()); err == nil { + if _, err := th.App.CreateTeamWithUser(team, model.NewId()); err == nil { t.Fatal("Should not create a new team - user does not exist") } user := model.User{Email: strings.ToLower(model.NewId()) + "success+test", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := a.CreateUser(&user) + ruser, _ := th.App.CreateUser(&user) id = model.NewId() team2 := &model.Team{ @@ -65,7 +63,7 @@ func TestCreateTeamWithUser(t *testing.T) { } //Fail to create a team with user when user has set email without domain - if _, err := a.CreateTeamWithUser(team2, ruser.Id); err == nil { + if _, err := th.App.CreateTeamWithUser(team2, ruser.Id); err == nil { t.Log(err.Message) t.Fatal("Should not create a team with user when user has set email without domain") } else { @@ -77,12 +75,11 @@ func TestCreateTeamWithUser(t *testing.T) { } func TestUpdateTeam(t *testing.T) { - a := Global() - th := a.Setup().InitBasic() + th := Setup().InitBasic() th.BasicTeam.DisplayName = "Testing 123" - if updatedTeam, err := a.UpdateTeam(th.BasicTeam); err != nil { + if updatedTeam, err := th.App.UpdateTeam(th.BasicTeam); err != nil { t.Log(err) t.Fatal("Should update the team") } else { @@ -93,36 +90,33 @@ func TestUpdateTeam(t *testing.T) { } func TestAddUserToTeam(t *testing.T) { - a := Global() - th := a.Setup().InitBasic() + th := Setup().InitBasic() user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := a.CreateUser(&user) + ruser, _ := th.App.CreateUser(&user) - if _, err := a.AddUserToTeam(th.BasicTeam.Id, ruser.Id, ""); err != nil { + if _, err := th.App.AddUserToTeam(th.BasicTeam.Id, ruser.Id, ""); err != nil { t.Log(err) t.Fatal("Should add user to the team") } } func TestAddUserToTeamByTeamId(t *testing.T) { - a := Global() - th := a.Setup().InitBasic() + th := Setup().InitBasic() user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@example.com", Nickname: "Darth Vader", Username: "vader" + model.NewId(), Password: "passwd1", AuthService: ""} - ruser, _ := a.CreateUser(&user) + ruser, _ := th.App.CreateUser(&user) - if err := a.AddUserToTeamByTeamId(th.BasicTeam.Id, ruser); err != nil { + if err := th.App.AddUserToTeamByTeamId(th.BasicTeam.Id, ruser); err != nil { t.Log(err) t.Fatal("Should add user to the team") } } func TestPermanentDeleteTeam(t *testing.T) { - a := Global() - th := a.Setup().InitBasic() + th := Setup().InitBasic() - team, err := a.CreateTeam(&model.Team{ + team, err := th.App.CreateTeam(&model.Team{ DisplayName: "deletion-test", Name: "deletion-test", Email: "foo@foo.com", @@ -132,10 +126,10 @@ func TestPermanentDeleteTeam(t *testing.T) { t.Fatal(err.Error()) } defer func() { - a.PermanentDeleteTeam(team) + th.App.PermanentDeleteTeam(team) }() - command, err := a.CreateCommand(&model.Command{ + command, err := th.App.CreateCommand(&model.Command{ CreatorId: th.BasicUser.Id, TeamId: team.Id, Trigger: "foo", @@ -145,37 +139,37 @@ func TestPermanentDeleteTeam(t *testing.T) { if err != nil { t.Fatal(err.Error()) } - defer a.DeleteCommand(command.Id) + defer th.App.DeleteCommand(command.Id) - if command, err = a.GetCommand(command.Id); command == nil || err != nil { + if command, err = th.App.GetCommand(command.Id); command == nil || err != nil { t.Fatal("unable to get new command") } - if err := a.PermanentDeleteTeam(team); err != nil { + if err := th.App.PermanentDeleteTeam(team); err != nil { t.Fatal(err.Error()) } - if command, err = a.GetCommand(command.Id); command != nil || err == nil { + if command, err = th.App.GetCommand(command.Id); command != nil || err == nil { t.Fatal("command wasn't deleted") } // Test deleting a team with no channels. team = th.CreateTeam() defer func() { - a.PermanentDeleteTeam(team) + th.App.PermanentDeleteTeam(team) }() - if channels, err := a.GetPublicChannelsForTeam(team.Id, 0, 1000); err != nil { + if channels, err := th.App.GetPublicChannelsForTeam(team.Id, 0, 1000); err != nil { t.Fatal(err) } else { for _, channel := range *channels { - if err2 := a.PermanentDeleteChannel(channel); err2 != nil { + if err2 := th.App.PermanentDeleteChannel(channel); err2 != nil { t.Fatal(err) } } } - if err := a.PermanentDeleteTeam(team); err != nil { + if err := th.App.PermanentDeleteTeam(team); err != nil { t.Fatal(err) } } diff --git a/app/user_test.go b/app/user_test.go index c011b1435..a01ee5c07 100644 --- a/app/user_test.go +++ b/app/user_test.go @@ -20,10 +20,9 @@ import ( ) func TestIsUsernameTaken(t *testing.T) { - a := Global() - th := a.Setup().InitBasic() + th := Setup().InitBasic() user := th.BasicUser - taken := a.IsUsernameTaken(user.Username) + taken := th.App.IsUsernameTaken(user.Username) if !taken { t.Logf("the username '%v' should be taken", user.Username) @@ -31,7 +30,7 @@ func TestIsUsernameTaken(t *testing.T) { } newUsername := "randomUsername" - taken = a.IsUsernameTaken(newUsername) + taken = th.App.IsUsernameTaken(newUsername) if taken { t.Logf("the username '%v' should not be taken", newUsername) @@ -40,8 +39,7 @@ func TestIsUsernameTaken(t *testing.T) { } func TestCheckUserDomain(t *testing.T) { - a := Global() - th := a.Setup().InitBasic() + th := Setup().InitBasic() user := th.BasicUser cases := []struct { @@ -67,13 +65,12 @@ func TestCheckUserDomain(t *testing.T) { } func TestCreateOAuthUser(t *testing.T) { - a := Global() - th := a.Setup().InitBasic() + th := Setup().InitBasic() r := rand.New(rand.NewSource(time.Now().UnixNano())) glUser := oauthgitlab.GitLabUser{Id: int64(r.Intn(1000)) + 1, Username: "o" + model.NewId(), Email: model.NewId() + "@simulator.amazonses.com", Name: "Joram Wilander"} json := glUser.ToJson() - user, err := a.CreateOAuthUser(model.USER_AUTH_SERVICE_GITLAB, strings.NewReader(json), th.BasicTeam.Id) + user, err := th.App.CreateOAuthUser(model.USER_AUTH_SERVICE_GITLAB, strings.NewReader(json), th.BasicTeam.Id) if err != nil { t.Fatal(err) } @@ -82,7 +79,7 @@ func TestCreateOAuthUser(t *testing.T) { t.Fatal("usernames didn't match") } - a.PermanentDeleteUser(user) + th.App.PermanentDeleteUser(user) userCreation := utils.Cfg.TeamSettings.EnableUserCreation defer func() { @@ -90,7 +87,7 @@ func TestCreateOAuthUser(t *testing.T) { }() utils.Cfg.TeamSettings.EnableUserCreation = false - _, err = a.CreateOAuthUser(model.USER_AUTH_SERVICE_GITLAB, strings.NewReader(json), th.BasicTeam.Id) + _, err = th.App.CreateOAuthUser(model.USER_AUTH_SERVICE_GITLAB, strings.NewReader(json), th.BasicTeam.Id) if err == nil { t.Fatal("should have failed - user creation disabled") } @@ -118,8 +115,7 @@ func TestCreateProfileImage(t *testing.T) { } func TestUpdateOAuthUserAttrs(t *testing.T) { - a := Global() - a.Setup() + th := Setup() id := model.NewId() id2 := model.NewId() gitlabProvider := einterfaces.GetOauthProvider("gitlab") @@ -142,7 +138,7 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { data := bytes.NewReader(gitlabUser) user = getUserFromDB(user.Id, t) - a.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") + th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") user = getUserFromDB(user.Id, t) if user.Username != gitlabUserObj.Username { @@ -157,7 +153,7 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { data := bytes.NewReader(gitlabUser) user = getUserFromDB(user.Id, t) - a.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") + th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") user = getUserFromDB(user.Id, t) if user.Username == gitlabUserObj.Username { @@ -173,7 +169,7 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { data := bytes.NewReader(gitlabUser) user = getUserFromDB(user.Id, t) - a.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") + th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") user = getUserFromDB(user.Id, t) if user.Email != gitlabUserObj.Email { @@ -192,7 +188,7 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { data := bytes.NewReader(gitlabUser) user = getUserFromDB(user.Id, t) - a.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") + th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") user = getUserFromDB(user.Id, t) if user.Email == gitlabUserObj.Email { @@ -207,7 +203,7 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { data := bytes.NewReader(gitlabUser) user = getUserFromDB(user.Id, t) - a.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") + th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") user = getUserFromDB(user.Id, t) if user.FirstName != "Updated" { @@ -221,7 +217,7 @@ func TestUpdateOAuthUserAttrs(t *testing.T) { data := bytes.NewReader(gitlabUser) user = getUserFromDB(user.Id, t) - a.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") + th.App.UpdateOAuthUserAttrs(data, user, gitlabProvider, "gitlab") user = getUserFromDB(user.Id, t) if user.LastName != "Lastname" { diff --git a/app/webhook_test.go b/app/webhook_test.go index fe1b34841..0a6bd0fb5 100644 --- a/app/webhook_test.go +++ b/app/webhook_test.go @@ -11,9 +11,8 @@ import ( ) func TestCreateWebhookPost(t *testing.T) { - a := Global() - th := a.Setup().InitBasic() - defer a.TearDown() + th := Setup().InitBasic() + defer th.App.TearDown() enableIncomingHooks := utils.Cfg.ServiceSettings.EnableIncomingWebhooks defer func() { @@ -23,13 +22,13 @@ func TestCreateWebhookPost(t *testing.T) { utils.Cfg.ServiceSettings.EnableIncomingWebhooks = true utils.SetDefaultRolesBasedOnConfig() - hook, err := a.CreateIncomingWebhookForChannel(th.BasicUser.Id, th.BasicChannel, &model.IncomingWebhook{ChannelId: th.BasicChannel.Id}) + hook, err := th.App.CreateIncomingWebhookForChannel(th.BasicUser.Id, th.BasicChannel, &model.IncomingWebhook{ChannelId: th.BasicChannel.Id}) if err != nil { t.Fatal(err.Error()) } - defer a.DeleteIncomingWebhook(hook.Id) + defer th.App.DeleteIncomingWebhook(hook.Id) - post, err := a.CreateWebhookPost(hook.UserId, th.BasicChannel, "foo", "user", "http://iconurl", model.StringInterface{ + post, err := th.App.CreateWebhookPost(hook.UserId, th.BasicChannel, "foo", "user", "http://iconurl", model.StringInterface{ "attachments": []*model.SlackAttachment{ &model.SlackAttachment{ Text: "text", diff --git a/cmd/platform/channel.go b/cmd/platform/channel.go index 1b06474d1..8f8e8e194 100644 --- a/cmd/platform/channel.go +++ b/cmd/platform/channel.go @@ -126,7 +126,8 @@ func init() { } func createChannelCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -170,7 +171,7 @@ func createChannelCmdF(cmd *cobra.Command, args []string) error { CreatorId: "", } - if _, err := app.Global().CreateChannel(channel, false); err != nil { + if _, err := a.CreateChannel(channel, false); err != nil { return err } @@ -178,7 +179,8 @@ func createChannelCmdF(cmd *cobra.Command, args []string) error { } func removeChannelUsersCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -197,24 +199,25 @@ func removeChannelUsersCmdF(cmd *cobra.Command, args []string) error { users := getUsersFromUserArgs(args[1:]) for i, user := range users { - removeUserFromChannel(channel, user, args[i+1]) + removeUserFromChannel(a, channel, user, args[i+1]) } return nil } -func removeUserFromChannel(channel *model.Channel, user *model.User, userArg string) { +func removeUserFromChannel(a *app.App, channel *model.Channel, user *model.User, userArg string) { if user == nil { CommandPrintErrorln("Can't find user '" + userArg + "'") return } - if err := app.Global().RemoveUserFromChannel(user.Id, "", channel); err != nil { + if err := a.RemoveUserFromChannel(user.Id, "", channel); err != nil { CommandPrintErrorln("Unable to remove '" + userArg + "' from " + channel.Name + ". Error: " + err.Error()) } } func addChannelUsersCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -233,24 +236,25 @@ func addChannelUsersCmdF(cmd *cobra.Command, args []string) error { users := getUsersFromUserArgs(args[1:]) for i, user := range users { - addUserToChannel(channel, user, args[i+1]) + addUserToChannel(a, channel, user, args[i+1]) } return nil } -func addUserToChannel(channel *model.Channel, user *model.User, userArg string) { +func addUserToChannel(a *app.App, channel *model.Channel, user *model.User, userArg string) { if user == nil { CommandPrintErrorln("Can't find user '" + userArg + "'") return } - if _, err := app.Global().AddUserToChannel(user, channel); err != nil { + if _, err := a.AddUserToChannel(user, channel); err != nil { CommandPrintErrorln("Unable to add '" + userArg + "' from " + channel.Name + ". Error: " + err.Error()) } } func archiveChannelsCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -264,7 +268,7 @@ func archiveChannelsCmdF(cmd *cobra.Command, args []string) error { CommandPrintErrorln("Unable to find channel '" + args[i] + "'") continue } - if result := <-app.Global().Srv.Store.Channel().Delete(channel.Id, model.GetMillis()); result.Err != nil { + if result := <-a.Srv.Store.Channel().Delete(channel.Id, model.GetMillis()); result.Err != nil { CommandPrintErrorln("Unable to archive channel '" + channel.Name + "' error: " + result.Err.Error()) } } @@ -273,7 +277,8 @@ func archiveChannelsCmdF(cmd *cobra.Command, args []string) error { } func deleteChannelsCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -297,7 +302,7 @@ func deleteChannelsCmdF(cmd *cobra.Command, args []string) error { CommandPrintErrorln("Unable to find channel '" + args[i] + "'") continue } - if err := deleteChannel(channel); err != nil { + if err := deleteChannel(a, channel); err != nil { CommandPrintErrorln("Unable to delete channel '" + channel.Name + "' error: " + err.Error()) } else { CommandPrettyPrintln("Deleted channel '" + channel.Name + "'") @@ -307,12 +312,13 @@ func deleteChannelsCmdF(cmd *cobra.Command, args []string) error { return nil } -func deleteChannel(channel *model.Channel) *model.AppError { - return app.Global().PermanentDeleteChannel(channel) +func deleteChannel(a *app.App, channel *model.Channel) *model.AppError { + return a.PermanentDeleteChannel(channel) } func moveChannelsCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -331,7 +337,7 @@ func moveChannelsCmdF(cmd *cobra.Command, args []string) error { CommandPrintErrorln("Unable to find channel '" + args[i] + "'") continue } - if err := moveChannel(team, channel); err != nil { + if err := moveChannel(a, team, channel); err != nil { CommandPrintErrorln("Unable to move channel '" + channel.Name + "' error: " + err.Error()) } else { CommandPrettyPrintln("Moved channel '" + channel.Name + "'") @@ -341,33 +347,33 @@ func moveChannelsCmdF(cmd *cobra.Command, args []string) error { return nil } -func moveChannel(team *model.Team, channel *model.Channel) *model.AppError { +func moveChannel(a *app.App, team *model.Team, channel *model.Channel) *model.AppError { oldTeamId := channel.TeamId - if err := app.Global().MoveChannel(team, channel); err != nil { + if err := a.MoveChannel(team, channel); err != nil { return err } - if incomingWebhooks, err := app.Global().GetIncomingWebhooksForTeamPage(oldTeamId, 0, 10000000); err != nil { + if incomingWebhooks, err := a.GetIncomingWebhooksForTeamPage(oldTeamId, 0, 10000000); err != nil { return err } else { for _, webhook := range incomingWebhooks { if webhook.ChannelId == channel.Id { webhook.TeamId = team.Id - if result := <-app.Global().Srv.Store.Webhook().UpdateIncoming(webhook); result.Err != nil { + if result := <-a.Srv.Store.Webhook().UpdateIncoming(webhook); result.Err != nil { CommandPrintErrorln("Failed to move incoming webhook '" + webhook.Id + "' to new team.") } } } } - if outgoingWebhooks, err := app.Global().GetOutgoingWebhooksForTeamPage(oldTeamId, 0, 10000000); err != nil { + if outgoingWebhooks, err := a.GetOutgoingWebhooksForTeamPage(oldTeamId, 0, 10000000); err != nil { return err } else { for _, webhook := range outgoingWebhooks { if webhook.ChannelId == channel.Id { webhook.TeamId = team.Id - if result := <-app.Global().Srv.Store.Webhook().UpdateOutgoing(webhook); result.Err != nil { + if result := <-a.Srv.Store.Webhook().UpdateOutgoing(webhook); result.Err != nil { CommandPrintErrorln("Failed to move outgoing webhook '" + webhook.Id + "' to new team.") } } @@ -378,7 +384,8 @@ func moveChannel(team *model.Team, channel *model.Channel) *model.AppError { } func listChannelsCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -396,7 +403,7 @@ func listChannelsCmdF(cmd *cobra.Command, args []string) error { CommandPrintErrorln("Unable to find team '" + args[i] + "'") continue } - if result := <-app.Global().Srv.Store.Channel().GetAll(team.Id); result.Err != nil { + if result := <-a.Srv.Store.Channel().GetAll(team.Id); result.Err != nil { CommandPrintErrorln("Unable to list channels for '" + args[i] + "'") } else { channels := result.Data.([]*model.Channel) @@ -415,7 +422,8 @@ func listChannelsCmdF(cmd *cobra.Command, args []string) error { } func restoreChannelsCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -433,7 +441,7 @@ func restoreChannelsCmdF(cmd *cobra.Command, args []string) error { CommandPrintErrorln("Unable to find channel '" + args[i] + "'") continue } - if result := <-app.Global().Srv.Store.Channel().SetDeleteAt(channel.Id, 0, model.GetMillis()); result.Err != nil { + if result := <-a.Srv.Store.Channel().SetDeleteAt(channel.Id, 0, model.GetMillis()); result.Err != nil { CommandPrintErrorln("Unable to restore channel '" + args[i] + "'") } } @@ -442,7 +450,8 @@ func restoreChannelsCmdF(cmd *cobra.Command, args []string) error { } func modifyChannelCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -475,7 +484,7 @@ func modifyChannelCmdF(cmd *cobra.Command, args []string) error { channel.Type = model.CHANNEL_PRIVATE } - if _, err := app.Global().UpdateChannel(channel); err != nil { + if _, err := a.UpdateChannel(channel); err != nil { return errors.New("Failed to update channel '" + args[0] + "' - " + err.Error()) } diff --git a/cmd/platform/import.go b/cmd/platform/import.go index 30e07cebf..85cb3835b 100644 --- a/cmd/platform/import.go +++ b/cmd/platform/import.go @@ -8,7 +8,6 @@ import ( "fmt" - "github.com/mattermost/mattermost-server/app" "github.com/spf13/cobra" ) @@ -45,7 +44,8 @@ func init() { } func slackImportCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -71,7 +71,7 @@ func slackImportCmdF(cmd *cobra.Command, args []string) error { CommandPrettyPrintln("Running Slack Import. This may take a long time for large teams or teams with many messages.") - app.Global().SlackImport(fileReader, fileInfo.Size(), team.Id) + a.SlackImport(fileReader, fileInfo.Size(), team.Id) CommandPrettyPrintln("Finished Slack Import.") @@ -79,7 +79,8 @@ func slackImportCmdF(cmd *cobra.Command, args []string) error { } func bulkImportCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -121,7 +122,7 @@ func bulkImportCmdF(cmd *cobra.Command, args []string) error { CommandPrettyPrintln("") - if err, lineNumber := app.Global().BulkImport(fileReader, !apply, workers); err != nil { + if err, lineNumber := a.BulkImport(fileReader, !apply, workers); err != nil { CommandPrettyPrintln(err.Error()) if lineNumber != 0 { CommandPrettyPrintln(fmt.Sprintf("Error occurred on data file line %v", lineNumber)) diff --git a/cmd/platform/init.go b/cmd/platform/init.go index b1ed2f3dc..1683c9d49 100644 --- a/cmd/platform/init.go +++ b/cmd/platform/init.go @@ -7,32 +7,34 @@ import ( "github.com/spf13/cobra" ) -func initDBCommandContextCobra(cmd *cobra.Command) error { +func initDBCommandContextCobra(cmd *cobra.Command) (*app.App, error) { config, err := cmd.Flags().GetString("config") if err != nil { - return err + return nil, err } - if err := initDBCommandContext(config); err != nil { + a, err := initDBCommandContext(config) + if err != nil { // Returning an error just prints the usage message, so actually panic panic(err) } - return nil + return a, nil } -func initDBCommandContext(configFileLocation string) error { +func initDBCommandContext(configFileLocation string) (*app.App, error) { if err := utils.InitAndLoadConfig(configFileLocation); err != nil { - return err + return nil, err } utils.ConfigureCmdLineLog() - app.Global().NewServer() - app.Global().InitStores() + a := app.Global() + a.NewServer() + a.InitStores() if model.BuildEnterpriseReady == "true" { - app.Global().LoadLicense() + a.LoadLicense() } - return nil + return a, nil } diff --git a/cmd/platform/ldap.go b/cmd/platform/ldap.go index 10f58fedb..ad9b0a2f6 100644 --- a/cmd/platform/ldap.go +++ b/cmd/platform/ldap.go @@ -27,7 +27,7 @@ func init() { } func ldapSyncCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + if _, err := initDBCommandContextCobra(cmd); err != nil { return err } diff --git a/cmd/platform/license.go b/cmd/platform/license.go index dc9c8f3dc..73efe9137 100644 --- a/cmd/platform/license.go +++ b/cmd/platform/license.go @@ -6,7 +6,6 @@ import ( "errors" "io/ioutil" - "github.com/mattermost/mattermost-server/app" "github.com/spf13/cobra" ) @@ -28,7 +27,8 @@ func init() { } func uploadLicenseCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -37,12 +37,11 @@ func uploadLicenseCmdF(cmd *cobra.Command, args []string) error { } var fileBytes []byte - var err error if fileBytes, err = ioutil.ReadFile(args[0]); err != nil { return err } - if _, err := app.Global().SaveLicense(fileBytes); err != nil { + if _, err := a.SaveLicense(fileBytes); err != nil { return err } diff --git a/cmd/platform/mattermost.go b/cmd/platform/mattermost.go index 8396b00c0..3c0add061 100644 --- a/cmd/platform/mattermost.go +++ b/cmd/platform/mattermost.go @@ -8,7 +8,6 @@ import ( "fmt" "os" - "github.com/mattermost/mattermost-server/app" "github.com/spf13/cobra" // Plugins @@ -59,7 +58,8 @@ var resetCmd = &cobra.Command{ } func resetCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -79,7 +79,7 @@ func resetCmdF(cmd *cobra.Command, args []string) error { } } - app.Global().Srv.Store.DropAllTables() + a.Srv.Store.DropAllTables() CommandPrettyPrintln("Database sucessfully reset") return nil diff --git a/cmd/platform/roles.go b/cmd/platform/roles.go index 1faf99d9e..ad64459e5 100644 --- a/cmd/platform/roles.go +++ b/cmd/platform/roles.go @@ -5,7 +5,6 @@ package main import ( "errors" - "github.com/mattermost/mattermost-server/app" "github.com/spf13/cobra" ) @@ -38,7 +37,8 @@ func init() { } func makeSystemAdminCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -52,7 +52,7 @@ func makeSystemAdminCmdF(cmd *cobra.Command, args []string) error { return errors.New("Unable to find user '" + args[i] + "'") } - if _, err := app.Global().UpdateUserRoles(user.Id, "system_admin system_user"); err != nil { + if _, err := a.UpdateUserRoles(user.Id, "system_admin system_user"); err != nil { return err } } @@ -61,7 +61,8 @@ func makeSystemAdminCmdF(cmd *cobra.Command, args []string) error { } func makeMemberCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -75,7 +76,7 @@ func makeMemberCmdF(cmd *cobra.Command, args []string) error { return errors.New("Unable to find user '" + args[i] + "'") } - if _, err := app.Global().UpdateUserRoles(user.Id, "system_user"); err != nil { + if _, err := a.UpdateUserRoles(user.Id, "system_user"); err != nil { return err } } diff --git a/cmd/platform/server.go b/cmd/platform/server.go index fe5f5272b..15c80134c 100644 --- a/cmd/platform/server.go +++ b/cmd/platform/server.go @@ -74,7 +74,7 @@ func runServer(configFileLocation string) { a := app.Global() a.NewServer() a.InitStores() - api.InitRouter() + a.Srv.Router = api.NewRouter() if model.BuildEnterpriseReady == "true" { a.LoadLicense() @@ -82,8 +82,8 @@ func runServer(configFileLocation string) { a.InitPlugins("plugins", "webapp/dist") wsapi.InitRouter() - api4.InitApi(false) - api.InitApi() + api4.InitApi(a.Srv.Router, false) + api.InitApi(a.Srv.Router) wsapi.InitApi() web.InitWeb() @@ -98,7 +98,7 @@ func runServer(configFileLocation string) { app.ReloadConfig() - resetStatuses() + resetStatuses(a) a.StartServer() @@ -107,13 +107,13 @@ func runServer(configFileLocation string) { manualtesting.InitManualTesting() } - setDiagnosticId() + setDiagnosticId(a) utils.RegenerateClientConfig() - go runSecurityJob() - go runDiagnosticsJob() + go runSecurityJob(a) + go runDiagnosticsJob(a) - go runTokenCleanupJob() - go runCommandWebhookCleanupJob() + go runTokenCleanupJob(a) + go runCommandWebhookCleanupJob(a) if complianceI := einterfaces.GetComplianceInterface(); complianceI != nil { complianceI.StartComplianceDailyJob() @@ -162,61 +162,69 @@ func runServer(configFileLocation string) { a.StopServer() } -func runSecurityJob() { - doSecurity() - model.CreateRecurringTask("Security", doSecurity, time.Hour*4) +func runSecurityJob(a *app.App) { + doSecurity(a) + model.CreateRecurringTask("Security", func() { + doSecurity(a) + }, time.Hour*4) } -func runDiagnosticsJob() { - doDiagnostics() - model.CreateRecurringTask("Diagnostics", doDiagnostics, time.Hour*24) +func runDiagnosticsJob(a *app.App) { + doDiagnostics(a) + model.CreateRecurringTask("Diagnostics", func() { + doDiagnostics(a) + }, time.Hour*24) } -func runTokenCleanupJob() { - doTokenCleanup() - model.CreateRecurringTask("Token Cleanup", doTokenCleanup, time.Hour*1) +func runTokenCleanupJob(a *app.App) { + doTokenCleanup(a) + model.CreateRecurringTask("Token Cleanup", func() { + doTokenCleanup(a) + }, time.Hour*1) } -func runCommandWebhookCleanupJob() { - doCommandWebhookCleanup() - model.CreateRecurringTask("Command Hook Cleanup", doCommandWebhookCleanup, time.Hour*1) +func runCommandWebhookCleanupJob(a *app.App) { + doCommandWebhookCleanup(a) + model.CreateRecurringTask("Command Hook Cleanup", func() { + doCommandWebhookCleanup(a) + }, time.Hour*1) } -func resetStatuses() { - if result := <-app.Global().Srv.Store.Status().ResetAll(); result.Err != nil { +func resetStatuses(a *app.App) { + if result := <-a.Srv.Store.Status().ResetAll(); result.Err != nil { l4g.Error(utils.T("mattermost.reset_status.error"), result.Err.Error()) } } -func setDiagnosticId() { - if result := <-app.Global().Srv.Store.System().Get(); result.Err == nil { +func setDiagnosticId(a *app.App) { + if result := <-a.Srv.Store.System().Get(); result.Err == nil { props := result.Data.(model.StringMap) id := props[model.SYSTEM_DIAGNOSTIC_ID] if len(id) == 0 { id = model.NewId() systemId := &model.System{Name: model.SYSTEM_DIAGNOSTIC_ID, Value: id} - <-app.Global().Srv.Store.System().Save(systemId) + <-a.Srv.Store.System().Save(systemId) } utils.CfgDiagnosticId = id } } -func doSecurity() { - app.Global().DoSecurityUpdateCheck() +func doSecurity(a *app.App) { + a.DoSecurityUpdateCheck() } -func doDiagnostics() { +func doDiagnostics(a *app.App) { if *utils.Cfg.LogSettings.EnableDiagnostics { - app.Global().SendDailyDiagnostics() + a.SendDailyDiagnostics() } } -func doTokenCleanup() { - app.Global().Srv.Store.Token().Cleanup() +func doTokenCleanup(a *app.App) { + a.Srv.Store.Token().Cleanup() } -func doCommandWebhookCleanup() { - app.Global().Srv.Store.CommandWebhook().Cleanup() +func doCommandWebhookCleanup(a *app.App) { + a.Srv.Store.CommandWebhook().Cleanup() } diff --git a/cmd/platform/team.go b/cmd/platform/team.go index d9e16cc2c..1662bd095 100644 --- a/cmd/platform/team.go +++ b/cmd/platform/team.go @@ -67,7 +67,8 @@ func init() { } func createTeamCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -94,7 +95,7 @@ func createTeamCmdF(cmd *cobra.Command, args []string) error { Type: teamType, } - if _, err := app.Global().CreateTeam(team); err != nil { + if _, err := a.CreateTeam(team); err != nil { return errors.New("Team creation failed: " + err.Error()) } @@ -102,7 +103,8 @@ func createTeamCmdF(cmd *cobra.Command, args []string) error { } func removeUsersCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -117,24 +119,25 @@ func removeUsersCmdF(cmd *cobra.Command, args []string) error { users := getUsersFromUserArgs(args[1:]) for i, user := range users { - removeUserFromTeam(team, user, args[i+1]) + removeUserFromTeam(a, team, user, args[i+1]) } return nil } -func removeUserFromTeam(team *model.Team, user *model.User, userArg string) { +func removeUserFromTeam(a *app.App, team *model.Team, user *model.User, userArg string) { if user == nil { CommandPrintErrorln("Can't find user '" + userArg + "'") return } - if err := app.Global().LeaveTeam(team, user); err != nil { + if err := a.LeaveTeam(team, user); err != nil { CommandPrintErrorln("Unable to remove '" + userArg + "' from " + team.Name + ". Error: " + err.Error()) } } func addUsersCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -149,24 +152,25 @@ func addUsersCmdF(cmd *cobra.Command, args []string) error { users := getUsersFromUserArgs(args[1:]) for i, user := range users { - addUserToTeam(team, user, args[i+1]) + addUserToTeam(a, team, user, args[i+1]) } return nil } -func addUserToTeam(team *model.Team, user *model.User, userArg string) { +func addUserToTeam(a *app.App, team *model.Team, user *model.User, userArg string) { if user == nil { CommandPrintErrorln("Can't find user '" + userArg + "'") return } - if err := app.Global().JoinUserToTeam(team, user, ""); err != nil { + if err := a.JoinUserToTeam(team, user, ""); err != nil { CommandPrintErrorln("Unable to add '" + userArg + "' to " + team.Name) } } func deleteTeamsCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -196,7 +200,7 @@ func deleteTeamsCmdF(cmd *cobra.Command, args []string) error { CommandPrintErrorln("Unable to find team '" + args[i] + "'") continue } - if err := deleteTeam(team); err != nil { + if err := deleteTeam(a, team); err != nil { CommandPrintErrorln("Unable to delete team '" + team.Name + "' error: " + err.Error()) } else { CommandPrettyPrintln("Deleted team '" + team.Name + "'") @@ -206,6 +210,6 @@ func deleteTeamsCmdF(cmd *cobra.Command, args []string) error { return nil } -func deleteTeam(team *model.Team) *model.AppError { - return app.Global().PermanentDeleteTeam(team) +func deleteTeam(a *app.App, team *model.Team) *model.AppError { + return a.PermanentDeleteTeam(team) } diff --git a/cmd/platform/test.go b/cmd/platform/test.go index e80880132..a7b89f40f 100644 --- a/cmd/platform/test.go +++ b/cmd/platform/test.go @@ -14,7 +14,6 @@ import ( "github.com/mattermost/mattermost-server/api" "github.com/mattermost/mattermost-server/api4" - "github.com/mattermost/mattermost-server/app" "github.com/mattermost/mattermost-server/utils" "github.com/mattermost/mattermost-server/wsapi" "github.com/spf13/cobra" @@ -46,43 +45,45 @@ func init() { } func webClientTestsCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } utils.InitTranslations(utils.Cfg.LocalizationSettings) - api.InitRouter() + a.Srv.Router = api.NewRouter() wsapi.InitRouter() - api4.InitApi(false) - api.InitApi() + api4.InitApi(a.Srv.Router, false) + api.InitApi(a.Srv.Router) wsapi.InitApi() setupClientTests() - app.Global().StartServer() + a.StartServer() runWebClientTests() - app.Global().StopServer() + a.StopServer() return nil } func serverForWebClientTestsCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } utils.InitTranslations(utils.Cfg.LocalizationSettings) - api.InitRouter() + a.Srv.Router = api.NewRouter() wsapi.InitRouter() - api4.InitApi(false) - api.InitApi() + api4.InitApi(a.Srv.Router, false) + api.InitApi(a.Srv.Router) wsapi.InitApi() setupClientTests() - app.Global().StartServer() + a.StartServer() c := make(chan os.Signal) signal.Notify(c, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) <-c - app.Global().StopServer() + a.StopServer() return nil } diff --git a/cmd/platform/user.go b/cmd/platform/user.go index 2275ea70c..a5a16049e 100644 --- a/cmd/platform/user.go +++ b/cmd/platform/user.go @@ -158,7 +158,8 @@ func init() { } func userActivateCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -166,14 +167,14 @@ func userActivateCmdF(cmd *cobra.Command, args []string) error { return errors.New("Expected at least one argument. See help text for details.") } - changeUsersActiveStatus(args, true) + changeUsersActiveStatus(a, args, true) return nil } -func changeUsersActiveStatus(userArgs []string, active bool) { +func changeUsersActiveStatus(a *app.App, userArgs []string, active bool) { users := getUsersFromUserArgs(userArgs) for i, user := range users { - err := changeUserActiveStatus(user, userArgs[i], active) + err := changeUserActiveStatus(a, user, userArgs[i], active) if err != nil { CommandPrintErrorln(err.Error()) @@ -181,14 +182,14 @@ func changeUsersActiveStatus(userArgs []string, active bool) { } } -func changeUserActiveStatus(user *model.User, userArg string, activate bool) error { +func changeUserActiveStatus(a *app.App, user *model.User, userArg string, activate bool) error { if user == nil { return fmt.Errorf("Can't find user '%v'", userArg) } if user.IsLDAPUser() { return errors.New("You can not modify the activation status of AD/LDAP accounts. Please modify through the AD/LDAP server.") } - if _, err := app.Global().UpdateActive(user, activate); err != nil { + if _, err := a.UpdateActive(user, activate); err != nil { return fmt.Errorf("Unable to change activation status of user: %v", userArg) } @@ -196,7 +197,8 @@ func changeUserActiveStatus(user *model.User, userArg string, activate bool) err } func userDeactivateCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -204,12 +206,13 @@ func userDeactivateCmdF(cmd *cobra.Command, args []string) error { return errors.New("Expected at least one argument. See help text for details.") } - changeUsersActiveStatus(args, false) + changeUsersActiveStatus(a, args, false) return nil } func userCreateCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -241,13 +244,10 @@ func userCreateCmdF(cmd *cobra.Command, args []string) error { Locale: locale, } - ruser, err := app.Global().CreateUser(user) - if err != nil { + if ruser, err := a.CreateUser(user); err != nil { return errors.New("Unable to create user. Error: " + err.Error()) - } - - if systemAdmin { - app.Global().UpdateUserRoles(ruser.Id, "system_user system_admin") + } else if systemAdmin { + a.UpdateUserRoles(ruser.Id, "system_user system_admin") } CommandPrettyPrintln("Created User") @@ -256,7 +256,8 @@ func userCreateCmdF(cmd *cobra.Command, args []string) error { } func userInviteCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + _, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -296,7 +297,8 @@ func inviteUser(email string, team *model.Team, teamArg string) error { } func resetUserPasswordCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -310,7 +312,7 @@ func resetUserPasswordCmdF(cmd *cobra.Command, args []string) error { } password := args[1] - if result := <-app.Global().Srv.Store.User().UpdatePassword(user.Id, model.HashPassword(password)); result.Err != nil { + if result := <-a.Srv.Store.User().UpdatePassword(user.Id, model.HashPassword(password)); result.Err != nil { return result.Err } @@ -318,7 +320,8 @@ func resetUserPasswordCmdF(cmd *cobra.Command, args []string) error { } func resetUserMfaCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + _, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -342,7 +345,8 @@ func resetUserMfaCmdF(cmd *cobra.Command, args []string) error { } func deleteUserCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -373,7 +377,7 @@ func deleteUserCmdF(cmd *cobra.Command, args []string) error { return errors.New("Unable to find user '" + args[i] + "'") } - if err := app.Global().PermanentDeleteUser(user); err != nil { + if err := a.PermanentDeleteUser(user); err != nil { return err } } @@ -382,7 +386,8 @@ func deleteUserCmdF(cmd *cobra.Command, args []string) error { } func deleteAllUsersCommandF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -406,7 +411,7 @@ func deleteAllUsersCommandF(cmd *cobra.Command, args []string) error { } } - if err := app.Global().PermanentDeleteAllUsers(); err != nil { + if err := a.PermanentDeleteAllUsers(); err != nil { return err } @@ -415,7 +420,8 @@ func deleteAllUsersCommandF(cmd *cobra.Command, args []string) error { } func migrateAuthCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + _, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -458,7 +464,8 @@ func migrateAuthCmdF(cmd *cobra.Command, args []string) error { } func verifyUserCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } @@ -473,7 +480,7 @@ func verifyUserCmdF(cmd *cobra.Command, args []string) error { CommandPrintErrorln("Unable to find user '" + args[i] + "'") continue } - if cresult := <-app.Global().Srv.Store.User().VerifyEmail(user.Id); cresult.Err != nil { + if cresult := <-a.Srv.Store.User().VerifyEmail(user.Id); cresult.Err != nil { CommandPrintErrorln("Unable to verify '" + args[i] + "' email. Error: " + cresult.Err.Error()) } } @@ -482,7 +489,8 @@ func verifyUserCmdF(cmd *cobra.Command, args []string) error { } func searchUserCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + _, err := initDBCommandContextCobra(cmd) + if err != nil { return err } diff --git a/cmd/platform/version.go b/cmd/platform/version.go index d9df65965..c34254c45 100644 --- a/cmd/platform/version.go +++ b/cmd/platform/version.go @@ -16,20 +16,21 @@ var versionCmd = &cobra.Command{ } func versionCmdF(cmd *cobra.Command, args []string) error { - if err := initDBCommandContextCobra(cmd); err != nil { + a, err := initDBCommandContextCobra(cmd) + if err != nil { return err } - printVersion() + printVersion(a) return nil } -func printVersion() { +func printVersion(a *app.App) { CommandPrintln("Version: " + model.CurrentVersion) CommandPrintln("Build Number: " + model.BuildNumber) CommandPrintln("Build Date: " + model.BuildDate) CommandPrintln("Build Hash: " + model.BuildHash) CommandPrintln("Build Enterprise Ready: " + model.BuildEnterpriseReady) - CommandPrintln("DB Version: " + app.Global().Srv.Store.(*store.LayeredStore).DatabaseLayer.GetCurrentSchemaVersion()) + CommandPrintln("DB Version: " + a.Srv.Store.(*store.LayeredStore).DatabaseLayer.GetCurrentSchemaVersion()) } diff --git a/web/web_test.go b/web/web_test.go index 0d66b87a9..be3d3f309 100644 --- a/web/web_test.go +++ b/web/web_test.go @@ -5,7 +5,6 @@ package web import ( "testing" - "time" "github.com/mattermost/mattermost-server/api" "github.com/mattermost/mattermost-server/api4" @@ -19,30 +18,32 @@ import ( var ApiClient *model.Client var URL string -func Setup() { - if app.Global().Srv == nil { +func Setup() *app.App { + a := app.Global() + if a.Srv == nil { utils.TranslationsPreInit() utils.LoadConfig("config.json") utils.InitTranslations(utils.Cfg.LocalizationSettings) - app.Global().NewServer() - app.Global().InitStores() - api.InitRouter() - app.Global().StartServer() - api4.InitApi(false) - api.InitApi() + a.NewServer() + a.InitStores() + a.Srv.Router = api.NewRouter() + a.StartServer() + api4.InitApi(a.Srv.Router, false) + api.InitApi(a.Srv.Router) InitWeb() URL = "http://localhost" + *utils.Cfg.ServiceSettings.ListenAddress ApiClient = model.NewClient(URL) - app.Global().Srv.Store.MarkSystemRanUnitTests() + a.Srv.Store.MarkSystemRanUnitTests() *utils.Cfg.TeamSettings.EnableOpenServer = true } + return a } -func TearDown() { - if app.Global().Srv != nil { - app.Global().StopServer() +func TearDown(a *app.App) { + if a.Srv != nil { + a.StopServer() } } @@ -64,20 +65,21 @@ func TestStatic(t *testing.T) { */ func TestIncomingWebhook(t *testing.T) { - Setup() + a := Setup() + defer TearDown(a) user := &model.User{Email: model.NewId() + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1"} user = ApiClient.Must(ApiClient.CreateUser(user, "")).Data.(*model.User) - store.Must(app.Global().Srv.Store.User().VerifyEmail(user.Id)) + store.Must(a.Srv.Store.User().VerifyEmail(user.Id)) ApiClient.Login(user.Email, "passwd1") team := &model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: "test@nowhere.com", Type: model.TEAM_OPEN} team = ApiClient.Must(ApiClient.CreateTeam(team)).Data.(*model.Team) - app.Global().JoinUserToTeam(team, user, "") + a.JoinUserToTeam(team, user, "") - app.Global().UpdateUserRoles(user.Id, model.ROLE_SYSTEM_ADMIN.Id) + a.UpdateUserRoles(user.Id, model.ROLE_SYSTEM_ADMIN.Id) ApiClient.SetTeamId(team.Id) channel1 := &model.Channel{DisplayName: "Test API Name", Name: "zz" + model.NewId() + "a", Type: model.CHANNEL_OPEN, TeamId: team.Id} @@ -113,15 +115,6 @@ func TestIncomingWebhook(t *testing.T) { } } -func TestZZWebTearDown(t *testing.T) { - // *IMPORTANT* - // This should be the last function in any test file - // that calls Setup() - // Should be in the last file too sorted by name - time.Sleep(2 * time.Second) - TearDown() -} - func TestCheckBrowserCompatability(t *testing.T) { //test should fail browser compatibility check with Mozilla FF 40.1 -- cgit v1.2.3-1-g7c22