github.com/dschalla/mattermost-server@v4.8.1-rc1+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  	"bytes"
     8  	"fmt"
     9  	"io"
    10  	"io/ioutil"
    11  	"net"
    12  	"net/http"
    13  	"os"
    14  	"reflect"
    15  	"strconv"
    16  	"strings"
    17  	"sync"
    18  	"testing"
    19  	"time"
    20  
    21  	l4g "github.com/alecthomas/log4go"
    22  	"github.com/mattermost/mattermost-server/app"
    23  	"github.com/mattermost/mattermost-server/model"
    24  	"github.com/mattermost/mattermost-server/store"
    25  	"github.com/mattermost/mattermost-server/store/sqlstore"
    26  	"github.com/mattermost/mattermost-server/store/storetest"
    27  	"github.com/mattermost/mattermost-server/utils"
    28  	"github.com/mattermost/mattermost-server/wsapi"
    29  
    30  	s3 "github.com/minio/minio-go"
    31  	"github.com/minio/minio-go/pkg/credentials"
    32  )
    33  
    34  type TestHelper struct {
    35  	App            *app.App
    36  	tempConfigPath string
    37  
    38  	Client              *model.Client4
    39  	BasicUser           *model.User
    40  	BasicUser2          *model.User
    41  	TeamAdminUser       *model.User
    42  	BasicTeam           *model.Team
    43  	BasicChannel        *model.Channel
    44  	BasicPrivateChannel *model.Channel
    45  	BasicChannel2       *model.Channel
    46  	BasicPost           *model.Post
    47  
    48  	SystemAdminClient *model.Client4
    49  	SystemAdminUser   *model.User
    50  }
    51  
    52  type persistentTestStore struct {
    53  	store.Store
    54  }
    55  
    56  func (*persistentTestStore) Close() {}
    57  
    58  var testStoreContainer *storetest.RunningContainer
    59  var testStore *persistentTestStore
    60  
    61  // UseTestStore sets the container and corresponding settings to use for tests. Once the tests are
    62  // complete (e.g. at the end of your TestMain implementation), you should call StopTestStore.
    63  func UseTestStore(container *storetest.RunningContainer, settings *model.SqlSettings) {
    64  	testStoreContainer = container
    65  	testStore = &persistentTestStore{store.NewLayeredStore(sqlstore.NewSqlSupplier(*settings, nil), nil, nil)}
    66  }
    67  
    68  func StopTestStore() {
    69  	if testStoreContainer != nil {
    70  		testStoreContainer.Stop()
    71  		testStoreContainer = nil
    72  	}
    73  }
    74  
    75  func setupTestHelper(enterprise bool) *TestHelper {
    76  	permConfig, err := os.Open(utils.FindConfigFile("config.json"))
    77  	if err != nil {
    78  		panic(err)
    79  	}
    80  	defer permConfig.Close()
    81  	tempConfig, err := ioutil.TempFile("", "")
    82  	if err != nil {
    83  		panic(err)
    84  	}
    85  	_, err = io.Copy(tempConfig, permConfig)
    86  	tempConfig.Close()
    87  	if err != nil {
    88  		panic(err)
    89  	}
    90  
    91  	options := []app.Option{app.ConfigFile(tempConfig.Name()), app.DisableConfigWatch}
    92  	if testStore != nil {
    93  		options = append(options, app.StoreOverride(testStore))
    94  	}
    95  
    96  	a, err := app.New(options...)
    97  	if err != nil {
    98  		panic(err)
    99  	}
   100  
   101  	th := &TestHelper{
   102  		App:            a,
   103  		tempConfigPath: tempConfig.Name(),
   104  	}
   105  
   106  	th.App.UpdateConfig(func(cfg *model.Config) {
   107  		*cfg.TeamSettings.MaxUsersPerTeam = 50
   108  		*cfg.RateLimitSettings.Enable = false
   109  		cfg.EmailSettings.SendEmailNotifications = true
   110  	})
   111  	prevListenAddress := *th.App.Config().ServiceSettings.ListenAddress
   112  	if testStore != nil {
   113  		th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = ":0" })
   114  	}
   115  	serverErr := th.App.StartServer()
   116  	if serverErr != nil {
   117  		panic(serverErr)
   118  	}
   119  
   120  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ListenAddress = prevListenAddress })
   121  	Init(th.App, th.App.Srv.Router, true)
   122  	wsapi.Init(th.App, th.App.Srv.WebSocketRouter)
   123  	th.App.Srv.Store.MarkSystemRanUnitTests()
   124  
   125  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableOpenServer = true })
   126  
   127  	if enterprise {
   128  		th.App.SetLicense(model.NewTestLicense())
   129  	} else {
   130  		th.App.SetLicense(nil)
   131  	}
   132  
   133  	th.Client = th.CreateClient()
   134  	th.SystemAdminClient = th.CreateClient()
   135  	return th
   136  }
   137  
   138  func SetupEnterprise() *TestHelper {
   139  	return setupTestHelper(true)
   140  }
   141  
   142  func Setup() *TestHelper {
   143  	return setupTestHelper(false)
   144  }
   145  
   146  func (me *TestHelper) TearDown() {
   147  	utils.DisableDebugLogForTest()
   148  
   149  	var wg sync.WaitGroup
   150  	wg.Add(3)
   151  
   152  	go func() {
   153  		defer wg.Done()
   154  		options := map[string]bool{}
   155  		options[store.USER_SEARCH_OPTION_NAMES_ONLY_NO_FULL_NAME] = true
   156  		if result := <-me.App.Srv.Store.User().Search("", "fakeuser", options); result.Err != nil {
   157  			l4g.Error("Error tearing down test users")
   158  		} else {
   159  			users := result.Data.([]*model.User)
   160  
   161  			for _, u := range users {
   162  				if err := me.App.PermanentDeleteUser(u); err != nil {
   163  					l4g.Error(err.Error())
   164  				}
   165  			}
   166  		}
   167  	}()
   168  
   169  	go func() {
   170  		defer wg.Done()
   171  		if result := <-me.App.Srv.Store.Team().SearchByName("faketeam"); result.Err != nil {
   172  			l4g.Error("Error tearing down test teams")
   173  		} else {
   174  			teams := result.Data.([]*model.Team)
   175  
   176  			for _, t := range teams {
   177  				if err := me.App.PermanentDeleteTeam(t); err != nil {
   178  					l4g.Error(err.Error())
   179  				}
   180  			}
   181  		}
   182  	}()
   183  
   184  	go func() {
   185  		defer wg.Done()
   186  		if result := <-me.App.Srv.Store.OAuth().GetApps(0, 1000); result.Err != nil {
   187  			l4g.Error("Error tearing down test oauth apps")
   188  		} else {
   189  			apps := result.Data.([]*model.OAuthApp)
   190  
   191  			for _, a := range apps {
   192  				if strings.HasPrefix(a.Name, "fakeoauthapp") {
   193  					<-me.App.Srv.Store.OAuth().DeleteApp(a.Id)
   194  				}
   195  			}
   196  		}
   197  	}()
   198  
   199  	wg.Wait()
   200  
   201  	me.App.Shutdown()
   202  	os.Remove(me.tempConfigPath)
   203  
   204  	utils.EnableDebugLogForTest()
   205  
   206  	if err := recover(); err != nil {
   207  		StopTestStore()
   208  		panic(err)
   209  	}
   210  }
   211  
   212  func (me *TestHelper) InitBasic() *TestHelper {
   213  	me.waitForConnectivity()
   214  
   215  	me.TeamAdminUser = me.CreateUser()
   216  	me.App.UpdateUserRoles(me.TeamAdminUser.Id, model.SYSTEM_USER_ROLE_ID, false)
   217  	me.LoginTeamAdmin()
   218  	me.BasicTeam = me.CreateTeam()
   219  	me.BasicChannel = me.CreatePublicChannel()
   220  	me.BasicPrivateChannel = me.CreatePrivateChannel()
   221  	me.BasicChannel2 = me.CreatePublicChannel()
   222  	me.BasicPost = me.CreatePost()
   223  	me.BasicUser = me.CreateUser()
   224  	me.LinkUserToTeam(me.BasicUser, me.BasicTeam)
   225  	me.BasicUser2 = me.CreateUser()
   226  	me.LinkUserToTeam(me.BasicUser2, me.BasicTeam)
   227  	me.App.AddUserToChannel(me.BasicUser, me.BasicChannel)
   228  	me.App.AddUserToChannel(me.BasicUser2, me.BasicChannel)
   229  	me.App.AddUserToChannel(me.BasicUser, me.BasicChannel2)
   230  	me.App.AddUserToChannel(me.BasicUser2, me.BasicChannel2)
   231  	me.App.AddUserToChannel(me.BasicUser, me.BasicPrivateChannel)
   232  	me.App.AddUserToChannel(me.BasicUser2, me.BasicPrivateChannel)
   233  	me.App.UpdateUserRoles(me.BasicUser.Id, model.SYSTEM_USER_ROLE_ID, false)
   234  	me.LoginBasic()
   235  
   236  	return me
   237  }
   238  
   239  func (me *TestHelper) InitSystemAdmin() *TestHelper {
   240  	me.waitForConnectivity()
   241  
   242  	me.SystemAdminUser = me.CreateUser()
   243  	me.App.UpdateUserRoles(me.SystemAdminUser.Id, model.SYSTEM_USER_ROLE_ID+" "+model.SYSTEM_ADMIN_ROLE_ID, false)
   244  	me.LoginSystemAdmin()
   245  
   246  	return me
   247  }
   248  
   249  func (me *TestHelper) waitForConnectivity() {
   250  	for i := 0; i < 1000; i++ {
   251  		conn, err := net.Dial("tcp", fmt.Sprintf("localhost:%v", me.App.Srv.ListenAddr.Port))
   252  		if err == nil {
   253  			conn.Close()
   254  			return
   255  		}
   256  		time.Sleep(time.Millisecond * 20)
   257  	}
   258  	panic("unable to connect")
   259  }
   260  
   261  func (me *TestHelper) CreateClient() *model.Client4 {
   262  	return model.NewAPIv4Client(fmt.Sprintf("http://localhost:%v", me.App.Srv.ListenAddr.Port))
   263  }
   264  
   265  func (me *TestHelper) CreateWebSocketClient() (*model.WebSocketClient, *model.AppError) {
   266  	return model.NewWebSocketClient4(fmt.Sprintf("ws://localhost:%v", me.App.Srv.ListenAddr.Port), me.Client.AuthToken)
   267  }
   268  
   269  func (me *TestHelper) CreateUser() *model.User {
   270  	return me.CreateUserWithClient(me.Client)
   271  }
   272  
   273  func (me *TestHelper) CreateTeam() *model.Team {
   274  	return me.CreateTeamWithClient(me.Client)
   275  }
   276  
   277  func (me *TestHelper) CreateTeamWithClient(client *model.Client4) *model.Team {
   278  	id := model.NewId()
   279  	team := &model.Team{
   280  		DisplayName: "dn_" + id,
   281  		Name:        GenerateTestTeamName(),
   282  		Email:       me.GenerateTestEmail(),
   283  		Type:        model.TEAM_OPEN,
   284  	}
   285  
   286  	utils.DisableDebugLogForTest()
   287  	rteam, _ := client.CreateTeam(team)
   288  	utils.EnableDebugLogForTest()
   289  	return rteam
   290  }
   291  
   292  func (me *TestHelper) CreateUserWithClient(client *model.Client4) *model.User {
   293  	id := model.NewId()
   294  
   295  	user := &model.User{
   296  		Email:     me.GenerateTestEmail(),
   297  		Username:  GenerateTestUsername(),
   298  		Nickname:  "nn_" + id,
   299  		FirstName: "f_" + id,
   300  		LastName:  "l_" + id,
   301  		Password:  "Password1",
   302  	}
   303  
   304  	utils.DisableDebugLogForTest()
   305  	ruser, _ := client.CreateUser(user)
   306  	ruser.Password = "Password1"
   307  	store.Must(me.App.Srv.Store.User().VerifyEmail(ruser.Id))
   308  	utils.EnableDebugLogForTest()
   309  	return ruser
   310  }
   311  
   312  func (me *TestHelper) CreatePublicChannel() *model.Channel {
   313  	return me.CreateChannelWithClient(me.Client, model.CHANNEL_OPEN)
   314  }
   315  
   316  func (me *TestHelper) CreatePrivateChannel() *model.Channel {
   317  	return me.CreateChannelWithClient(me.Client, model.CHANNEL_PRIVATE)
   318  }
   319  
   320  func (me *TestHelper) CreateChannelWithClient(client *model.Client4, channelType string) *model.Channel {
   321  	return me.CreateChannelWithClientAndTeam(client, channelType, me.BasicTeam.Id)
   322  }
   323  
   324  func (me *TestHelper) CreateChannelWithClientAndTeam(client *model.Client4, channelType string, teamId string) *model.Channel {
   325  	id := model.NewId()
   326  
   327  	channel := &model.Channel{
   328  		DisplayName: "dn_" + id,
   329  		Name:        GenerateTestChannelName(),
   330  		Type:        channelType,
   331  		TeamId:      teamId,
   332  	}
   333  
   334  	utils.DisableDebugLogForTest()
   335  	rchannel, _ := client.CreateChannel(channel)
   336  	utils.EnableDebugLogForTest()
   337  	return rchannel
   338  }
   339  
   340  func (me *TestHelper) CreatePost() *model.Post {
   341  	return me.CreatePostWithClient(me.Client, me.BasicChannel)
   342  }
   343  
   344  func (me *TestHelper) CreatePinnedPost() *model.Post {
   345  	return me.CreatePinnedPostWithClient(me.Client, me.BasicChannel)
   346  }
   347  
   348  func (me *TestHelper) CreateMessagePost(message string) *model.Post {
   349  	return me.CreateMessagePostWithClient(me.Client, me.BasicChannel, message)
   350  }
   351  
   352  func (me *TestHelper) CreatePostWithClient(client *model.Client4, channel *model.Channel) *model.Post {
   353  	id := model.NewId()
   354  
   355  	post := &model.Post{
   356  		ChannelId: channel.Id,
   357  		Message:   "message_" + id,
   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) CreatePinnedPostWithClient(client *model.Client4, channel *model.Channel) *model.Post {
   370  	id := model.NewId()
   371  
   372  	post := &model.Post{
   373  		ChannelId: channel.Id,
   374  		Message:   "message_" + id,
   375  		IsPinned:  true,
   376  	}
   377  
   378  	utils.DisableDebugLogForTest()
   379  	rpost, resp := client.CreatePost(post)
   380  	if resp.Error != nil {
   381  		panic(resp.Error)
   382  	}
   383  	utils.EnableDebugLogForTest()
   384  	return rpost
   385  }
   386  
   387  func (me *TestHelper) CreateMessagePostWithClient(client *model.Client4, channel *model.Channel, message string) *model.Post {
   388  	post := &model.Post{
   389  		ChannelId: channel.Id,
   390  		Message:   message,
   391  	}
   392  
   393  	utils.DisableDebugLogForTest()
   394  	rpost, resp := client.CreatePost(post)
   395  	if resp.Error != nil {
   396  		panic(resp.Error)
   397  	}
   398  	utils.EnableDebugLogForTest()
   399  	return rpost
   400  }
   401  
   402  func (me *TestHelper) LoginBasic() {
   403  	me.LoginBasicWithClient(me.Client)
   404  }
   405  
   406  func (me *TestHelper) LoginBasic2() {
   407  	me.LoginBasic2WithClient(me.Client)
   408  }
   409  
   410  func (me *TestHelper) LoginTeamAdmin() {
   411  	me.LoginTeamAdminWithClient(me.Client)
   412  }
   413  
   414  func (me *TestHelper) LoginSystemAdmin() {
   415  	me.LoginSystemAdminWithClient(me.SystemAdminClient)
   416  }
   417  
   418  func (me *TestHelper) LoginBasicWithClient(client *model.Client4) {
   419  	utils.DisableDebugLogForTest()
   420  	client.Login(me.BasicUser.Email, me.BasicUser.Password)
   421  	utils.EnableDebugLogForTest()
   422  }
   423  
   424  func (me *TestHelper) LoginBasic2WithClient(client *model.Client4) {
   425  	utils.DisableDebugLogForTest()
   426  	client.Login(me.BasicUser2.Email, me.BasicUser2.Password)
   427  	utils.EnableDebugLogForTest()
   428  }
   429  
   430  func (me *TestHelper) LoginTeamAdminWithClient(client *model.Client4) {
   431  	utils.DisableDebugLogForTest()
   432  	client.Login(me.TeamAdminUser.Email, me.TeamAdminUser.Password)
   433  	utils.EnableDebugLogForTest()
   434  }
   435  
   436  func (me *TestHelper) LoginSystemAdminWithClient(client *model.Client4) {
   437  	utils.DisableDebugLogForTest()
   438  	client.Login(me.SystemAdminUser.Email, me.SystemAdminUser.Password)
   439  	utils.EnableDebugLogForTest()
   440  }
   441  
   442  func (me *TestHelper) UpdateActiveUser(user *model.User, active bool) {
   443  	utils.DisableDebugLogForTest()
   444  
   445  	_, err := me.App.UpdateActive(user, active)
   446  	if err != nil {
   447  		l4g.Error(err.Error())
   448  		l4g.Close()
   449  		time.Sleep(time.Second)
   450  		panic(err)
   451  	}
   452  
   453  	utils.EnableDebugLogForTest()
   454  }
   455  
   456  func (me *TestHelper) LinkUserToTeam(user *model.User, team *model.Team) {
   457  	utils.DisableDebugLogForTest()
   458  
   459  	err := me.App.JoinUserToTeam(team, user, "")
   460  	if err != nil {
   461  		l4g.Error(err.Error())
   462  		l4g.Close()
   463  		time.Sleep(time.Second)
   464  		panic(err)
   465  	}
   466  
   467  	utils.EnableDebugLogForTest()
   468  }
   469  
   470  func (me *TestHelper) GenerateTestEmail() string {
   471  	if me.App.Config().EmailSettings.SMTPServer != "dockerhost" && os.Getenv("CI_INBUCKET_PORT") == "" {
   472  		return strings.ToLower("success+" + model.NewId() + "@simulator.amazonses.com")
   473  	}
   474  	return strings.ToLower(model.NewId() + "@dockerhost")
   475  }
   476  
   477  func GenerateTestUsername() string {
   478  	return "fakeuser" + model.NewRandomString(10)
   479  }
   480  
   481  func GenerateTestTeamName() string {
   482  	return "faketeam" + model.NewRandomString(6)
   483  }
   484  
   485  func GenerateTestChannelName() string {
   486  	return "fakechannel" + model.NewRandomString(10)
   487  }
   488  
   489  func GenerateTestAppName() string {
   490  	return "fakeoauthapp" + model.NewRandomString(10)
   491  }
   492  
   493  func GenerateTestId() string {
   494  	return model.NewId()
   495  }
   496  
   497  func CheckUserSanitization(t *testing.T, user *model.User) {
   498  	t.Helper()
   499  
   500  	if user.Password != "" {
   501  		t.Fatal("password wasn't blank")
   502  	}
   503  
   504  	if user.AuthData != nil && *user.AuthData != "" {
   505  		t.Fatal("auth data wasn't blank")
   506  	}
   507  
   508  	if user.MfaSecret != "" {
   509  		t.Fatal("mfa secret wasn't blank")
   510  	}
   511  }
   512  
   513  func CheckTeamSanitization(t *testing.T, team *model.Team) {
   514  	t.Helper()
   515  
   516  	if team.Email != "" {
   517  		t.Fatal("email wasn't blank")
   518  	}
   519  
   520  	if team.AllowedDomains != "" {
   521  		t.Fatal("'allowed domains' wasn't blank")
   522  	}
   523  }
   524  
   525  func CheckEtag(t *testing.T, data interface{}, resp *model.Response) {
   526  	t.Helper()
   527  
   528  	if !reflect.ValueOf(data).IsNil() {
   529  		t.Fatal("etag data was not nil")
   530  	}
   531  
   532  	if resp.StatusCode != http.StatusNotModified {
   533  		t.Log("actual: " + strconv.Itoa(resp.StatusCode))
   534  		t.Log("expected: " + strconv.Itoa(http.StatusNotModified))
   535  		t.Fatal("wrong status code for etag")
   536  	}
   537  }
   538  
   539  func CheckNoError(t *testing.T, resp *model.Response) {
   540  	t.Helper()
   541  
   542  	if resp.Error != nil {
   543  		t.Fatal("Expected no error, got " + resp.Error.Error())
   544  	}
   545  }
   546  
   547  func CheckCreatedStatus(t *testing.T, resp *model.Response) {
   548  	t.Helper()
   549  
   550  	if resp.StatusCode != http.StatusCreated {
   551  		t.Log("actual: " + strconv.Itoa(resp.StatusCode))
   552  		t.Log("expected: " + strconv.Itoa(http.StatusCreated))
   553  		t.Fatal("wrong status code")
   554  	}
   555  }
   556  
   557  func CheckForbiddenStatus(t *testing.T, resp *model.Response) {
   558  	t.Helper()
   559  
   560  	if resp.Error == nil {
   561  		t.Fatal("should have errored with status:" + strconv.Itoa(http.StatusForbidden))
   562  		return
   563  	}
   564  
   565  	if resp.StatusCode != http.StatusForbidden {
   566  		t.Log("actual: " + strconv.Itoa(resp.StatusCode))
   567  		t.Log("expected: " + strconv.Itoa(http.StatusForbidden))
   568  		t.Fatal("wrong status code")
   569  	}
   570  }
   571  
   572  func CheckUnauthorizedStatus(t *testing.T, resp *model.Response) {
   573  	t.Helper()
   574  
   575  	if resp.Error == nil {
   576  		t.Fatal("should have errored with status:" + strconv.Itoa(http.StatusUnauthorized))
   577  		return
   578  	}
   579  
   580  	if resp.StatusCode != http.StatusUnauthorized {
   581  		t.Log("actual: " + strconv.Itoa(resp.StatusCode))
   582  		t.Log("expected: " + strconv.Itoa(http.StatusUnauthorized))
   583  		t.Fatal("wrong status code")
   584  	}
   585  }
   586  
   587  func CheckNotFoundStatus(t *testing.T, resp *model.Response) {
   588  	t.Helper()
   589  
   590  	if resp.Error == nil {
   591  		t.Fatal("should have errored with status:" + strconv.Itoa(http.StatusNotFound))
   592  		return
   593  	}
   594  
   595  	if resp.StatusCode != http.StatusNotFound {
   596  		t.Log("actual: " + strconv.Itoa(resp.StatusCode))
   597  		t.Log("expected: " + strconv.Itoa(http.StatusNotFound))
   598  		t.Fatal("wrong status code")
   599  	}
   600  }
   601  
   602  func CheckBadRequestStatus(t *testing.T, resp *model.Response) {
   603  	t.Helper()
   604  
   605  	if resp.Error == nil {
   606  		t.Fatal("should have errored with status:" + strconv.Itoa(http.StatusBadRequest))
   607  		return
   608  	}
   609  
   610  	if resp.StatusCode != http.StatusBadRequest {
   611  		t.Log("actual: " + strconv.Itoa(resp.StatusCode))
   612  		t.Log("expected: " + strconv.Itoa(http.StatusBadRequest))
   613  		t.Fatal("wrong status code")
   614  	}
   615  }
   616  
   617  func CheckNotImplementedStatus(t *testing.T, resp *model.Response) {
   618  	t.Helper()
   619  
   620  	if resp.Error == nil {
   621  		t.Fatal("should have errored with status:" + strconv.Itoa(http.StatusNotImplemented))
   622  		return
   623  	}
   624  
   625  	if resp.StatusCode != http.StatusNotImplemented {
   626  		t.Log("actual: " + strconv.Itoa(resp.StatusCode))
   627  		t.Log("expected: " + strconv.Itoa(http.StatusNotImplemented))
   628  		t.Fatal("wrong status code")
   629  	}
   630  }
   631  
   632  func CheckOKStatus(t *testing.T, resp *model.Response) {
   633  	t.Helper()
   634  
   635  	CheckNoError(t, resp)
   636  
   637  	if resp.StatusCode != http.StatusOK {
   638  		t.Fatalf("wrong status code. expected %d got %d", http.StatusOK, resp.StatusCode)
   639  	}
   640  }
   641  
   642  func CheckErrorMessage(t *testing.T, resp *model.Response, errorId string) {
   643  	t.Helper()
   644  
   645  	if resp.Error == nil {
   646  		t.Fatal("should have errored with message:" + errorId)
   647  		return
   648  	}
   649  
   650  	if resp.Error.Id != errorId {
   651  		t.Log("actual: " + resp.Error.Id)
   652  		t.Log("expected: " + errorId)
   653  		t.Fatal("incorrect error message")
   654  	}
   655  }
   656  
   657  func CheckInternalErrorStatus(t *testing.T, resp *model.Response) {
   658  	t.Helper()
   659  
   660  	if resp.Error == nil {
   661  		t.Fatal("should have errored with status:" + strconv.Itoa(http.StatusInternalServerError))
   662  		return
   663  	}
   664  
   665  	if resp.StatusCode != http.StatusInternalServerError {
   666  		t.Log("actual: " + strconv.Itoa(resp.StatusCode))
   667  		t.Log("expected: " + strconv.Itoa(http.StatusInternalServerError))
   668  		t.Fatal("wrong status code")
   669  	}
   670  }
   671  
   672  func CheckPayLoadTooLargeStatus(t *testing.T, resp *model.Response) {
   673  	t.Helper()
   674  
   675  	if resp.Error == nil {
   676  		t.Fatal("should have errored with status:" + strconv.Itoa(http.StatusRequestEntityTooLarge))
   677  		return
   678  	}
   679  
   680  	if resp.StatusCode != http.StatusRequestEntityTooLarge {
   681  		t.Log("actual: " + strconv.Itoa(resp.StatusCode))
   682  		t.Log("expected: " + strconv.Itoa(http.StatusRequestEntityTooLarge))
   683  		t.Fatal("wrong status code")
   684  	}
   685  }
   686  
   687  func readTestFile(name string) ([]byte, error) {
   688  	path, _ := utils.FindDir("tests")
   689  	file, err := os.Open(path + "/" + name)
   690  	if err != nil {
   691  		return nil, err
   692  	}
   693  	defer file.Close()
   694  
   695  	data := &bytes.Buffer{}
   696  	if _, err := io.Copy(data, file); err != nil {
   697  		return nil, err
   698  	} else {
   699  		return data.Bytes(), nil
   700  	}
   701  }
   702  
   703  // Similar to s3.New() but allows initialization of signature v2 or signature v4 client.
   704  // If signV2 input is false, function always returns signature v4.
   705  //
   706  // Additionally this function also takes a user defined region, if set
   707  // disables automatic region lookup.
   708  func s3New(endpoint, accessKey, secretKey string, secure bool, signV2 bool, region string) (*s3.Client, error) {
   709  	var creds *credentials.Credentials
   710  	if signV2 {
   711  		creds = credentials.NewStatic(accessKey, secretKey, "", credentials.SignatureV2)
   712  	} else {
   713  		creds = credentials.NewStatic(accessKey, secretKey, "", credentials.SignatureV4)
   714  	}
   715  	return s3.NewWithCredentials(endpoint, creds, secure, region)
   716  }
   717  
   718  func (me *TestHelper) cleanupTestFile(info *model.FileInfo) error {
   719  	cfg := me.App.Config()
   720  	if *cfg.FileSettings.DriverName == model.IMAGE_DRIVER_S3 {
   721  		endpoint := cfg.FileSettings.AmazonS3Endpoint
   722  		accessKey := cfg.FileSettings.AmazonS3AccessKeyId
   723  		secretKey := cfg.FileSettings.AmazonS3SecretAccessKey
   724  		secure := *cfg.FileSettings.AmazonS3SSL
   725  		signV2 := *cfg.FileSettings.AmazonS3SignV2
   726  		region := cfg.FileSettings.AmazonS3Region
   727  		s3Clnt, err := s3New(endpoint, accessKey, secretKey, secure, signV2, region)
   728  		if err != nil {
   729  			return err
   730  		}
   731  		bucket := cfg.FileSettings.AmazonS3Bucket
   732  		if err := s3Clnt.RemoveObject(bucket, info.Path); err != nil {
   733  			return err
   734  		}
   735  
   736  		if info.ThumbnailPath != "" {
   737  			if err := s3Clnt.RemoveObject(bucket, info.ThumbnailPath); err != nil {
   738  				return err
   739  			}
   740  		}
   741  
   742  		if info.PreviewPath != "" {
   743  			if err := s3Clnt.RemoveObject(bucket, info.PreviewPath); err != nil {
   744  				return err
   745  			}
   746  		}
   747  	} else if *cfg.FileSettings.DriverName == model.IMAGE_DRIVER_LOCAL {
   748  		if err := os.Remove(cfg.FileSettings.Directory + info.Path); err != nil {
   749  			return err
   750  		}
   751  
   752  		if info.ThumbnailPath != "" {
   753  			if err := os.Remove(cfg.FileSettings.Directory + info.ThumbnailPath); err != nil {
   754  				return err
   755  			}
   756  		}
   757  
   758  		if info.PreviewPath != "" {
   759  			if err := os.Remove(cfg.FileSettings.Directory + info.PreviewPath); err != nil {
   760  				return err
   761  			}
   762  		}
   763  	}
   764  
   765  	return nil
   766  }
   767  
   768  func (me *TestHelper) MakeUserChannelAdmin(user *model.User, channel *model.Channel) {
   769  	utils.DisableDebugLogForTest()
   770  
   771  	if cmr := <-me.App.Srv.Store.Channel().GetMember(channel.Id, user.Id); cmr.Err == nil {
   772  		cm := cmr.Data.(*model.ChannelMember)
   773  		cm.Roles = "channel_admin channel_user"
   774  		if sr := <-me.App.Srv.Store.Channel().UpdateMember(cm); sr.Err != nil {
   775  			utils.EnableDebugLogForTest()
   776  			panic(sr.Err)
   777  		}
   778  	} else {
   779  		utils.EnableDebugLogForTest()
   780  		panic(cmr.Err)
   781  	}
   782  
   783  	utils.EnableDebugLogForTest()
   784  }
   785  
   786  func (me *TestHelper) UpdateUserToTeamAdmin(user *model.User, team *model.Team) {
   787  	utils.DisableDebugLogForTest()
   788  
   789  	tm := &model.TeamMember{TeamId: team.Id, UserId: user.Id, Roles: model.TEAM_USER_ROLE_ID + " " + model.TEAM_ADMIN_ROLE_ID}
   790  	if tmr := <-me.App.Srv.Store.Team().UpdateMember(tm); tmr.Err != nil {
   791  		utils.EnableDebugLogForTest()
   792  		l4g.Error(tmr.Err.Error())
   793  		l4g.Close()
   794  		time.Sleep(time.Second)
   795  		panic(tmr.Err)
   796  	}
   797  	utils.EnableDebugLogForTest()
   798  }
   799  
   800  func (me *TestHelper) UpdateUserToNonTeamAdmin(user *model.User, team *model.Team) {
   801  	utils.DisableDebugLogForTest()
   802  
   803  	tm := &model.TeamMember{TeamId: team.Id, UserId: user.Id, Roles: model.TEAM_USER_ROLE_ID}
   804  	if tmr := <-me.App.Srv.Store.Team().UpdateMember(tm); tmr.Err != nil {
   805  		utils.EnableDebugLogForTest()
   806  		l4g.Error(tmr.Err.Error())
   807  		l4g.Close()
   808  		time.Sleep(time.Second)
   809  		panic(tmr.Err)
   810  	}
   811  	utils.EnableDebugLogForTest()
   812  }