github.com/kongr45gpen/mattermost-server@v5.11.1+incompatible/api4/apitestlib.go (about)

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