github.com/masterhung0112/hk_server/v5@v5.0.0-20220302090640-ec71aef15e1c/api4/apitestlib.go (about)

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