github.com/mattermost/mattermost-server/v5@v5.39.3/api4/apitestlib.go (about)

     1  // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
     2  // See LICENSE.txt for license information.
     3  
     4  package api4
     5  
     6  import (
     7  	"context"
     8  	"fmt"
     9  	"io/ioutil"
    10  	"math/rand"
    11  	"net"
    12  	"net/http"
    13  	"os"
    14  	"path/filepath"
    15  	"strings"
    16  	"sync"
    17  	"testing"
    18  	"time"
    19  
    20  	s3 "github.com/minio/minio-go/v7"
    21  	"github.com/minio/minio-go/v7/pkg/credentials"
    22  	"github.com/stretchr/testify/require"
    23  
    24  	"github.com/mattermost/mattermost-server/v5/app"
    25  	"github.com/mattermost/mattermost-server/v5/app/request"
    26  	"github.com/mattermost/mattermost-server/v5/config"
    27  	"github.com/mattermost/mattermost-server/v5/model"
    28  	"github.com/mattermost/mattermost-server/v5/plugin/plugintest/mock"
    29  	"github.com/mattermost/mattermost-server/v5/services/searchengine"
    30  	"github.com/mattermost/mattermost-server/v5/shared/mlog"
    31  	"github.com/mattermost/mattermost-server/v5/store"
    32  	"github.com/mattermost/mattermost-server/v5/store/localcachelayer"
    33  	"github.com/mattermost/mattermost-server/v5/store/storetest/mocks"
    34  	"github.com/mattermost/mattermost-server/v5/testlib"
    35  	"github.com/mattermost/mattermost-server/v5/utils"
    36  	"github.com/mattermost/mattermost-server/v5/web"
    37  	"github.com/mattermost/mattermost-server/v5/wsapi"
    38  )
    39  
    40  type TestHelper struct {
    41  	App         *app.App
    42  	Server      *app.Server
    43  	ConfigStore *config.Store
    44  
    45  	Context              *request.Context
    46  	Client               *model.Client4
    47  	BasicUser            *model.User
    48  	BasicUser2           *model.User
    49  	TeamAdminUser        *model.User
    50  	BasicTeam            *model.Team
    51  	BasicChannel         *model.Channel
    52  	BasicPrivateChannel  *model.Channel
    53  	BasicPrivateChannel2 *model.Channel
    54  	BasicDeletedChannel  *model.Channel
    55  	BasicChannel2        *model.Channel
    56  	BasicPost            *model.Post
    57  	Group                *model.Group
    58  
    59  	SystemAdminClient *model.Client4
    60  	SystemAdminUser   *model.User
    61  	tempWorkspace     string
    62  
    63  	SystemManagerClient *model.Client4
    64  	SystemManagerUser   *model.User
    65  
    66  	LocalClient *model.Client4
    67  
    68  	IncludeCacheLayer bool
    69  }
    70  
    71  var mainHelper *testlib.MainHelper
    72  
    73  func SetMainHelper(mh *testlib.MainHelper) {
    74  	mainHelper = mh
    75  }
    76  
    77  func setupTestHelper(dbStore store.Store, searchEngine *searchengine.Broker, enterprise bool, includeCache bool,
    78  	updateConfig func(*model.Config), options []app.Option) *TestHelper {
    79  	tempWorkspace, err := ioutil.TempDir("", "apptest")
    80  	if err != nil {
    81  		panic(err)
    82  	}
    83  
    84  	memoryStore, err := config.NewMemoryStoreWithOptions(&config.MemoryStoreOptions{IgnoreEnvironmentOverrides: true})
    85  	if err != nil {
    86  		panic("failed to initialize memory store: " + err.Error())
    87  	}
    88  
    89  	memoryConfig := &model.Config{}
    90  	memoryConfig.SetDefaults()
    91  	*memoryConfig.PluginSettings.Directory = filepath.Join(tempWorkspace, "plugins")
    92  	*memoryConfig.PluginSettings.ClientDirectory = filepath.Join(tempWorkspace, "webapp")
    93  	memoryConfig.ServiceSettings.EnableLocalMode = model.NewBool(true)
    94  	*memoryConfig.ServiceSettings.LocalModeSocketLocation = filepath.Join(tempWorkspace, "mattermost_local.sock")
    95  	*memoryConfig.AnnouncementSettings.AdminNoticesEnabled = false
    96  	*memoryConfig.AnnouncementSettings.UserNoticesEnabled = false
    97  	*memoryConfig.PluginSettings.AutomaticPrepackagedPlugins = false
    98  	if updateConfig != nil {
    99  		updateConfig(memoryConfig)
   100  	}
   101  	memoryStore.Set(memoryConfig)
   102  
   103  	configStore, err := config.NewStoreFromBacking(memoryStore, nil, false)
   104  	if err != nil {
   105  		panic(err)
   106  	}
   107  
   108  	options = append(options, app.ConfigStore(configStore))
   109  	if includeCache {
   110  		// Adds the cache layer to the test store
   111  		options = append(options, app.StoreOverride(func(s *app.Server) store.Store {
   112  			lcl, err2 := localcachelayer.NewLocalCacheLayer(dbStore, s.Metrics, s.Cluster, s.CacheProvider)
   113  			if err2 != nil {
   114  				panic(err2)
   115  			}
   116  			return lcl
   117  		}))
   118  	} else {
   119  		options = append(options, app.StoreOverride(dbStore))
   120  	}
   121  
   122  	s, err := app.NewServer(options...)
   123  	if err != nil {
   124  		panic(err)
   125  	}
   126  
   127  	th := &TestHelper{
   128  		App:               app.New(app.ServerConnector(s)),
   129  		Server:            s,
   130  		ConfigStore:       configStore,
   131  		IncludeCacheLayer: includeCache,
   132  		Context:           &request.Context{},
   133  	}
   134  
   135  	if s.SearchEngine != nil && s.SearchEngine.BleveEngine != nil && searchEngine != nil {
   136  		searchEngine.BleveEngine = s.SearchEngine.BleveEngine
   137  	}
   138  
   139  	if searchEngine != nil {
   140  		th.App.SetSearchEngine(searchEngine)
   141  	}
   142  
   143  	th.App.UpdateConfig(func(cfg *model.Config) {
   144  		*cfg.TeamSettings.MaxUsersPerTeam = 50
   145  		*cfg.RateLimitSettings.Enable = false
   146  		*cfg.EmailSettings.SendEmailNotifications = true
   147  		*cfg.ServiceSettings.SiteURL = ""
   148  
   149  		// Disable sniffing, otherwise elastic client fails to connect to docker node
   150  		// More details: https://github.com/olivere/elastic/wiki/Sniffing
   151  		*cfg.ElasticsearchSettings.Sniff = false
   152  
   153  		*cfg.TeamSettings.EnableOpenServer = true
   154  
   155  		// Disable strict password requirements for test
   156  		*cfg.PasswordSettings.MinimumLength = 5
   157  		*cfg.PasswordSettings.Lowercase = false
   158  		*cfg.PasswordSettings.Uppercase = false
   159  		*cfg.PasswordSettings.Symbol = false
   160  		*cfg.PasswordSettings.Number = false
   161  
   162  		*cfg.ServiceSettings.ListenAddress = ":0"
   163  	})
   164  	if err := th.Server.Start(); err != nil {
   165  		panic(err)
   166  	}
   167  
   168  	Init(th.App, th.App.Srv().Router)
   169  	InitLocal(th.App, th.App.Srv().LocalRouter)
   170  	web.New(th.App, th.App.Srv().Router)
   171  	wsapi.Init(th.App.Srv())
   172  
   173  	if enterprise {
   174  		th.App.Srv().SetLicense(model.NewTestLicense())
   175  		th.App.Srv().Jobs.InitWorkers()
   176  		th.App.Srv().Jobs.InitSchedulers()
   177  	} else {
   178  		th.App.Srv().SetLicense(nil)
   179  	}
   180  
   181  	th.Client = th.CreateClient()
   182  	th.SystemAdminClient = th.CreateClient()
   183  	th.SystemManagerClient = th.CreateClient()
   184  
   185  	// Verify handling of the supported true/false values by randomizing on each run.
   186  	rand.Seed(time.Now().UTC().UnixNano())
   187  	trueValues := []string{"1", "t", "T", "TRUE", "true", "True"}
   188  	falseValues := []string{"0", "f", "F", "FALSE", "false", "False"}
   189  	trueString := trueValues[rand.Intn(len(trueValues))]
   190  	falseString := falseValues[rand.Intn(len(falseValues))]
   191  	mlog.Debug("Configured Client4 bool string values", mlog.String("true", trueString), mlog.String("false", falseString))
   192  	th.Client.SetBoolString(true, trueString)
   193  	th.Client.SetBoolString(false, falseString)
   194  
   195  	th.LocalClient = th.CreateLocalClient(*memoryConfig.ServiceSettings.LocalModeSocketLocation)
   196  
   197  	if th.tempWorkspace == "" {
   198  		th.tempWorkspace = tempWorkspace
   199  	}
   200  
   201  	return th
   202  }
   203  
   204  func SetupEnterprise(tb testing.TB) *TestHelper {
   205  	if testing.Short() {
   206  		tb.SkipNow()
   207  	}
   208  
   209  	if mainHelper == nil {
   210  		tb.SkipNow()
   211  	}
   212  
   213  	dbStore := mainHelper.GetStore()
   214  	dbStore.DropAllTables()
   215  	dbStore.MarkSystemRanUnitTests()
   216  	mainHelper.PreloadMigrations()
   217  	searchEngine := mainHelper.GetSearchEngine()
   218  	th := setupTestHelper(dbStore, searchEngine, true, true, nil, nil)
   219  	th.InitLogin()
   220  	return th
   221  }
   222  
   223  func Setup(tb testing.TB) *TestHelper {
   224  	if testing.Short() {
   225  		tb.SkipNow()
   226  	}
   227  
   228  	if mainHelper == nil {
   229  		tb.SkipNow()
   230  	}
   231  
   232  	dbStore := mainHelper.GetStore()
   233  	dbStore.DropAllTables()
   234  	dbStore.MarkSystemRanUnitTests()
   235  	mainHelper.PreloadMigrations()
   236  	searchEngine := mainHelper.GetSearchEngine()
   237  	th := setupTestHelper(dbStore, searchEngine, false, true, nil, nil)
   238  	th.InitLogin()
   239  	return th
   240  }
   241  
   242  func SetupConfig(tb testing.TB, updateConfig func(cfg *model.Config)) *TestHelper {
   243  	if testing.Short() {
   244  		tb.SkipNow()
   245  	}
   246  
   247  	if mainHelper == nil {
   248  		tb.SkipNow()
   249  	}
   250  
   251  	dbStore := mainHelper.GetStore()
   252  	dbStore.DropAllTables()
   253  	dbStore.MarkSystemRanUnitTests()
   254  	searchEngine := mainHelper.GetSearchEngine()
   255  	th := setupTestHelper(dbStore, searchEngine, false, true, updateConfig, nil)
   256  	th.InitLogin()
   257  	return th
   258  }
   259  
   260  func SetupConfigWithStoreMock(tb testing.TB, updateConfig func(cfg *model.Config)) *TestHelper {
   261  	th := setupTestHelper(testlib.GetMockStoreForSetupFunctions(), nil, false, false, updateConfig, nil)
   262  	statusMock := mocks.StatusStore{}
   263  	statusMock.On("UpdateExpiredDNDStatuses").Return([]*model.Status{}, nil)
   264  	statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.STATUS_ONLINE}, nil)
   265  	statusMock.On("UpdateLastActivityAt", "user1", mock.Anything).Return(nil)
   266  	statusMock.On("SaveOrUpdate", mock.AnythingOfType("*model.Status")).Return(nil)
   267  	emptyMockStore := mocks.Store{}
   268  	emptyMockStore.On("Close").Return(nil)
   269  	emptyMockStore.On("Status").Return(&statusMock)
   270  	th.App.Srv().Store = &emptyMockStore
   271  	return th
   272  }
   273  
   274  func SetupWithStoreMock(tb testing.TB) *TestHelper {
   275  	th := setupTestHelper(testlib.GetMockStoreForSetupFunctions(), nil, false, false, nil, nil)
   276  	statusMock := mocks.StatusStore{}
   277  	statusMock.On("UpdateExpiredDNDStatuses").Return([]*model.Status{}, nil)
   278  	statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.STATUS_ONLINE}, nil)
   279  	statusMock.On("UpdateLastActivityAt", "user1", mock.Anything).Return(nil)
   280  	statusMock.On("SaveOrUpdate", mock.AnythingOfType("*model.Status")).Return(nil)
   281  	emptyMockStore := mocks.Store{}
   282  	emptyMockStore.On("Close").Return(nil)
   283  	emptyMockStore.On("Status").Return(&statusMock)
   284  	th.App.Srv().Store = &emptyMockStore
   285  	return th
   286  }
   287  
   288  func SetupEnterpriseWithStoreMock(tb testing.TB) *TestHelper {
   289  	th := setupTestHelper(testlib.GetMockStoreForSetupFunctions(), nil, true, false, nil, nil)
   290  	statusMock := mocks.StatusStore{}
   291  	statusMock.On("UpdateExpiredDNDStatuses").Return([]*model.Status{}, nil)
   292  	statusMock.On("Get", "user1").Return(&model.Status{UserId: "user1", Status: model.STATUS_ONLINE}, nil)
   293  	statusMock.On("UpdateLastActivityAt", "user1", mock.Anything).Return(nil)
   294  	statusMock.On("SaveOrUpdate", mock.AnythingOfType("*model.Status")).Return(nil)
   295  	emptyMockStore := mocks.Store{}
   296  	emptyMockStore.On("Close").Return(nil)
   297  	emptyMockStore.On("Status").Return(&statusMock)
   298  	th.App.Srv().Store = &emptyMockStore
   299  	return th
   300  }
   301  
   302  func SetupWithServerOptions(tb testing.TB, options []app.Option) *TestHelper {
   303  	if testing.Short() {
   304  		tb.SkipNow()
   305  	}
   306  
   307  	if mainHelper == nil {
   308  		tb.SkipNow()
   309  	}
   310  
   311  	dbStore := mainHelper.GetStore()
   312  	dbStore.DropAllTables()
   313  	dbStore.MarkSystemRanUnitTests()
   314  	mainHelper.PreloadMigrations()
   315  	searchEngine := mainHelper.GetSearchEngine()
   316  	th := setupTestHelper(dbStore, searchEngine, false, true, nil, options)
   317  	th.InitLogin()
   318  	return th
   319  }
   320  
   321  func (th *TestHelper) ShutdownApp() {
   322  	done := make(chan bool)
   323  	go func() {
   324  		th.Server.Shutdown()
   325  		close(done)
   326  	}()
   327  
   328  	select {
   329  	case <-done:
   330  	case <-time.After(30 * time.Second):
   331  		// panic instead of fatal to terminate all tests in this package, otherwise the
   332  		// still running App could spuriously fail subsequent tests.
   333  		panic("failed to shutdown App within 30 seconds")
   334  	}
   335  }
   336  
   337  func (th *TestHelper) TearDown() {
   338  	utils.DisableDebugLogForTest()
   339  	if th.IncludeCacheLayer {
   340  		// Clean all the caches
   341  		th.App.Srv().InvalidateAllCaches()
   342  	}
   343  
   344  	th.ShutdownApp()
   345  
   346  	utils.EnableDebugLogForTest()
   347  }
   348  
   349  var initBasicOnce sync.Once
   350  var userCache struct {
   351  	SystemAdminUser   *model.User
   352  	SystemManagerUser *model.User
   353  	TeamAdminUser     *model.User
   354  	BasicUser         *model.User
   355  	BasicUser2        *model.User
   356  }
   357  
   358  func (th *TestHelper) InitLogin() *TestHelper {
   359  	th.waitForConnectivity()
   360  
   361  	// create users once and cache them because password hashing is slow
   362  	initBasicOnce.Do(func() {
   363  		th.SystemAdminUser = th.CreateUser()
   364  		th.App.UpdateUserRoles(th.SystemAdminUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID, false)
   365  		th.SystemAdminUser, _ = th.App.GetUser(th.SystemAdminUser.Id)
   366  		userCache.SystemAdminUser = th.SystemAdminUser.DeepCopy()
   367  
   368  		th.SystemManagerUser = th.CreateUser()
   369  		th.App.UpdateUserRoles(th.SystemManagerUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_MANAGER_ROLE_ID, false)
   370  		th.SystemManagerUser, _ = th.App.GetUser(th.SystemManagerUser.Id)
   371  		userCache.SystemManagerUser = th.SystemManagerUser.DeepCopy()
   372  
   373  		th.TeamAdminUser = th.CreateUser()
   374  		th.App.UpdateUserRoles(th.TeamAdminUser.Id, model.SYSTEM_USER_ROLE_ID, false)
   375  		th.TeamAdminUser, _ = th.App.GetUser(th.TeamAdminUser.Id)
   376  		userCache.TeamAdminUser = th.TeamAdminUser.DeepCopy()
   377  
   378  		th.BasicUser = th.CreateUser()
   379  		th.BasicUser, _ = th.App.GetUser(th.BasicUser.Id)
   380  		userCache.BasicUser = th.BasicUser.DeepCopy()
   381  
   382  		th.BasicUser2 = th.CreateUser()
   383  		th.BasicUser2, _ = th.App.GetUser(th.BasicUser2.Id)
   384  		userCache.BasicUser2 = th.BasicUser2.DeepCopy()
   385  	})
   386  	// restore cached users
   387  	th.SystemAdminUser = userCache.SystemAdminUser.DeepCopy()
   388  	th.SystemManagerUser = userCache.SystemManagerUser.DeepCopy()
   389  	th.TeamAdminUser = userCache.TeamAdminUser.DeepCopy()
   390  	th.BasicUser = userCache.BasicUser.DeepCopy()
   391  	th.BasicUser2 = userCache.BasicUser2.DeepCopy()
   392  	mainHelper.GetSQLStore().GetMaster().Insert(th.SystemAdminUser, th.TeamAdminUser, th.BasicUser, th.BasicUser2, th.SystemManagerUser)
   393  	// restore non hashed password for login
   394  	th.SystemAdminUser.Password = "Pa$$word11"
   395  	th.TeamAdminUser.Password = "Pa$$word11"
   396  	th.BasicUser.Password = "Pa$$word11"
   397  	th.BasicUser2.Password = "Pa$$word11"
   398  	th.SystemManagerUser.Password = "Pa$$word11"
   399  
   400  	var wg sync.WaitGroup
   401  	wg.Add(3)
   402  	go func() {
   403  		th.LoginSystemAdmin()
   404  		wg.Done()
   405  	}()
   406  	go func() {
   407  		th.LoginSystemManager()
   408  		wg.Done()
   409  	}()
   410  	go func() {
   411  		th.LoginTeamAdmin()
   412  		wg.Done()
   413  	}()
   414  	wg.Wait()
   415  	return th
   416  }
   417  
   418  func (th *TestHelper) InitBasic() *TestHelper {
   419  	th.BasicTeam = th.CreateTeam()
   420  	th.BasicChannel = th.CreatePublicChannel()
   421  	th.BasicPrivateChannel = th.CreatePrivateChannel()
   422  	th.BasicPrivateChannel2 = th.CreatePrivateChannel()
   423  	th.BasicDeletedChannel = th.CreatePublicChannel()
   424  	th.BasicChannel2 = th.CreatePublicChannel()
   425  	th.BasicPost = th.CreatePost()
   426  	th.LinkUserToTeam(th.BasicUser, th.BasicTeam)
   427  	th.LinkUserToTeam(th.BasicUser2, th.BasicTeam)
   428  	th.App.AddUserToChannel(th.BasicUser, th.BasicChannel, false)
   429  	th.App.AddUserToChannel(th.BasicUser2, th.BasicChannel, false)
   430  	th.App.AddUserToChannel(th.BasicUser, th.BasicChannel2, false)
   431  	th.App.AddUserToChannel(th.BasicUser2, th.BasicChannel2, false)
   432  	th.App.AddUserToChannel(th.BasicUser, th.BasicPrivateChannel, false)
   433  	th.App.AddUserToChannel(th.BasicUser2, th.BasicPrivateChannel, false)
   434  	th.App.AddUserToChannel(th.BasicUser, th.BasicDeletedChannel, false)
   435  	th.App.AddUserToChannel(th.BasicUser2, th.BasicDeletedChannel, false)
   436  	th.App.UpdateUserRoles(th.BasicUser.Id, model.SYSTEM_USER_ROLE_ID, false)
   437  	th.Client.DeleteChannel(th.BasicDeletedChannel.Id)
   438  	th.LoginBasic()
   439  	th.Group = th.CreateGroup()
   440  
   441  	return th
   442  }
   443  
   444  func (th *TestHelper) waitForConnectivity() {
   445  	for i := 0; i < 1000; i++ {
   446  		conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%v", th.App.Srv().ListenAddr.Port))
   447  		if err == nil {
   448  			conn.Close()
   449  			return
   450  		}
   451  		time.Sleep(time.Millisecond * 20)
   452  	}
   453  	panic("unable to connect")
   454  }
   455  
   456  func (th *TestHelper) CreateClient() *model.Client4 {
   457  	return model.NewAPIv4Client(fmt.Sprintf("http://localhost:%v", th.App.Srv().ListenAddr.Port))
   458  }
   459  
   460  // ToDo: maybe move this to NewAPIv4SocketClient and reuse it in mmctl
   461  func (th *TestHelper) CreateLocalClient(socketPath string) *model.Client4 {
   462  	httpClient := &http.Client{
   463  		Transport: &http.Transport{
   464  			Dial: func(network, addr string) (net.Conn, error) {
   465  				return net.Dial("unix", socketPath)
   466  			},
   467  		},
   468  	}
   469  
   470  	return &model.Client4{
   471  		ApiUrl:     "http://_" + model.API_URL_SUFFIX,
   472  		HttpClient: httpClient,
   473  	}
   474  }
   475  
   476  func (th *TestHelper) CreateWebSocketClient() (*model.WebSocketClient, *model.AppError) {
   477  	return model.NewWebSocketClient4(fmt.Sprintf("ws://localhost:%v", th.App.Srv().ListenAddr.Port), th.Client.AuthToken)
   478  }
   479  
   480  func (th *TestHelper) CreateWebSocketSystemAdminClient() (*model.WebSocketClient, *model.AppError) {
   481  	return model.NewWebSocketClient4(fmt.Sprintf("ws://localhost:%v", th.App.Srv().ListenAddr.Port), th.SystemAdminClient.AuthToken)
   482  }
   483  
   484  func (th *TestHelper) CreateWebSocketSystemManagerClient() (*model.WebSocketClient, *model.AppError) {
   485  	return model.NewWebSocketClient4(fmt.Sprintf("ws://localhost:%v", th.App.Srv().ListenAddr.Port), th.SystemManagerClient.AuthToken)
   486  }
   487  
   488  func (th *TestHelper) CreateWebSocketClientWithClient(client *model.Client4) (*model.WebSocketClient, *model.AppError) {
   489  	return model.NewWebSocketClient4(fmt.Sprintf("ws://localhost:%v", th.App.Srv().ListenAddr.Port), client.AuthToken)
   490  }
   491  
   492  func (th *TestHelper) CreateBotWithSystemAdminClient() *model.Bot {
   493  	return th.CreateBotWithClient((th.SystemAdminClient))
   494  }
   495  
   496  func (th *TestHelper) CreateBotWithClient(client *model.Client4) *model.Bot {
   497  	bot := &model.Bot{
   498  		Username:    GenerateTestUsername(),
   499  		DisplayName: "a bot",
   500  		Description: "bot",
   501  	}
   502  
   503  	utils.DisableDebugLogForTest()
   504  	rbot, resp := client.CreateBot(bot)
   505  	if resp.Error != nil {
   506  		panic(resp.Error)
   507  	}
   508  	utils.EnableDebugLogForTest()
   509  	return rbot
   510  }
   511  
   512  func (th *TestHelper) CreateUser() *model.User {
   513  	return th.CreateUserWithClient(th.Client)
   514  }
   515  
   516  func (th *TestHelper) CreateTeam() *model.Team {
   517  	return th.CreateTeamWithClient(th.Client)
   518  }
   519  
   520  func (th *TestHelper) CreateTeamWithClient(client *model.Client4) *model.Team {
   521  	id := model.NewId()
   522  	team := &model.Team{
   523  		DisplayName: "dn_" + id,
   524  		Name:        GenerateTestTeamName(),
   525  		Email:       th.GenerateTestEmail(),
   526  		Type:        model.TEAM_OPEN,
   527  	}
   528  
   529  	utils.DisableDebugLogForTest()
   530  	rteam, resp := client.CreateTeam(team)
   531  	if resp.Error != nil {
   532  		panic(resp.Error)
   533  	}
   534  	utils.EnableDebugLogForTest()
   535  	return rteam
   536  }
   537  
   538  func (th *TestHelper) CreateUserWithClient(client *model.Client4) *model.User {
   539  	id := model.NewId()
   540  
   541  	user := &model.User{
   542  		Email:     th.GenerateTestEmail(),
   543  		Username:  GenerateTestUsername(),
   544  		Nickname:  "nn_" + id,
   545  		FirstName: "f_" + id,
   546  		LastName:  "l_" + id,
   547  		Password:  "Pa$$word11",
   548  	}
   549  
   550  	utils.DisableDebugLogForTest()
   551  	ruser, response := client.CreateUser(user)
   552  	if response.Error != nil {
   553  		panic(response.Error)
   554  	}
   555  
   556  	ruser.Password = "Pa$$word11"
   557  	_, err := th.App.Srv().Store.User().VerifyEmail(ruser.Id, ruser.Email)
   558  	if err != nil {
   559  		return nil
   560  	}
   561  	utils.EnableDebugLogForTest()
   562  	return ruser
   563  }
   564  
   565  func (th *TestHelper) CreateUserWithAuth(authService string) *model.User {
   566  	id := model.NewId()
   567  	user := &model.User{
   568  		Email:         "success+" + id + "@simulator.amazonses.com",
   569  		Username:      "un_" + id,
   570  		Nickname:      "nn_" + id,
   571  		EmailVerified: true,
   572  		AuthService:   authService,
   573  	}
   574  	user, err := th.App.CreateUser(th.Context, user)
   575  	if err != nil {
   576  		panic(err)
   577  	}
   578  	return user
   579  }
   580  
   581  func (th *TestHelper) SetupLdapConfig() {
   582  	th.App.UpdateConfig(func(cfg *model.Config) {
   583  		*cfg.ServiceSettings.EnableMultifactorAuthentication = true
   584  		*cfg.LdapSettings.Enable = true
   585  		*cfg.LdapSettings.EnableSync = true
   586  		*cfg.LdapSettings.LdapServer = "dockerhost"
   587  		*cfg.LdapSettings.BaseDN = "dc=mm,dc=test,dc=com"
   588  		*cfg.LdapSettings.BindUsername = "cn=admin,dc=mm,dc=test,dc=com"
   589  		*cfg.LdapSettings.BindPassword = "mostest"
   590  		*cfg.LdapSettings.FirstNameAttribute = "cn"
   591  		*cfg.LdapSettings.LastNameAttribute = "sn"
   592  		*cfg.LdapSettings.NicknameAttribute = "cn"
   593  		*cfg.LdapSettings.EmailAttribute = "mail"
   594  		*cfg.LdapSettings.UsernameAttribute = "uid"
   595  		*cfg.LdapSettings.IdAttribute = "cn"
   596  		*cfg.LdapSettings.LoginIdAttribute = "uid"
   597  		*cfg.LdapSettings.SkipCertificateVerification = true
   598  		*cfg.LdapSettings.GroupFilter = ""
   599  		*cfg.LdapSettings.GroupDisplayNameAttribute = "cN"
   600  		*cfg.LdapSettings.GroupIdAttribute = "entRyUuId"
   601  		*cfg.LdapSettings.MaxPageSize = 0
   602  	})
   603  	th.App.Srv().SetLicense(model.NewTestLicense("ldap"))
   604  }
   605  
   606  func (th *TestHelper) SetupSamlConfig() {
   607  	th.App.UpdateConfig(func(cfg *model.Config) {
   608  		*cfg.SamlSettings.Enable = true
   609  		*cfg.SamlSettings.Verify = false
   610  		*cfg.SamlSettings.Encrypt = false
   611  		*cfg.SamlSettings.IdpUrl = "https://does.notmatter.com"
   612  		*cfg.SamlSettings.IdpDescriptorUrl = "https://localhost/adfs/services/trust"
   613  		*cfg.SamlSettings.AssertionConsumerServiceURL = "https://localhost/login/sso/saml"
   614  		*cfg.SamlSettings.ServiceProviderIdentifier = "https://localhost/login/sso/saml"
   615  		*cfg.SamlSettings.IdpCertificateFile = app.SamlIdpCertificateName
   616  		*cfg.SamlSettings.PrivateKeyFile = app.SamlPrivateKeyName
   617  		*cfg.SamlSettings.PublicCertificateFile = app.SamlPublicCertificateName
   618  		*cfg.SamlSettings.EmailAttribute = "Email"
   619  		*cfg.SamlSettings.UsernameAttribute = "Username"
   620  		*cfg.SamlSettings.FirstNameAttribute = "FirstName"
   621  		*cfg.SamlSettings.LastNameAttribute = "LastName"
   622  		*cfg.SamlSettings.NicknameAttribute = ""
   623  		*cfg.SamlSettings.PositionAttribute = ""
   624  		*cfg.SamlSettings.LocaleAttribute = ""
   625  		*cfg.SamlSettings.SignatureAlgorithm = model.SAML_SETTINGS_SIGNATURE_ALGORITHM_SHA256
   626  		*cfg.SamlSettings.CanonicalAlgorithm = model.SAML_SETTINGS_CANONICAL_ALGORITHM_C14N11
   627  	})
   628  	th.App.Srv().SetLicense(model.NewTestLicense("saml"))
   629  }
   630  
   631  func (th *TestHelper) CreatePublicChannel() *model.Channel {
   632  	return th.CreateChannelWithClient(th.Client, model.CHANNEL_OPEN)
   633  }
   634  
   635  func (th *TestHelper) CreatePrivateChannel() *model.Channel {
   636  	return th.CreateChannelWithClient(th.Client, model.CHANNEL_PRIVATE)
   637  }
   638  
   639  func (th *TestHelper) CreateChannelWithClient(client *model.Client4, channelType string) *model.Channel {
   640  	return th.CreateChannelWithClientAndTeam(client, channelType, th.BasicTeam.Id)
   641  }
   642  
   643  func (th *TestHelper) CreateChannelWithClientAndTeam(client *model.Client4, channelType string, teamId string) *model.Channel {
   644  	id := model.NewId()
   645  
   646  	channel := &model.Channel{
   647  		DisplayName: "dn_" + id,
   648  		Name:        GenerateTestChannelName(),
   649  		Type:        channelType,
   650  		TeamId:      teamId,
   651  	}
   652  
   653  	utils.DisableDebugLogForTest()
   654  	rchannel, resp := client.CreateChannel(channel)
   655  	if resp.Error != nil {
   656  		panic(resp.Error)
   657  	}
   658  	utils.EnableDebugLogForTest()
   659  	return rchannel
   660  }
   661  
   662  func (th *TestHelper) CreatePost() *model.Post {
   663  	return th.CreatePostWithClient(th.Client, th.BasicChannel)
   664  }
   665  
   666  func (th *TestHelper) CreatePinnedPost() *model.Post {
   667  	return th.CreatePinnedPostWithClient(th.Client, th.BasicChannel)
   668  }
   669  
   670  func (th *TestHelper) CreateMessagePost(message string) *model.Post {
   671  	return th.CreateMessagePostWithClient(th.Client, th.BasicChannel, message)
   672  }
   673  
   674  func (th *TestHelper) CreatePostWithClient(client *model.Client4, channel *model.Channel) *model.Post {
   675  	id := model.NewId()
   676  
   677  	post := &model.Post{
   678  		ChannelId: channel.Id,
   679  		Message:   "message_" + id,
   680  	}
   681  
   682  	utils.DisableDebugLogForTest()
   683  	rpost, resp := client.CreatePost(post)
   684  	if resp.Error != nil {
   685  		panic(resp.Error)
   686  	}
   687  	utils.EnableDebugLogForTest()
   688  	return rpost
   689  }
   690  
   691  func (th *TestHelper) CreatePinnedPostWithClient(client *model.Client4, channel *model.Channel) *model.Post {
   692  	id := model.NewId()
   693  
   694  	post := &model.Post{
   695  		ChannelId: channel.Id,
   696  		Message:   "message_" + id,
   697  		IsPinned:  true,
   698  	}
   699  
   700  	utils.DisableDebugLogForTest()
   701  	rpost, resp := client.CreatePost(post)
   702  	if resp.Error != nil {
   703  		panic(resp.Error)
   704  	}
   705  	utils.EnableDebugLogForTest()
   706  	return rpost
   707  }
   708  
   709  func (th *TestHelper) CreateMessagePostWithClient(client *model.Client4, channel *model.Channel, message string) *model.Post {
   710  	post := &model.Post{
   711  		ChannelId: channel.Id,
   712  		Message:   message,
   713  	}
   714  
   715  	utils.DisableDebugLogForTest()
   716  	rpost, resp := client.CreatePost(post)
   717  	if resp.Error != nil {
   718  		panic(resp.Error)
   719  	}
   720  	utils.EnableDebugLogForTest()
   721  	return rpost
   722  }
   723  
   724  func (th *TestHelper) CreateMessagePostNoClient(channel *model.Channel, message string, createAtTime int64) *model.Post {
   725  	post, err := th.App.Srv().Store.Post().Save(&model.Post{
   726  		UserId:    th.BasicUser.Id,
   727  		ChannelId: channel.Id,
   728  		Message:   message,
   729  		CreateAt:  createAtTime,
   730  	})
   731  
   732  	if err != nil {
   733  		panic(err)
   734  	}
   735  
   736  	return post
   737  }
   738  
   739  func (th *TestHelper) CreateDmChannel(user *model.User) *model.Channel {
   740  	utils.DisableDebugLogForTest()
   741  	var err *model.AppError
   742  	var channel *model.Channel
   743  	if channel, err = th.App.GetOrCreateDirectChannel(th.Context, th.BasicUser.Id, user.Id); err != nil {
   744  		panic(err)
   745  	}
   746  	utils.EnableDebugLogForTest()
   747  	return channel
   748  }
   749  
   750  func (th *TestHelper) LoginBasic() {
   751  	th.LoginBasicWithClient(th.Client)
   752  }
   753  
   754  func (th *TestHelper) LoginBasic2() {
   755  	th.LoginBasic2WithClient(th.Client)
   756  }
   757  
   758  func (th *TestHelper) LoginTeamAdmin() {
   759  	th.LoginTeamAdminWithClient(th.Client)
   760  }
   761  
   762  func (th *TestHelper) LoginSystemAdmin() {
   763  	th.LoginSystemAdminWithClient(th.SystemAdminClient)
   764  }
   765  
   766  func (th *TestHelper) LoginSystemManager() {
   767  	th.LoginSystemManagerWithClient(th.SystemManagerClient)
   768  }
   769  
   770  func (th *TestHelper) LoginBasicWithClient(client *model.Client4) {
   771  	utils.DisableDebugLogForTest()
   772  	_, resp := client.Login(th.BasicUser.Email, th.BasicUser.Password)
   773  	if resp.Error != nil {
   774  		panic(resp.Error)
   775  	}
   776  	utils.EnableDebugLogForTest()
   777  }
   778  
   779  func (th *TestHelper) LoginBasic2WithClient(client *model.Client4) {
   780  	utils.DisableDebugLogForTest()
   781  	_, resp := client.Login(th.BasicUser2.Email, th.BasicUser2.Password)
   782  	if resp.Error != nil {
   783  		panic(resp.Error)
   784  	}
   785  	utils.EnableDebugLogForTest()
   786  }
   787  
   788  func (th *TestHelper) LoginTeamAdminWithClient(client *model.Client4) {
   789  	utils.DisableDebugLogForTest()
   790  	_, resp := client.Login(th.TeamAdminUser.Email, th.TeamAdminUser.Password)
   791  	if resp.Error != nil {
   792  		panic(resp.Error)
   793  	}
   794  	utils.EnableDebugLogForTest()
   795  }
   796  
   797  func (th *TestHelper) LoginSystemManagerWithClient(client *model.Client4) {
   798  	utils.DisableDebugLogForTest()
   799  	_, resp := client.Login(th.SystemManagerUser.Email, th.SystemManagerUser.Password)
   800  	if resp.Error != nil {
   801  		panic(resp.Error)
   802  	}
   803  	utils.EnableDebugLogForTest()
   804  }
   805  
   806  func (th *TestHelper) LoginSystemAdminWithClient(client *model.Client4) {
   807  	utils.DisableDebugLogForTest()
   808  	_, resp := client.Login(th.SystemAdminUser.Email, th.SystemAdminUser.Password)
   809  	if resp.Error != nil {
   810  		panic(resp.Error)
   811  	}
   812  	utils.EnableDebugLogForTest()
   813  }
   814  
   815  func (th *TestHelper) UpdateActiveUser(user *model.User, active bool) {
   816  	utils.DisableDebugLogForTest()
   817  
   818  	_, err := th.App.UpdateActive(th.Context, user, active)
   819  	if err != nil {
   820  		panic(err)
   821  	}
   822  
   823  	utils.EnableDebugLogForTest()
   824  }
   825  
   826  func (th *TestHelper) LinkUserToTeam(user *model.User, team *model.Team) {
   827  	utils.DisableDebugLogForTest()
   828  
   829  	_, err := th.App.JoinUserToTeam(th.Context, team, user, "")
   830  	if err != nil {
   831  		panic(err)
   832  	}
   833  
   834  	utils.EnableDebugLogForTest()
   835  }
   836  
   837  func (th *TestHelper) AddUserToChannel(user *model.User, channel *model.Channel) *model.ChannelMember {
   838  	utils.DisableDebugLogForTest()
   839  
   840  	member, err := th.App.AddUserToChannel(user, channel, false)
   841  	if err != nil {
   842  		panic(err)
   843  	}
   844  
   845  	utils.EnableDebugLogForTest()
   846  
   847  	return member
   848  }
   849  
   850  func (th *TestHelper) GenerateTestEmail() string {
   851  	if *th.App.Config().EmailSettings.SMTPServer != "localhost" && os.Getenv("CI_INBUCKET_PORT") == "" {
   852  		return strings.ToLower("success+" + model.NewId() + "@simulator.amazonses.com")
   853  	}
   854  	return strings.ToLower(model.NewId() + "@localhost")
   855  }
   856  
   857  func (th *TestHelper) CreateGroup() *model.Group {
   858  	id := model.NewId()
   859  	group := &model.Group{
   860  		Name:        model.NewString("n-" + id),
   861  		DisplayName: "dn_" + id,
   862  		Source:      model.GroupSourceLdap,
   863  		RemoteId:    "ri_" + id,
   864  	}
   865  
   866  	utils.DisableDebugLogForTest()
   867  	group, err := th.App.CreateGroup(group)
   868  	if err != nil {
   869  		panic(err)
   870  	}
   871  	utils.EnableDebugLogForTest()
   872  	return group
   873  }
   874  
   875  // TestForSystemAdminAndLocal runs a test function for both
   876  // SystemAdmin and Local clients. Several endpoints work in the same
   877  // way when used by a fully privileged user and through the local
   878  // mode, so this helper facilitates checking both
   879  func (th *TestHelper) TestForSystemAdminAndLocal(t *testing.T, f func(*testing.T, *model.Client4), name ...string) {
   880  	var testName string
   881  	if len(name) > 0 {
   882  		testName = name[0] + "/"
   883  	}
   884  
   885  	t.Run(testName+"SystemAdminClient", func(t *testing.T) {
   886  		f(t, th.SystemAdminClient)
   887  	})
   888  
   889  	t.Run(testName+"LocalClient", func(t *testing.T) {
   890  		f(t, th.LocalClient)
   891  	})
   892  }
   893  
   894  // TestForAllClients runs a test function for all the clients
   895  // registered in the TestHelper
   896  func (th *TestHelper) TestForAllClients(t *testing.T, f func(*testing.T, *model.Client4), name ...string) {
   897  	var testName string
   898  	if len(name) > 0 {
   899  		testName = name[0] + "/"
   900  	}
   901  
   902  	t.Run(testName+"Client", func(t *testing.T) {
   903  		f(t, th.Client)
   904  	})
   905  
   906  	t.Run(testName+"SystemAdminClient", func(t *testing.T) {
   907  		f(t, th.SystemAdminClient)
   908  	})
   909  
   910  	t.Run(testName+"LocalClient", func(t *testing.T) {
   911  		f(t, th.LocalClient)
   912  	})
   913  }
   914  
   915  func GenerateTestUsername() string {
   916  	return "fakeuser" + model.NewRandomString(10)
   917  }
   918  
   919  func GenerateTestTeamName() string {
   920  	return "faketeam" + model.NewRandomString(6)
   921  }
   922  
   923  func GenerateTestChannelName() string {
   924  	return "fakechannel" + model.NewRandomString(10)
   925  }
   926  
   927  func GenerateTestAppName() string {
   928  	return "fakeoauthapp" + model.NewRandomString(10)
   929  }
   930  
   931  func GenerateTestId() string {
   932  	return model.NewId()
   933  }
   934  
   935  func CheckUserSanitization(t *testing.T, user *model.User) {
   936  	t.Helper()
   937  
   938  	require.Equal(t, "", user.Password, "password wasn't blank")
   939  	require.Empty(t, user.AuthData, "auth data wasn't blank")
   940  	require.Equal(t, "", user.MfaSecret, "mfa secret wasn't blank")
   941  }
   942  
   943  func CheckEtag(t *testing.T, data interface{}, resp *model.Response) {
   944  	t.Helper()
   945  
   946  	require.Empty(t, data)
   947  	require.Equal(t, resp.StatusCode, http.StatusNotModified, "wrong status code for etag")
   948  }
   949  
   950  func CheckNoError(t *testing.T, resp *model.Response) {
   951  	t.Helper()
   952  
   953  	require.Nil(t, resp.Error, "expected no error")
   954  }
   955  
   956  func checkHTTPStatus(t *testing.T, resp *model.Response, expectedStatus int, expectError bool) {
   957  	t.Helper()
   958  
   959  	require.NotNilf(t, resp, "Unexpected nil response, expected http:%v, expectError:%v", expectedStatus, expectError)
   960  	if expectError {
   961  		require.NotNil(t, resp.Error, "Expected a non-nil error and http status:%v, got nil, %v", expectedStatus, resp.StatusCode)
   962  	} else {
   963  		require.Nil(t, resp.Error, "Expected no error and http status:%v, got %q, http:%v", expectedStatus, resp.Error, resp.StatusCode)
   964  	}
   965  	require.Equalf(t, expectedStatus, resp.StatusCode, "Expected http status:%v, got %v (err: %q)", expectedStatus, resp.StatusCode, resp.Error)
   966  }
   967  
   968  func CheckOKStatus(t *testing.T, resp *model.Response) {
   969  	t.Helper()
   970  	checkHTTPStatus(t, resp, http.StatusOK, false)
   971  }
   972  
   973  func CheckCreatedStatus(t *testing.T, resp *model.Response) {
   974  	t.Helper()
   975  	checkHTTPStatus(t, resp, http.StatusCreated, false)
   976  }
   977  
   978  func CheckForbiddenStatus(t *testing.T, resp *model.Response) {
   979  	t.Helper()
   980  	checkHTTPStatus(t, resp, http.StatusForbidden, true)
   981  }
   982  
   983  func CheckUnauthorizedStatus(t *testing.T, resp *model.Response) {
   984  	t.Helper()
   985  	checkHTTPStatus(t, resp, http.StatusUnauthorized, true)
   986  }
   987  
   988  func CheckNotFoundStatus(t *testing.T, resp *model.Response) {
   989  	t.Helper()
   990  	checkHTTPStatus(t, resp, http.StatusNotFound, true)
   991  }
   992  
   993  func CheckBadRequestStatus(t *testing.T, resp *model.Response) {
   994  	t.Helper()
   995  	checkHTTPStatus(t, resp, http.StatusBadRequest, true)
   996  }
   997  
   998  func CheckNotImplementedStatus(t *testing.T, resp *model.Response) {
   999  	t.Helper()
  1000  	checkHTTPStatus(t, resp, http.StatusNotImplemented, true)
  1001  }
  1002  
  1003  func CheckRequestEntityTooLargeStatus(t *testing.T, resp *model.Response) {
  1004  	t.Helper()
  1005  	checkHTTPStatus(t, resp, http.StatusRequestEntityTooLarge, true)
  1006  }
  1007  
  1008  func CheckInternalErrorStatus(t *testing.T, resp *model.Response) {
  1009  	t.Helper()
  1010  	checkHTTPStatus(t, resp, http.StatusInternalServerError, true)
  1011  }
  1012  
  1013  func CheckServiceUnavailableStatus(t *testing.T, resp *model.Response) {
  1014  	t.Helper()
  1015  	checkHTTPStatus(t, resp, http.StatusServiceUnavailable, true)
  1016  }
  1017  
  1018  func CheckErrorMessage(t *testing.T, resp *model.Response, errorId string) {
  1019  	t.Helper()
  1020  
  1021  	require.NotNilf(t, resp.Error, "should have errored with message: %s", errorId)
  1022  	require.Equalf(t, errorId, resp.Error.Id, "incorrect error message, actual: %s, expected: %s", resp.Error.Id, errorId)
  1023  }
  1024  
  1025  func CheckStartsWith(t *testing.T, value, prefix, message string) {
  1026  	require.True(t, strings.HasPrefix(value, prefix), message, value)
  1027  }
  1028  
  1029  // Similar to s3.New() but allows initialization of signature v2 or signature v4 client.
  1030  // If signV2 input is false, function always returns signature v4.
  1031  //
  1032  // Additionally this function also takes a user defined region, if set
  1033  // disables automatic region lookup.
  1034  func s3New(endpoint, accessKey, secretKey string, secure bool, signV2 bool, region string) (*s3.Client, error) {
  1035  	var creds *credentials.Credentials
  1036  	if signV2 {
  1037  		creds = credentials.NewStatic(accessKey, secretKey, "", credentials.SignatureV2)
  1038  	} else {
  1039  		creds = credentials.NewStatic(accessKey, secretKey, "", credentials.SignatureV4)
  1040  	}
  1041  
  1042  	opts := s3.Options{
  1043  		Creds:  creds,
  1044  		Secure: secure,
  1045  		Region: region,
  1046  	}
  1047  	return s3.New(endpoint, &opts)
  1048  }
  1049  
  1050  func (th *TestHelper) cleanupTestFile(info *model.FileInfo) error {
  1051  	cfg := th.App.Config()
  1052  	if *cfg.FileSettings.DriverName == model.IMAGE_DRIVER_S3 {
  1053  		endpoint := *cfg.FileSettings.AmazonS3Endpoint
  1054  		accessKey := *cfg.FileSettings.AmazonS3AccessKeyId
  1055  		secretKey := *cfg.FileSettings.AmazonS3SecretAccessKey
  1056  		secure := *cfg.FileSettings.AmazonS3SSL
  1057  		signV2 := *cfg.FileSettings.AmazonS3SignV2
  1058  		region := *cfg.FileSettings.AmazonS3Region
  1059  		s3Clnt, err := s3New(endpoint, accessKey, secretKey, secure, signV2, region)
  1060  		if err != nil {
  1061  			return err
  1062  		}
  1063  		bucket := *cfg.FileSettings.AmazonS3Bucket
  1064  		if err := s3Clnt.RemoveObject(context.Background(), bucket, info.Path, s3.RemoveObjectOptions{}); err != nil {
  1065  			return err
  1066  		}
  1067  
  1068  		if info.ThumbnailPath != "" {
  1069  			if err := s3Clnt.RemoveObject(context.Background(), bucket, info.ThumbnailPath, s3.RemoveObjectOptions{}); err != nil {
  1070  				return err
  1071  			}
  1072  		}
  1073  
  1074  		if info.PreviewPath != "" {
  1075  			if err := s3Clnt.RemoveObject(context.Background(), bucket, info.PreviewPath, s3.RemoveObjectOptions{}); err != nil {
  1076  				return err
  1077  			}
  1078  		}
  1079  	} else if *cfg.FileSettings.DriverName == model.IMAGE_DRIVER_LOCAL {
  1080  		if err := os.Remove(*cfg.FileSettings.Directory + info.Path); err != nil {
  1081  			return err
  1082  		}
  1083  
  1084  		if info.ThumbnailPath != "" {
  1085  			if err := os.Remove(*cfg.FileSettings.Directory + info.ThumbnailPath); err != nil {
  1086  				return err
  1087  			}
  1088  		}
  1089  
  1090  		if info.PreviewPath != "" {
  1091  			if err := os.Remove(*cfg.FileSettings.Directory + info.PreviewPath); err != nil {
  1092  				return err
  1093  			}
  1094  		}
  1095  	}
  1096  
  1097  	return nil
  1098  }
  1099  
  1100  func (th *TestHelper) MakeUserChannelAdmin(user *model.User, channel *model.Channel) {
  1101  	utils.DisableDebugLogForTest()
  1102  
  1103  	if cm, err := th.App.Srv().Store.Channel().GetMember(context.Background(), channel.Id, user.Id); err == nil {
  1104  		cm.SchemeAdmin = true
  1105  		if _, err = th.App.Srv().Store.Channel().UpdateMember(cm); err != nil {
  1106  			utils.EnableDebugLogForTest()
  1107  			panic(err)
  1108  		}
  1109  	} else {
  1110  		utils.EnableDebugLogForTest()
  1111  		panic(err)
  1112  	}
  1113  
  1114  	utils.EnableDebugLogForTest()
  1115  }
  1116  
  1117  func (th *TestHelper) UpdateUserToTeamAdmin(user *model.User, team *model.Team) {
  1118  	utils.DisableDebugLogForTest()
  1119  
  1120  	if tm, err := th.App.Srv().Store.Team().GetMember(context.Background(), team.Id, user.Id); err == nil {
  1121  		tm.SchemeAdmin = true
  1122  		if _, err = th.App.Srv().Store.Team().UpdateMember(tm); err != nil {
  1123  			utils.EnableDebugLogForTest()
  1124  			panic(err)
  1125  		}
  1126  	} else {
  1127  		utils.EnableDebugLogForTest()
  1128  		panic(err)
  1129  	}
  1130  
  1131  	utils.EnableDebugLogForTest()
  1132  }
  1133  
  1134  func (th *TestHelper) UpdateUserToNonTeamAdmin(user *model.User, team *model.Team) {
  1135  	utils.DisableDebugLogForTest()
  1136  
  1137  	if tm, err := th.App.Srv().Store.Team().GetMember(context.Background(), team.Id, user.Id); err == nil {
  1138  		tm.SchemeAdmin = false
  1139  		if _, err = th.App.Srv().Store.Team().UpdateMember(tm); err != nil {
  1140  			utils.EnableDebugLogForTest()
  1141  			panic(err)
  1142  		}
  1143  	} else {
  1144  		utils.EnableDebugLogForTest()
  1145  		panic(err)
  1146  	}
  1147  
  1148  	utils.EnableDebugLogForTest()
  1149  }
  1150  
  1151  func (th *TestHelper) SaveDefaultRolePermissions() map[string][]string {
  1152  	utils.DisableDebugLogForTest()
  1153  
  1154  	results := make(map[string][]string)
  1155  
  1156  	for _, roleName := range []string{
  1157  		"system_user",
  1158  		"system_admin",
  1159  		"team_user",
  1160  		"team_admin",
  1161  		"channel_user",
  1162  		"channel_admin",
  1163  	} {
  1164  		role, err1 := th.App.GetRoleByName(context.Background(), roleName)
  1165  		if err1 != nil {
  1166  			utils.EnableDebugLogForTest()
  1167  			panic(err1)
  1168  		}
  1169  
  1170  		results[roleName] = role.Permissions
  1171  	}
  1172  
  1173  	utils.EnableDebugLogForTest()
  1174  	return results
  1175  }
  1176  
  1177  func (th *TestHelper) RestoreDefaultRolePermissions(data map[string][]string) {
  1178  	utils.DisableDebugLogForTest()
  1179  
  1180  	for roleName, permissions := range data {
  1181  		role, err1 := th.App.GetRoleByName(context.Background(), roleName)
  1182  		if err1 != nil {
  1183  			utils.EnableDebugLogForTest()
  1184  			panic(err1)
  1185  		}
  1186  
  1187  		if strings.Join(role.Permissions, " ") == strings.Join(permissions, " ") {
  1188  			continue
  1189  		}
  1190  
  1191  		role.Permissions = permissions
  1192  
  1193  		_, err2 := th.App.UpdateRole(role)
  1194  		if err2 != nil {
  1195  			utils.EnableDebugLogForTest()
  1196  			panic(err2)
  1197  		}
  1198  	}
  1199  
  1200  	utils.EnableDebugLogForTest()
  1201  }
  1202  
  1203  func (th *TestHelper) RemovePermissionFromRole(permission string, roleName string) {
  1204  	utils.DisableDebugLogForTest()
  1205  
  1206  	role, err1 := th.App.GetRoleByName(context.Background(), roleName)
  1207  	if err1 != nil {
  1208  		utils.EnableDebugLogForTest()
  1209  		panic(err1)
  1210  	}
  1211  
  1212  	var newPermissions []string
  1213  	for _, p := range role.Permissions {
  1214  		if p != permission {
  1215  			newPermissions = append(newPermissions, p)
  1216  		}
  1217  	}
  1218  
  1219  	if strings.Join(role.Permissions, " ") == strings.Join(newPermissions, " ") {
  1220  		utils.EnableDebugLogForTest()
  1221  		return
  1222  	}
  1223  
  1224  	role.Permissions = newPermissions
  1225  
  1226  	_, err2 := th.App.UpdateRole(role)
  1227  	if err2 != nil {
  1228  		utils.EnableDebugLogForTest()
  1229  		panic(err2)
  1230  	}
  1231  
  1232  	utils.EnableDebugLogForTest()
  1233  }
  1234  
  1235  func (th *TestHelper) AddPermissionToRole(permission string, roleName string) {
  1236  	utils.DisableDebugLogForTest()
  1237  
  1238  	role, err1 := th.App.GetRoleByName(context.Background(), roleName)
  1239  	if err1 != nil {
  1240  		utils.EnableDebugLogForTest()
  1241  		panic(err1)
  1242  	}
  1243  
  1244  	for _, existingPermission := range role.Permissions {
  1245  		if existingPermission == permission {
  1246  			utils.EnableDebugLogForTest()
  1247  			return
  1248  		}
  1249  	}
  1250  
  1251  	role.Permissions = append(role.Permissions, permission)
  1252  
  1253  	_, err2 := th.App.UpdateRole(role)
  1254  	if err2 != nil {
  1255  		utils.EnableDebugLogForTest()
  1256  		panic(err2)
  1257  	}
  1258  
  1259  	utils.EnableDebugLogForTest()
  1260  }
  1261  
  1262  func (th *TestHelper) SetupTeamScheme() *model.Scheme {
  1263  	return th.SetupScheme(model.SCHEME_SCOPE_TEAM)
  1264  }
  1265  
  1266  func (th *TestHelper) SetupChannelScheme() *model.Scheme {
  1267  	return th.SetupScheme(model.SCHEME_SCOPE_CHANNEL)
  1268  }
  1269  
  1270  func (th *TestHelper) SetupScheme(scope string) *model.Scheme {
  1271  	scheme, err := th.App.CreateScheme(&model.Scheme{
  1272  		Name:        model.NewId(),
  1273  		DisplayName: model.NewId(),
  1274  		Scope:       scope,
  1275  	})
  1276  	if err != nil {
  1277  		panic(err)
  1278  	}
  1279  	return scheme
  1280  }