[MM-37557] Move error out of client4 response (#18101)

* Return an error seperately from Response

* Remove BuildErrorResponse

* Drop Response.Error from model/client4.go

* Migrate require.Nil checks

* Migrate require.NotNil checks

* More manual fixes

* Move error check out of CheckOKStatus and CheckCreatedStatus

* Move error check out of CheckForbiddenStatus

* Move error check out of CheckUnauthorizedStatus

* Move error check out of CheckNotFoundStatus

* Move error check out of CheckBadRequestStatus

* Move error check out of CheckNotImplementedStatus and CheckRequestEntityTooLargeStatus

* Move error check out of CheckInternalErrorStatus

* Move error check out of CheckServiceUnavailableStatus

* Remove error check from checkHTTPStatus

* Remove remaining references to Response.Error

* Check previously unchecked errors

* Manually fix compile and linter errors

* Return error in CreateWebSocket methods

* Return error instead of *AppError in DoApi methods

* Manually fix bad replacments

* Conistently return Response and error

* Use err instead of seperate bool return value to indicate success

* Reduce ussage of model.AppError in web/oauth_test.go

* Remove client4.Must

* Check error in buf.ReadFrom

* Fix failing tests
This commit is contained in:
Ben Schumacher 2021-08-13 13:12:16 +02:00 committed by GitHub
parent 96593580ae
commit a8ca5c423f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
60 changed files with 9790 additions and 8706 deletions

View file

@ -5,6 +5,7 @@ package api4
import (
"context"
"errors"
"fmt"
"io/ioutil"
"math/rand"
@ -473,19 +474,19 @@ func (th *TestHelper) CreateLocalClient(socketPath string) *model.Client4 {
}
}
func (th *TestHelper) CreateWebSocketClient() (*model.WebSocketClient, *model.AppError) {
func (th *TestHelper) CreateWebSocketClient() (*model.WebSocketClient, error) {
return model.NewWebSocketClient4(fmt.Sprintf("ws://localhost:%v", th.App.Srv().ListenAddr.Port), th.Client.AuthToken)
}
func (th *TestHelper) CreateWebSocketSystemAdminClient() (*model.WebSocketClient, *model.AppError) {
func (th *TestHelper) CreateWebSocketSystemAdminClient() (*model.WebSocketClient, error) {
return model.NewWebSocketClient4(fmt.Sprintf("ws://localhost:%v", th.App.Srv().ListenAddr.Port), th.SystemAdminClient.AuthToken)
}
func (th *TestHelper) CreateWebSocketSystemManagerClient() (*model.WebSocketClient, *model.AppError) {
func (th *TestHelper) CreateWebSocketSystemManagerClient() (*model.WebSocketClient, error) {
return model.NewWebSocketClient4(fmt.Sprintf("ws://localhost:%v", th.App.Srv().ListenAddr.Port), th.SystemManagerClient.AuthToken)
}
func (th *TestHelper) CreateWebSocketClientWithClient(client *model.Client4) (*model.WebSocketClient, *model.AppError) {
func (th *TestHelper) CreateWebSocketClientWithClient(client *model.Client4) (*model.WebSocketClient, error) {
return model.NewWebSocketClient4(fmt.Sprintf("ws://localhost:%v", th.App.Srv().ListenAddr.Port), client.AuthToken)
}
@ -501,9 +502,9 @@ func (th *TestHelper) CreateBotWithClient(client *model.Client4) *model.Bot {
}
utils.DisableDebugLogForTest()
rbot, resp := client.CreateBot(bot)
if resp.Error != nil {
panic(resp.Error)
rbot, _, err := client.CreateBot(bot)
if err != nil {
panic(err)
}
utils.EnableDebugLogForTest()
return rbot
@ -527,9 +528,9 @@ func (th *TestHelper) CreateTeamWithClient(client *model.Client4) *model.Team {
}
utils.DisableDebugLogForTest()
rteam, resp := client.CreateTeam(team)
if resp.Error != nil {
panic(resp.Error)
rteam, _, err := client.CreateTeam(team)
if err != nil {
panic(err)
}
utils.EnableDebugLogForTest()
return rteam
@ -548,13 +549,13 @@ func (th *TestHelper) CreateUserWithClient(client *model.Client4) *model.User {
}
utils.DisableDebugLogForTest()
ruser, response := client.CreateUser(user)
if response.Error != nil {
panic(response.Error)
ruser, _, err := client.CreateUser(user)
if err != nil {
panic(err)
}
ruser.Password = "Pa$$word11"
_, err := th.App.Srv().Store.User().VerifyEmail(ruser.Id, ruser.Email)
_, err = th.App.Srv().Store.User().VerifyEmail(ruser.Id, ruser.Email)
if err != nil {
return nil
}
@ -651,9 +652,9 @@ func (th *TestHelper) CreateChannelWithClientAndTeam(client *model.Client4, chan
}
utils.DisableDebugLogForTest()
rchannel, resp := client.CreateChannel(channel)
if resp.Error != nil {
panic(resp.Error)
rchannel, _, err := client.CreateChannel(channel)
if err != nil {
panic(err)
}
utils.EnableDebugLogForTest()
return rchannel
@ -680,9 +681,9 @@ func (th *TestHelper) CreatePostWithClient(client *model.Client4, channel *model
}
utils.DisableDebugLogForTest()
rpost, resp := client.CreatePost(post)
if resp.Error != nil {
panic(resp.Error)
rpost, _, err := client.CreatePost(post)
if err != nil {
panic(err)
}
utils.EnableDebugLogForTest()
return rpost
@ -698,9 +699,9 @@ func (th *TestHelper) CreatePinnedPostWithClient(client *model.Client4, channel
}
utils.DisableDebugLogForTest()
rpost, resp := client.CreatePost(post)
if resp.Error != nil {
panic(resp.Error)
rpost, _, err := client.CreatePost(post)
if err != nil {
panic(err)
}
utils.EnableDebugLogForTest()
return rpost
@ -713,9 +714,9 @@ func (th *TestHelper) CreateMessagePostWithClient(client *model.Client4, channel
}
utils.DisableDebugLogForTest()
rpost, resp := client.CreatePost(post)
if resp.Error != nil {
panic(resp.Error)
rpost, _, err := client.CreatePost(post)
if err != nil {
panic(err)
}
utils.EnableDebugLogForTest()
return rpost
@ -769,45 +770,45 @@ func (th *TestHelper) LoginSystemManager() {
func (th *TestHelper) LoginBasicWithClient(client *model.Client4) {
utils.DisableDebugLogForTest()
_, resp := client.Login(th.BasicUser.Email, th.BasicUser.Password)
if resp.Error != nil {
panic(resp.Error)
_, _, err := client.Login(th.BasicUser.Email, th.BasicUser.Password)
if err != nil {
panic(err)
}
utils.EnableDebugLogForTest()
}
func (th *TestHelper) LoginBasic2WithClient(client *model.Client4) {
utils.DisableDebugLogForTest()
_, resp := client.Login(th.BasicUser2.Email, th.BasicUser2.Password)
if resp.Error != nil {
panic(resp.Error)
_, _, err := client.Login(th.BasicUser2.Email, th.BasicUser2.Password)
if err != nil {
panic(err)
}
utils.EnableDebugLogForTest()
}
func (th *TestHelper) LoginTeamAdminWithClient(client *model.Client4) {
utils.DisableDebugLogForTest()
_, resp := client.Login(th.TeamAdminUser.Email, th.TeamAdminUser.Password)
if resp.Error != nil {
panic(resp.Error)
_, _, err := client.Login(th.TeamAdminUser.Email, th.TeamAdminUser.Password)
if err != nil {
panic(err)
}
utils.EnableDebugLogForTest()
}
func (th *TestHelper) LoginSystemManagerWithClient(client *model.Client4) {
utils.DisableDebugLogForTest()
_, resp := client.Login(th.SystemManagerUser.Email, th.SystemManagerUser.Password)
if resp.Error != nil {
panic(resp.Error)
_, _, err := client.Login(th.SystemManagerUser.Email, th.SystemManagerUser.Password)
if err != nil {
panic(err)
}
utils.EnableDebugLogForTest()
}
func (th *TestHelper) LoginSystemAdminWithClient(client *model.Client4) {
utils.DisableDebugLogForTest()
_, resp := client.Login(th.SystemAdminUser.Email, th.SystemAdminUser.Password)
if resp.Error != nil {
panic(resp.Error)
_, _, err := client.Login(th.SystemAdminUser.Email, th.SystemAdminUser.Password)
if err != nil {
panic(err)
}
utils.EnableDebugLogForTest()
}
@ -947,82 +948,90 @@ func CheckEtag(t *testing.T, data interface{}, resp *model.Response) {
require.Equal(t, resp.StatusCode, http.StatusNotModified, "wrong status code for etag")
}
func CheckNoError(t *testing.T, resp *model.Response) {
func checkHTTPStatus(t *testing.T, resp *model.Response, expectedStatus int) {
t.Helper()
require.Nil(t, resp.Error, "expected no error")
}
func checkHTTPStatus(t *testing.T, resp *model.Response, expectedStatus int, expectError bool) {
t.Helper()
require.NotNilf(t, resp, "Unexpected nil response, expected http:%v, expectError:%v", expectedStatus, expectError)
if expectError {
require.NotNil(t, resp.Error, "Expected a non-nil error and http status:%v, got nil, %v", expectedStatus, resp.StatusCode)
} else {
require.Nil(t, resp.Error, "Expected no error and http status:%v, got %q, http:%v", expectedStatus, resp.Error, resp.StatusCode)
}
require.Equalf(t, expectedStatus, resp.StatusCode, "Expected http status:%v, got %v (err: %q)", expectedStatus, resp.StatusCode, resp.Error)
require.NotNilf(t, resp, "Unexpected nil response, expected http status:%v", expectedStatus)
require.Equalf(t, expectedStatus, resp.StatusCode, "Expected http status:%v, got %v", expectedStatus, resp.StatusCode)
}
func CheckOKStatus(t *testing.T, resp *model.Response) {
t.Helper()
checkHTTPStatus(t, resp, http.StatusOK, false)
checkHTTPStatus(t, resp, http.StatusOK)
}
func CheckCreatedStatus(t *testing.T, resp *model.Response) {
t.Helper()
checkHTTPStatus(t, resp, http.StatusCreated, false)
checkHTTPStatus(t, resp, http.StatusCreated)
}
func CheckForbiddenStatus(t *testing.T, resp *model.Response) {
t.Helper()
checkHTTPStatus(t, resp, http.StatusForbidden, true)
checkHTTPStatus(t, resp, http.StatusForbidden)
}
func CheckUnauthorizedStatus(t *testing.T, resp *model.Response) {
t.Helper()
checkHTTPStatus(t, resp, http.StatusUnauthorized, true)
checkHTTPStatus(t, resp, http.StatusUnauthorized)
}
func CheckNotFoundStatus(t *testing.T, resp *model.Response) {
t.Helper()
checkHTTPStatus(t, resp, http.StatusNotFound, true)
checkHTTPStatus(t, resp, http.StatusNotFound)
}
func CheckBadRequestStatus(t *testing.T, resp *model.Response) {
t.Helper()
checkHTTPStatus(t, resp, http.StatusBadRequest, true)
checkHTTPStatus(t, resp, http.StatusBadRequest)
}
func CheckNotImplementedStatus(t *testing.T, resp *model.Response) {
t.Helper()
checkHTTPStatus(t, resp, http.StatusNotImplemented, true)
checkHTTPStatus(t, resp, http.StatusNotImplemented)
}
func CheckRequestEntityTooLargeStatus(t *testing.T, resp *model.Response) {
t.Helper()
checkHTTPStatus(t, resp, http.StatusRequestEntityTooLarge, true)
checkHTTPStatus(t, resp, http.StatusRequestEntityTooLarge)
}
func CheckInternalErrorStatus(t *testing.T, resp *model.Response) {
t.Helper()
checkHTTPStatus(t, resp, http.StatusInternalServerError, true)
checkHTTPStatus(t, resp, http.StatusInternalServerError)
}
func CheckServiceUnavailableStatus(t *testing.T, resp *model.Response) {
t.Helper()
checkHTTPStatus(t, resp, http.StatusServiceUnavailable, true)
checkHTTPStatus(t, resp, http.StatusServiceUnavailable)
}
func CheckErrorMessage(t *testing.T, resp *model.Response, errorId string) {
func CheckErrorID(t *testing.T, err error, errorId string) {
t.Helper()
require.NotNilf(t, resp.Error, "should have errored with message: %s", errorId)
require.Equalf(t, errorId, resp.Error.Id, "incorrect error message, actual: %s, expected: %s", resp.Error.Id, errorId)
require.Error(t, err, "should have errored with id: %s", errorId)
var appError *model.AppError
ok := errors.As(err, &appError)
require.True(t, ok, "should have been a model.AppError")
require.Equalf(t, errorId, appError.Id, "incorrect error id, actual: %s, expected: %s", appError.Id, errorId)
}
func CheckErrorMessage(t *testing.T, err error, message string) {
t.Helper()
require.Error(t, err, "should have errored with message: %s", message)
var appError *model.AppError
ok := errors.As(err, &appError)
require.True(t, ok, "should have been a model.AppError")
require.Equalf(t, message, appError.Message, "incorrect error message, actual: %s, expected: %s", appError.Id, message)
}
func CheckStartsWith(t *testing.T, value, prefix, message string) {
t.Helper()
require.True(t, strings.HasPrefix(value, prefix), message, value)
}

View file

@ -7,6 +7,7 @@ import (
"testing"
"github.com/mattermost/mattermost-server/v6/model"
"github.com/stretchr/testify/require"
)
func TestBlevePurgeIndexes(t *testing.T) {
@ -14,26 +15,30 @@ func TestBlevePurgeIndexes(t *testing.T) {
defer th.TearDown()
t.Run("as system user", func(t *testing.T) {
_, resp := th.Client.PurgeBleveIndexes()
resp, err := th.Client.PurgeBleveIndexes()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("as system user with write experimental permission", func(t *testing.T) {
th.AddPermissionToRole(model.PermissionPurgeBleveIndexes.Id, model.SystemUserRoleId)
defer th.RemovePermissionFromRole(model.PermissionSysconsoleWriteExperimental.Id, model.SystemUserRoleId)
_, resp := th.Client.PurgeBleveIndexes()
resp, err := th.Client.PurgeBleveIndexes()
require.NoError(t, err)
CheckOKStatus(t, resp)
})
t.Run("as system admin", func(t *testing.T) {
_, resp := th.SystemAdminClient.PurgeBleveIndexes()
resp, err := th.SystemAdminClient.PurgeBleveIndexes()
require.NoError(t, err)
CheckOKStatus(t, resp)
})
t.Run("as restricted system admin", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
_, resp := th.SystemAdminClient.PurgeBleveIndexes()
resp, err := th.SystemAdminClient.PurgeBleveIndexes()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
}

File diff suppressed because it is too large Load diff

View file

@ -15,34 +15,39 @@ import (
func TestGetBrandImage(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
client := th.Client
_, resp := Client.GetBrandImage()
_, resp, err := client.GetBrandImage()
require.Error(t, err)
CheckNotFoundStatus(t, resp)
Client.Logout()
_, resp = Client.GetBrandImage()
client.Logout()
_, resp, err = client.GetBrandImage()
require.Error(t, err)
CheckNotFoundStatus(t, resp)
_, resp = th.SystemAdminClient.GetBrandImage()
_, resp, err = th.SystemAdminClient.GetBrandImage()
require.Error(t, err)
CheckNotFoundStatus(t, resp)
}
func TestUploadBrandImage(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
client := th.Client
data, err := testutils.ReadTestFile("test.png")
require.NoError(t, err)
_, resp := Client.UploadBrandImage(data)
resp, err := client.UploadBrandImage(data)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
// status code returns either forbidden or unauthorized
// note: forbidden is set as default at Client4.SetProfileImage when request is terminated early by server
Client.Logout()
_, resp = Client.UploadBrandImage(data)
client.Logout()
resp, err = client.UploadBrandImage(data)
require.Error(t, err)
if resp.StatusCode == http.StatusForbidden {
CheckForbiddenStatus(t, resp)
} else if resp.StatusCode == http.StatusUnauthorized {
@ -51,7 +56,8 @@ func TestUploadBrandImage(t *testing.T) {
require.Fail(t, "Should have failed either forbidden or unauthorized")
}
_, resp = th.SystemAdminClient.UploadBrandImage(data)
resp, err = th.SystemAdminClient.UploadBrandImage(data)
require.NoError(t, err)
CheckCreatedStatus(t, resp)
}
@ -62,20 +68,25 @@ func TestDeleteBrandImage(t *testing.T) {
data, err := testutils.ReadTestFile("test.png")
require.NoError(t, err)
_, resp := th.SystemAdminClient.UploadBrandImage(data)
resp, err := th.SystemAdminClient.UploadBrandImage(data)
require.NoError(t, err)
CheckCreatedStatus(t, resp)
resp = th.Client.DeleteBrandImage()
resp, err = th.Client.DeleteBrandImage()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
th.Client.Logout()
resp = th.Client.DeleteBrandImage()
resp, err = th.Client.DeleteBrandImage()
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
resp = th.SystemAdminClient.DeleteBrandImage()
resp, err = th.SystemAdminClient.DeleteBrandImage()
require.NoError(t, err)
CheckOKStatus(t, resp)
resp = th.SystemAdminClient.DeleteBrandImage()
resp, err = th.SystemAdminClient.DeleteBrandImage()
require.Error(t, err)
CheckNotFoundStatus(t, resp)
}

View file

@ -19,8 +19,8 @@ func TestCreateCategoryForTeamForUser(t *testing.T) {
t.Run("should silently prevent the user from creating a category with an invalid channel ID", func(t *testing.T) {
user, client := setupUserForSubtest(t, th)
categories, resp := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.Nil(t, resp.Error)
categories, _, err := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.NoError(t, err)
require.Len(t, categories.Categories, 3)
require.Len(t, categories.Order, 3)
@ -34,8 +34,8 @@ func TestCreateCategoryForTeamForUser(t *testing.T) {
Channels: []string{th.BasicChannel.Id, "notachannel", th.BasicChannel2.Id},
}
received, resp := client.CreateSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, category)
require.Nil(t, resp.Error)
received, _, err := client.CreateSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, category)
require.NoError(t, err)
assert.NotContains(t, received.Channels, "notachannel")
assert.Equal(t, []string{th.BasicChannel.Id, th.BasicChannel2.Id}, received.Channels)
})
@ -43,18 +43,18 @@ func TestCreateCategoryForTeamForUser(t *testing.T) {
t.Run("should silently prevent the user from creating a category with a channel that they're not a member of", func(t *testing.T) {
user, client := setupUserForSubtest(t, th)
categories, resp := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.Nil(t, resp.Error)
categories, _, err := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.NoError(t, err)
require.Len(t, categories.Categories, 3)
require.Len(t, categories.Order, 3)
// Have another user create a channel that user isn't a part of
channel, resp := th.SystemAdminClient.CreateChannel(&model.Channel{
channel, _, err := th.SystemAdminClient.CreateChannel(&model.Channel{
TeamId: th.BasicTeam.Id,
Type: model.ChannelTypeOpen,
Name: "testchannel",
})
require.Nil(t, resp.Error)
require.NoError(t, err)
// Attempt to create the category
category := &model.SidebarCategoryWithChannels{
@ -66,8 +66,8 @@ func TestCreateCategoryForTeamForUser(t *testing.T) {
Channels: []string{th.BasicChannel.Id, channel.Id},
}
received, resp := client.CreateSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, category)
require.Nil(t, resp.Error)
received, _, err := client.CreateSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, category)
require.NoError(t, err)
assert.NotContains(t, received.Channels, channel.Id)
assert.Equal(t, []string{th.BasicChannel.Id}, received.Channels)
})
@ -80,8 +80,8 @@ func TestUpdateCategoryForTeamForUser(t *testing.T) {
t.Run("should update the channel order of the Channels category", func(t *testing.T) {
user, client := setupUserForSubtest(t, th)
categories, resp := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.Nil(t, resp.Error)
categories, _, err := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.NoError(t, err)
require.Len(t, categories.Categories, 3)
require.Len(t, categories.Order, 3)
@ -95,14 +95,14 @@ func TestUpdateCategoryForTeamForUser(t *testing.T) {
Channels: []string{channelsCategory.Channels[1], channelsCategory.Channels[0], channelsCategory.Channels[4], channelsCategory.Channels[3], channelsCategory.Channels[2]},
}
received, resp := client.UpdateSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, channelsCategory.Id, updatedCategory)
assert.Nil(t, resp.Error)
received, _, err := client.UpdateSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, channelsCategory.Id, updatedCategory)
assert.NoError(t, err)
assert.Equal(t, channelsCategory.Id, received.Id)
assert.Equal(t, updatedCategory.Channels, received.Channels)
// And when requesting the category later
received, resp = client.GetSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, channelsCategory.Id, "")
assert.Nil(t, resp.Error)
received, _, err = client.GetSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, channelsCategory.Id, "")
assert.NoError(t, err)
assert.Equal(t, channelsCategory.Id, received.Id)
assert.Equal(t, updatedCategory.Channels, received.Channels)
})
@ -110,8 +110,8 @@ func TestUpdateCategoryForTeamForUser(t *testing.T) {
t.Run("should update the sort order of the DM category", func(t *testing.T) {
user, client := setupUserForSubtest(t, th)
categories, resp := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.Nil(t, resp.Error)
categories, _, err := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.NoError(t, err)
require.Len(t, categories.Categories, 3)
require.Len(t, categories.Order, 3)
@ -126,14 +126,14 @@ func TestUpdateCategoryForTeamForUser(t *testing.T) {
}
updatedCategory.Sorting = model.SidebarCategorySortAlphabetical
received, resp := client.UpdateSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, dmsCategory.Id, updatedCategory)
assert.Nil(t, resp.Error)
received, _, err := client.UpdateSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, dmsCategory.Id, updatedCategory)
assert.NoError(t, err)
assert.Equal(t, dmsCategory.Id, received.Id)
assert.Equal(t, model.SidebarCategorySortAlphabetical, received.Sorting)
// And when requesting the category later
received, resp = client.GetSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, dmsCategory.Id, "")
assert.Nil(t, resp.Error)
received, _, err = client.GetSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, dmsCategory.Id, "")
assert.NoError(t, err)
assert.Equal(t, dmsCategory.Id, received.Id)
assert.Equal(t, model.SidebarCategorySortAlphabetical, received.Sorting)
})
@ -141,14 +141,14 @@ func TestUpdateCategoryForTeamForUser(t *testing.T) {
t.Run("should update the display name of a custom category", func(t *testing.T) {
user, client := setupUserForSubtest(t, th)
customCategory, resp := client.CreateSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, &model.SidebarCategoryWithChannels{
customCategory, _, err := client.CreateSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, &model.SidebarCategoryWithChannels{
SidebarCategory: model.SidebarCategory{
UserId: user.Id,
TeamId: th.BasicTeam.Id,
DisplayName: "custom123",
},
})
require.Nil(t, resp.Error)
require.NoError(t, err)
require.Equal(t, "custom123", customCategory.DisplayName)
// Should return the correct values from the API
@ -158,14 +158,14 @@ func TestUpdateCategoryForTeamForUser(t *testing.T) {
}
updatedCategory.DisplayName = "abcCustom"
received, resp := client.UpdateSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, customCategory.Id, updatedCategory)
assert.Nil(t, resp.Error)
received, _, err := client.UpdateSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, customCategory.Id, updatedCategory)
assert.NoError(t, err)
assert.Equal(t, customCategory.Id, received.Id)
assert.Equal(t, updatedCategory.DisplayName, received.DisplayName)
// And when requesting the category later
received, resp = client.GetSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, customCategory.Id, "")
assert.Nil(t, resp.Error)
received, _, err = client.GetSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, customCategory.Id, "")
assert.NoError(t, err)
assert.Equal(t, customCategory.Id, received.Id)
assert.Equal(t, updatedCategory.DisplayName, received.DisplayName)
})
@ -173,8 +173,8 @@ func TestUpdateCategoryForTeamForUser(t *testing.T) {
t.Run("should update the channel order of the category even if it contains archived channels", func(t *testing.T) {
user, client := setupUserForSubtest(t, th)
categories, resp := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.Nil(t, resp.Error)
categories, _, err := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.NoError(t, err)
require.Len(t, categories.Categories, 3)
require.Len(t, categories.Order, 3)
@ -183,8 +183,8 @@ func TestUpdateCategoryForTeamForUser(t *testing.T) {
require.Len(t, channelsCategory.Channels, 5) // Town Square, Off Topic, and the 3 channels created by InitBasic
// Delete one of the channels
_, resp = client.DeleteChannel(th.BasicChannel.Id)
require.Nil(t, resp.Error)
_, err = client.DeleteChannel(th.BasicChannel.Id)
require.NoError(t, err)
// Should still be able to reorder the channels
updatedCategory := &model.SidebarCategoryWithChannels{
@ -192,8 +192,8 @@ func TestUpdateCategoryForTeamForUser(t *testing.T) {
Channels: []string{channelsCategory.Channels[1], channelsCategory.Channels[0], channelsCategory.Channels[4], channelsCategory.Channels[3], channelsCategory.Channels[2]},
}
received, resp := client.UpdateSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, channelsCategory.Id, updatedCategory)
require.Nil(t, resp.Error)
received, _, err := client.UpdateSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, channelsCategory.Id, updatedCategory)
require.NoError(t, err)
assert.Equal(t, channelsCategory.Id, received.Id)
assert.Equal(t, updatedCategory.Channels, received.Channels)
})
@ -201,8 +201,8 @@ func TestUpdateCategoryForTeamForUser(t *testing.T) {
t.Run("should silently prevent the user from adding an invalid channel ID", func(t *testing.T) {
user, client := setupUserForSubtest(t, th)
categories, resp := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.Nil(t, resp.Error)
categories, _, err := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.NoError(t, err)
require.Len(t, categories.Categories, 3)
require.Len(t, categories.Order, 3)
@ -214,8 +214,8 @@ func TestUpdateCategoryForTeamForUser(t *testing.T) {
Channels: append(channelsCategory.Channels, "notachannel"),
}
received, resp := client.UpdateSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, channelsCategory.Id, updatedCategory)
require.Nil(t, resp.Error)
received, _, err := client.UpdateSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, channelsCategory.Id, updatedCategory)
require.NoError(t, err)
assert.Equal(t, channelsCategory.Id, received.Id)
assert.NotContains(t, received.Channels, "notachannel")
assert.Equal(t, channelsCategory.Channels, received.Channels)
@ -224,8 +224,8 @@ func TestUpdateCategoryForTeamForUser(t *testing.T) {
t.Run("should silently prevent the user from adding a channel that they're not a member of", func(t *testing.T) {
user, client := setupUserForSubtest(t, th)
categories, resp := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.Nil(t, resp.Error)
categories, _, err := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.NoError(t, err)
require.Len(t, categories.Categories, 3)
require.Len(t, categories.Order, 3)
@ -233,12 +233,12 @@ func TestUpdateCategoryForTeamForUser(t *testing.T) {
require.Equal(t, model.SidebarCategoryChannels, channelsCategory.Type)
// Have another user create a channel that user isn't a part of
channel, resp := th.SystemAdminClient.CreateChannel(&model.Channel{
channel, _, err := th.SystemAdminClient.CreateChannel(&model.Channel{
TeamId: th.BasicTeam.Id,
Type: model.ChannelTypeOpen,
Name: "testchannel",
})
require.Nil(t, resp.Error)
require.NoError(t, err)
// Attempt to update the category
updatedCategory := &model.SidebarCategoryWithChannels{
@ -246,8 +246,8 @@ func TestUpdateCategoryForTeamForUser(t *testing.T) {
Channels: append(channelsCategory.Channels, channel.Id),
}
received, resp := client.UpdateSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, channelsCategory.Id, updatedCategory)
require.Nil(t, resp.Error)
received, _, err := client.UpdateSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, channelsCategory.Id, updatedCategory)
require.NoError(t, err)
assert.Equal(t, channelsCategory.Id, received.Id)
assert.NotContains(t, received.Channels, channel.Id)
assert.Equal(t, channelsCategory.Channels, received.Channels)
@ -256,8 +256,8 @@ func TestUpdateCategoryForTeamForUser(t *testing.T) {
t.Run("muting a category should mute all of its channels", func(t *testing.T) {
user, client := setupUserForSubtest(t, th)
categories, resp := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.Nil(t, resp.Error)
categories, _, err := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.NoError(t, err)
require.Len(t, categories.Categories, 3)
require.Len(t, categories.Order, 3)
@ -277,28 +277,28 @@ func TestUpdateCategoryForTeamForUser(t *testing.T) {
Channels: channelsCategory.Channels,
}
received, resp := client.UpdateSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, channelsCategory.Id, updatedCategory)
require.Nil(t, resp.Error)
received, _, err := client.UpdateSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, channelsCategory.Id, updatedCategory)
require.NoError(t, err)
assert.Equal(t, channelsCategory.Id, received.Id)
assert.True(t, received.Muted)
// Check that the muted category was saved in the database
received, resp = client.GetSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, channelsCategory.Id, "")
require.Nil(t, resp.Error)
received, _, err = client.GetSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, channelsCategory.Id, "")
require.NoError(t, err)
assert.Equal(t, channelsCategory.Id, received.Id)
assert.True(t, received.Muted)
// Confirm that the channels in the category were muted
member, resp := client.GetChannelMember(channelsCategory.Channels[0], user.Id, "")
require.Nil(t, resp.Error)
member, _, err := client.GetChannelMember(channelsCategory.Channels[0], user.Id, "")
require.NoError(t, err)
assert.True(t, member.IsChannelMuted())
})
t.Run("should not be able to mute DM category", func(t *testing.T) {
user, client := setupUserForSubtest(t, th)
categories, resp := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.Nil(t, resp.Error)
categories, _, err := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.NoError(t, err)
require.Len(t, categories.Categories, 3)
require.Len(t, categories.Order, 3)
@ -307,8 +307,8 @@ func TestUpdateCategoryForTeamForUser(t *testing.T) {
require.Len(t, dmsCategory.Channels, 0)
// Ensure a DM channel exists
dmChannel, resp := client.CreateDirectChannel(user.Id, th.BasicUser.Id)
require.Nil(t, resp.Error)
dmChannel, _, err := client.CreateDirectChannel(user.Id, th.BasicUser.Id)
require.NoError(t, err)
// Attempt to mute the category
updatedCategory := &model.SidebarCategoryWithChannels{
@ -322,20 +322,20 @@ func TestUpdateCategoryForTeamForUser(t *testing.T) {
Channels: []string{dmChannel.Id},
}
received, resp := client.UpdateSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, dmsCategory.Id, updatedCategory)
require.Nil(t, resp.Error)
received, _, err := client.UpdateSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, dmsCategory.Id, updatedCategory)
require.NoError(t, err)
assert.Equal(t, dmsCategory.Id, received.Id)
assert.False(t, received.Muted)
// Check that the muted category was not saved in the database
received, resp = client.GetSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, dmsCategory.Id, "")
require.Nil(t, resp.Error)
received, _, err = client.GetSidebarCategoryForTeamForUser(user.Id, th.BasicTeam.Id, dmsCategory.Id, "")
require.NoError(t, err)
assert.Equal(t, dmsCategory.Id, received.Id)
assert.False(t, received.Muted)
// Confirm that the channels in the category were not muted
member, resp := client.GetChannelMember(dmChannel.Id, user.Id, "")
require.Nil(t, resp.Error)
member, _, err := client.GetChannelMember(dmChannel.Id, user.Id, "")
require.NoError(t, err)
assert.False(t, member.IsChannelMuted())
})
}
@ -347,8 +347,8 @@ func TestUpdateCategoriesForTeamForUser(t *testing.T) {
t.Run("should silently prevent the user from adding an invalid channel ID", func(t *testing.T) {
user, client := setupUserForSubtest(t, th)
categories, resp := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.Nil(t, resp.Error)
categories, _, err := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.NoError(t, err)
require.Len(t, categories.Categories, 3)
require.Len(t, categories.Order, 3)
@ -360,8 +360,8 @@ func TestUpdateCategoriesForTeamForUser(t *testing.T) {
Channels: append(channelsCategory.Channels, "notachannel"),
}
received, resp := client.UpdateSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, []*model.SidebarCategoryWithChannels{updatedCategory})
require.Nil(t, resp.Error)
received, _, err := client.UpdateSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, []*model.SidebarCategoryWithChannels{updatedCategory})
require.NoError(t, err)
assert.Equal(t, channelsCategory.Id, received[0].Id)
assert.NotContains(t, received[0].Channels, "notachannel")
assert.Equal(t, channelsCategory.Channels, received[0].Channels)
@ -370,8 +370,8 @@ func TestUpdateCategoriesForTeamForUser(t *testing.T) {
t.Run("should silently prevent the user from adding a channel that they're not a member of", func(t *testing.T) {
user, client := setupUserForSubtest(t, th)
categories, resp := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.Nil(t, resp.Error)
categories, _, err := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.NoError(t, err)
require.Len(t, categories.Categories, 3)
require.Len(t, categories.Order, 3)
@ -379,12 +379,12 @@ func TestUpdateCategoriesForTeamForUser(t *testing.T) {
require.Equal(t, model.SidebarCategoryChannels, channelsCategory.Type)
// Have another user create a channel that user isn't a part of
channel, resp := th.SystemAdminClient.CreateChannel(&model.Channel{
channel, _, err := th.SystemAdminClient.CreateChannel(&model.Channel{
TeamId: th.BasicTeam.Id,
Type: model.ChannelTypeOpen,
Name: "testchannel",
})
require.Nil(t, resp.Error)
require.NoError(t, err)
// Attempt to update the category
updatedCategory := &model.SidebarCategoryWithChannels{
@ -392,8 +392,8 @@ func TestUpdateCategoriesForTeamForUser(t *testing.T) {
Channels: append(channelsCategory.Channels, channel.Id),
}
received, resp := client.UpdateSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, []*model.SidebarCategoryWithChannels{updatedCategory})
require.Nil(t, resp.Error)
received, _, err := client.UpdateSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, []*model.SidebarCategoryWithChannels{updatedCategory})
require.NoError(t, err)
assert.Equal(t, channelsCategory.Id, received[0].Id)
assert.NotContains(t, received[0].Channels, channel.Id)
assert.Equal(t, channelsCategory.Channels, received[0].Channels)
@ -402,19 +402,19 @@ func TestUpdateCategoriesForTeamForUser(t *testing.T) {
t.Run("should update order", func(t *testing.T) {
user, client := setupUserForSubtest(t, th)
categories, resp := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.Nil(t, resp.Error)
categories, _, err := client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.NoError(t, err)
require.Len(t, categories.Categories, 3)
require.Len(t, categories.Order, 3)
channelsCategory := categories.Categories[1]
require.Equal(t, model.SidebarCategoryChannels, channelsCategory.Type)
_, resp = client.UpdateSidebarCategoryOrderForTeamForUser(user.Id, th.BasicTeam.Id, []string{categories.Order[1], categories.Order[0], categories.Order[2]})
require.Nil(t, resp.Error)
_, _, err = client.UpdateSidebarCategoryOrderForTeamForUser(user.Id, th.BasicTeam.Id, []string{categories.Order[1], categories.Order[0], categories.Order[2]})
require.NoError(t, err)
categories, resp = client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.Nil(t, resp.Error)
categories, _, err = client.GetSidebarCategoriesForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.NoError(t, err)
require.Len(t, categories.Categories, 3)
require.Len(t, categories.Order, 3)
@ -422,28 +422,28 @@ func TestUpdateCategoriesForTeamForUser(t *testing.T) {
require.Equal(t, model.SidebarCategoryChannels, channelsCategory.Type)
// validate order
newOrder, resp := client.GetSidebarCategoryOrderForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.Nil(t, resp.Error)
newOrder, _, err := client.GetSidebarCategoryOrderForTeamForUser(user.Id, th.BasicTeam.Id, "")
require.NoError(t, err)
require.EqualValues(t, newOrder, categories.Order)
// try to update with missing category
_, resp = client.UpdateSidebarCategoryOrderForTeamForUser(user.Id, th.BasicTeam.Id, []string{categories.Order[1], categories.Order[0]})
require.NotNil(t, resp.Error)
_, _, err = client.UpdateSidebarCategoryOrderForTeamForUser(user.Id, th.BasicTeam.Id, []string{categories.Order[1], categories.Order[0]})
require.Error(t, err)
// try to update with invalid category
_, resp = client.UpdateSidebarCategoryOrderForTeamForUser(user.Id, th.BasicTeam.Id, []string{categories.Order[1], categories.Order[0], "asd"})
require.NotNil(t, resp.Error)
_, _, err = client.UpdateSidebarCategoryOrderForTeamForUser(user.Id, th.BasicTeam.Id, []string{categories.Order[1], categories.Order[0], "asd"})
require.Error(t, err)
})
}
func setupUserForSubtest(t *testing.T, th *TestHelper) (*model.User, *model.Client4) {
password := "password"
user, err := th.App.CreateUser(th.Context, &model.User{
user, appErr := th.App.CreateUser(th.Context, &model.User{
Email: th.GenerateTestEmail(),
Username: "user_" + model.NewId(),
Password: password,
})
require.Nil(t, err)
require.Nil(t, appErr)
th.LinkUserToTeam(user, th.BasicTeam)
th.AddUserToChannel(user, th.BasicChannel)
@ -451,8 +451,8 @@ func setupUserForSubtest(t *testing.T, th *TestHelper) (*model.User, *model.Clie
th.AddUserToChannel(user, th.BasicPrivateChannel)
client := th.CreateClient()
user, resp := client.Login(user.Email, password)
require.Nil(t, resp.Error)
user, _, err := client.Login(user.Email, password)
require.NoError(t, err)
return user, client
}

File diff suppressed because it is too large Load diff

View file

@ -16,13 +16,14 @@ func TestGetClusterStatus(t *testing.T) {
defer th.TearDown()
t.Run("as system user", func(t *testing.T) {
_, resp := th.Client.GetClusterStatus()
_, resp, err := th.Client.GetClusterStatus()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("as system admin", func(t *testing.T) {
infos, resp := th.SystemAdminClient.GetClusterStatus()
CheckNoError(t, resp)
infos, _, err := th.SystemAdminClient.GetClusterStatus()
require.NoError(t, err)
require.NotNil(t, infos, "cluster status should not be nil")
})
@ -30,7 +31,8 @@ func TestGetClusterStatus(t *testing.T) {
t.Run("as restricted system admin", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
_, resp := th.SystemAdminClient.GetClusterStatus()
_, resp, err := th.SystemAdminClient.GetClusterStatus()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
}

View file

@ -15,7 +15,7 @@ func TestHelpCommand(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
channel := th.BasicChannel
HelpLink := *th.App.Config().SupportSettings.HelpLink
@ -24,12 +24,12 @@ func TestHelpCommand(t *testing.T) {
}()
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.SupportSettings.HelpLink = "" })
rs1, _ := Client.ExecuteCommand(channel.Id, "/help ")
rs1, _, _ := client.ExecuteCommand(channel.Id, "/help ")
assert.Equal(t, rs1.GotoLocation, model.SupportSettingsDefaultHelpLink, "failed to default help link")
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.SupportSettings.HelpLink = "https://docs.mattermost.com/guides/user.html"
})
rs2, _ := Client.ExecuteCommand(channel.Id, "/help ")
rs2, _, _ := client.ExecuteCommand(channel.Id, "/help ")
assert.Equal(t, rs2.GotoLocation, "https://docs.mattermost.com/guides/user.html", "failed to help link")
}

View file

@ -21,7 +21,7 @@ import (
func TestCreateCommand(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
LocalClient := th.LocalClient
enableCommands := *th.App.Config().ServiceSettings.EnableCommands
@ -37,43 +37,47 @@ func TestCreateCommand(t *testing.T) {
Method: model.CommandMethodPost,
Trigger: "trigger"}
_, resp := Client.CreateCommand(newCmd)
_, resp, err := client.CreateCommand(newCmd)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
createdCmd, resp := th.SystemAdminClient.CreateCommand(newCmd)
CheckNoError(t, resp)
createdCmd, resp, err := th.SystemAdminClient.CreateCommand(newCmd)
require.NoError(t, err)
CheckCreatedStatus(t, resp)
require.Equal(t, th.SystemAdminUser.Id, createdCmd.CreatorId, "user ids didn't match")
require.Equal(t, th.BasicTeam.Id, createdCmd.TeamId, "team ids didn't match")
_, resp = th.SystemAdminClient.CreateCommand(newCmd)
_, resp, err = th.SystemAdminClient.CreateCommand(newCmd)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
CheckErrorMessage(t, resp, "api.command.duplicate_trigger.app_error")
CheckErrorID(t, err, "api.command.duplicate_trigger.app_error")
newCmd.Trigger = "Local"
localCreatedCmd, resp := LocalClient.CreateCommand(newCmd)
CheckNoError(t, resp)
localCreatedCmd, resp, err := LocalClient.CreateCommand(newCmd)
require.NoError(t, err)
CheckCreatedStatus(t, resp)
require.Equal(t, th.BasicUser.Id, localCreatedCmd.CreatorId, "local client: user ids didn't match")
require.Equal(t, th.BasicTeam.Id, localCreatedCmd.TeamId, "local client: team ids didn't match")
newCmd.Method = "Wrong"
newCmd.Trigger = "testcommand"
_, resp = th.SystemAdminClient.CreateCommand(newCmd)
_, resp, err = th.SystemAdminClient.CreateCommand(newCmd)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
CheckErrorMessage(t, resp, "model.command.is_valid.method.app_error")
CheckErrorID(t, err, "model.command.is_valid.method.app_error")
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCommands = false })
newCmd.Method = "P"
newCmd.Trigger = "testcommand"
_, resp = th.SystemAdminClient.CreateCommand(newCmd)
_, resp, err = th.SystemAdminClient.CreateCommand(newCmd)
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
CheckErrorMessage(t, resp, "api.command.disabled.app_error")
CheckErrorID(t, err, "api.command.disabled.app_error")
// Confirm that local clients can't override disable command setting
newCmd.Trigger = "LocalOverride"
_, resp = LocalClient.CreateCommand(newCmd)
CheckErrorMessage(t, resp, "api.command.disabled.app_error")
_, _, err = LocalClient.CreateCommand(newCmd)
CheckErrorID(t, err, "api.command.disabled.app_error")
}
func TestUpdateCommand(t *testing.T) {
@ -109,8 +113,8 @@ func TestUpdateCommand(t *testing.T) {
}
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
rcmd, resp := client.UpdateCommand(cmd2)
CheckNoError(t, resp)
rcmd, _, err := client.UpdateCommand(cmd2)
require.NoError(t, err)
require.Equal(t, cmd2.Trigger, rcmd.Trigger, "Trigger should have updated")
@ -124,29 +128,34 @@ func TestUpdateCommand(t *testing.T) {
cmd2.Id = GenerateTestId()
rcmd, resp = client.UpdateCommand(cmd2)
rcmd, resp, err := client.UpdateCommand(cmd2)
require.Error(t, err)
CheckNotFoundStatus(t, resp)
require.Nil(t, rcmd, "should be empty")
cmd2.Id = "junk"
_, resp = client.UpdateCommand(cmd2)
_, resp, err = client.UpdateCommand(cmd2)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
cmd2.Id = cmd1.Id
cmd2.TeamId = GenerateTestId()
_, resp = client.UpdateCommand(cmd2)
_, resp, err = client.UpdateCommand(cmd2)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
cmd2.TeamId = team.Id
_, resp = th.Client.UpdateCommand(cmd2)
_, resp, err = th.Client.UpdateCommand(cmd2)
require.Error(t, err)
CheckNotFoundStatus(t, resp)
})
th.SystemAdminClient.Logout()
_, resp := th.SystemAdminClient.UpdateCommand(cmd2)
_, resp, err := th.SystemAdminClient.UpdateCommand(cmd2)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
}
@ -173,22 +182,20 @@ func TestMoveCommand(t *testing.T) {
rcmd1, _ := th.App.CreateCommand(cmd1)
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
ok, resp := client.MoveCommand(newTeam.Id, rcmd1.Id)
CheckNoError(t, resp)
require.True(t, ok)
_, err := client.MoveCommand(newTeam.Id, rcmd1.Id)
require.NoError(t, err)
rcmd1, _ = th.App.GetCommand(rcmd1.Id)
require.NotNil(t, rcmd1)
require.Equal(t, newTeam.Id, rcmd1.TeamId)
ok, resp = client.MoveCommand(newTeam.Id, "bogus")
resp, err := client.MoveCommand(newTeam.Id, "bogus")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
require.False(t, ok)
ok, resp = client.MoveCommand(GenerateTestId(), rcmd1.Id)
resp, err = client.MoveCommand(GenerateTestId(), rcmd1.Id)
require.Error(t, err)
CheckNotFoundStatus(t, resp)
require.False(t, ok)
})
cmd2 := &model.Command{
CreatorId: user.Id,
@ -200,11 +207,13 @@ func TestMoveCommand(t *testing.T) {
rcmd2, _ := th.App.CreateCommand(cmd2)
_, resp := th.Client.MoveCommand(newTeam.Id, rcmd2.Id)
resp, err := th.Client.MoveCommand(newTeam.Id, rcmd2.Id)
require.Error(t, err)
CheckNotFoundStatus(t, resp)
th.SystemAdminClient.Logout()
_, resp = th.SystemAdminClient.MoveCommand(newTeam.Id, rcmd2.Id)
resp, err = th.SystemAdminClient.MoveCommand(newTeam.Id, rcmd2.Id)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
}
@ -230,22 +239,20 @@ func TestDeleteCommand(t *testing.T) {
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
cmd1.Id = ""
rcmd1, err := th.App.CreateCommand(cmd1)
require.Nil(t, err)
ok, resp := client.DeleteCommand(rcmd1.Id)
CheckNoError(t, resp)
require.True(t, ok)
rcmd1, appErr := th.App.CreateCommand(cmd1)
require.Nil(t, appErr)
_, err := client.DeleteCommand(rcmd1.Id)
require.NoError(t, err)
rcmd1, _ = th.App.GetCommand(rcmd1.Id)
require.Nil(t, rcmd1)
ok, resp = client.DeleteCommand("junk")
resp, err := client.DeleteCommand("junk")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
require.False(t, ok)
_, resp = client.DeleteCommand(GenerateTestId())
resp, err = client.DeleteCommand(GenerateTestId())
require.Error(t, err)
CheckNotFoundStatus(t, resp)
})
cmd2 := &model.Command{
@ -258,18 +265,20 @@ func TestDeleteCommand(t *testing.T) {
rcmd2, _ := th.App.CreateCommand(cmd2)
_, resp := th.Client.DeleteCommand(rcmd2.Id)
resp, err := th.Client.DeleteCommand(rcmd2.Id)
require.Error(t, err)
CheckNotFoundStatus(t, resp)
th.SystemAdminClient.Logout()
_, resp = th.SystemAdminClient.DeleteCommand(rcmd2.Id)
resp, err = th.SystemAdminClient.DeleteCommand(rcmd2.Id)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
}
func TestListCommands(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
enableCommands := *th.App.Config().ServiceSettings.EnableCommands
defer func() {
@ -284,12 +293,12 @@ func TestListCommands(t *testing.T) {
Method: model.CommandMethodPost,
Trigger: "custom_command"}
_, resp := th.SystemAdminClient.CreateCommand(newCmd)
CheckNoError(t, resp)
_, _, err := th.SystemAdminClient.CreateCommand(newCmd)
require.NoError(t, err)
th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) {
listCommands, resp := c.ListCommands(th.BasicTeam.Id, false)
CheckNoError(t, resp)
listCommands, _, err := c.ListCommands(th.BasicTeam.Id, false)
require.NoError(t, err)
foundEcho := false
foundCustom := false
@ -306,21 +315,22 @@ func TestListCommands(t *testing.T) {
}, "ListSystemAndCustomCommands")
th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) {
listCommands, resp := c.ListCommands(th.BasicTeam.Id, true)
CheckNoError(t, resp)
listCommands, _, err := c.ListCommands(th.BasicTeam.Id, true)
require.NoError(t, err)
require.Len(t, listCommands, 1, "Should list just one custom command")
require.Equal(t, listCommands[0].Trigger, "custom_command", "Wrong custom command trigger")
}, "ListCustomOnlyCommands")
t.Run("UserWithNoPermissionForCustomCommands", func(t *testing.T) {
_, resp := Client.ListCommands(th.BasicTeam.Id, true)
_, resp, err := client.ListCommands(th.BasicTeam.Id, true)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("RegularUserCanListOnlySystemCommands", func(t *testing.T) {
listCommands, resp := Client.ListCommands(th.BasicTeam.Id, false)
CheckNoError(t, resp)
listCommands, _, err := client.ListCommands(th.BasicTeam.Id, false)
require.NoError(t, err)
foundEcho := false
foundCustom := false
@ -337,21 +347,25 @@ func TestListCommands(t *testing.T) {
})
t.Run("NoMember", func(t *testing.T) {
Client.Logout()
client.Logout()
user := th.CreateUser()
th.SystemAdminClient.RemoveTeamMember(th.BasicTeam.Id, user.Id)
Client.Login(user.Email, user.Password)
_, resp := Client.ListCommands(th.BasicTeam.Id, false)
client.Login(user.Email, user.Password)
_, resp, err := client.ListCommands(th.BasicTeam.Id, false)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
_, resp = Client.ListCommands(th.BasicTeam.Id, true)
_, resp, err = client.ListCommands(th.BasicTeam.Id, true)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("NotLoggedIn", func(t *testing.T) {
Client.Logout()
_, resp := Client.ListCommands(th.BasicTeam.Id, false)
client.Logout()
_, resp, err := client.ListCommands(th.BasicTeam.Id, false)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
_, resp = Client.ListCommands(th.BasicTeam.Id, true)
_, resp, err = client.ListCommands(th.BasicTeam.Id, true)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
})
}
@ -359,7 +373,7 @@ func TestListCommands(t *testing.T) {
func TestListAutocompleteCommands(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
newCmd := &model.Command{
CreatorId: th.BasicUser.Id,
@ -368,12 +382,12 @@ func TestListAutocompleteCommands(t *testing.T) {
Method: model.CommandMethodPost,
Trigger: "custom_command"}
_, resp := th.SystemAdminClient.CreateCommand(newCmd)
CheckNoError(t, resp)
_, _, err := th.SystemAdminClient.CreateCommand(newCmd)
require.NoError(t, err)
t.Run("ListAutocompleteCommandsOnly", func(t *testing.T) {
listCommands, resp := th.SystemAdminClient.ListAutocompleteCommands(th.BasicTeam.Id)
CheckNoError(t, resp)
listCommands, _, err := th.SystemAdminClient.ListAutocompleteCommands(th.BasicTeam.Id)
require.NoError(t, err)
foundEcho := false
foundCustom := false
@ -390,8 +404,8 @@ func TestListAutocompleteCommands(t *testing.T) {
})
t.Run("RegularUserCanListOnlySystemCommands", func(t *testing.T) {
listCommands, resp := Client.ListAutocompleteCommands(th.BasicTeam.Id)
CheckNoError(t, resp)
listCommands, _, err := client.ListAutocompleteCommands(th.BasicTeam.Id)
require.NoError(t, err)
foundEcho := false
foundCustom := false
@ -408,17 +422,19 @@ func TestListAutocompleteCommands(t *testing.T) {
})
t.Run("NoMember", func(t *testing.T) {
Client.Logout()
client.Logout()
user := th.CreateUser()
th.SystemAdminClient.RemoveTeamMember(th.BasicTeam.Id, user.Id)
Client.Login(user.Email, user.Password)
_, resp := Client.ListAutocompleteCommands(th.BasicTeam.Id)
client.Login(user.Email, user.Password)
_, resp, err := client.ListAutocompleteCommands(th.BasicTeam.Id)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("NotLoggedIn", func(t *testing.T) {
Client.Logout()
_, resp := Client.ListAutocompleteCommands(th.BasicTeam.Id)
client.Logout()
_, resp, err := client.ListAutocompleteCommands(th.BasicTeam.Id)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
})
}
@ -426,7 +442,7 @@ func TestListAutocompleteCommands(t *testing.T) {
func TestListCommandAutocompleteSuggestions(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
newCmd := &model.Command{
CreatorId: th.BasicUser.Id,
@ -435,12 +451,12 @@ func TestListCommandAutocompleteSuggestions(t *testing.T) {
Method: model.CommandMethodPost,
Trigger: "custom_command"}
_, resp := th.SystemAdminClient.CreateCommand(newCmd)
CheckNoError(t, resp)
_, _, err := th.SystemAdminClient.CreateCommand(newCmd)
require.NoError(t, err)
t.Run("ListAutocompleteSuggestionsOnly", func(t *testing.T) {
suggestions, resp := th.SystemAdminClient.ListCommandAutocompleteSuggestions("/", th.BasicTeam.Id)
CheckNoError(t, resp)
suggestions, _, err := th.SystemAdminClient.ListCommandAutocompleteSuggestions("/", th.BasicTeam.Id)
require.NoError(t, err)
foundEcho := false
foundShrug := false
@ -462,8 +478,8 @@ func TestListCommandAutocompleteSuggestions(t *testing.T) {
})
t.Run("ListAutocompleteSuggestionsOnlyWithInput", func(t *testing.T) {
suggestions, resp := th.SystemAdminClient.ListCommandAutocompleteSuggestions("/e", th.BasicTeam.Id)
CheckNoError(t, resp)
suggestions, _, err := th.SystemAdminClient.ListCommandAutocompleteSuggestions("/e", th.BasicTeam.Id)
require.NoError(t, err)
foundEcho := false
foundShrug := false
@ -480,8 +496,8 @@ func TestListCommandAutocompleteSuggestions(t *testing.T) {
})
t.Run("RegularUserCanListOnlySystemCommands", func(t *testing.T) {
suggestions, resp := Client.ListCommandAutocompleteSuggestions("/", th.BasicTeam.Id)
CheckNoError(t, resp)
suggestions, _, err := client.ListCommandAutocompleteSuggestions("/", th.BasicTeam.Id)
require.NoError(t, err)
foundEcho := false
foundCustom := false
@ -498,17 +514,19 @@ func TestListCommandAutocompleteSuggestions(t *testing.T) {
})
t.Run("NoMember", func(t *testing.T) {
Client.Logout()
client.Logout()
user := th.CreateUser()
th.SystemAdminClient.RemoveTeamMember(th.BasicTeam.Id, user.Id)
Client.Login(user.Email, user.Password)
_, resp := Client.ListCommandAutocompleteSuggestions("/", th.BasicTeam.Id)
client.Login(user.Email, user.Password)
_, resp, err := client.ListCommandAutocompleteSuggestions("/", th.BasicTeam.Id)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("NotLoggedIn", func(t *testing.T) {
Client.Logout()
_, resp := Client.ListCommandAutocompleteSuggestions("/", th.BasicTeam.Id)
client.Logout()
_, resp, err := client.ListCommandAutocompleteSuggestions("/", th.BasicTeam.Id)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
})
}
@ -530,13 +548,13 @@ func TestGetCommand(t *testing.T) {
Method: model.CommandMethodPost,
Trigger: "roger"}
newCmd, resp := th.SystemAdminClient.CreateCommand(newCmd)
CheckNoError(t, resp)
newCmd, _, err := th.SystemAdminClient.CreateCommand(newCmd)
require.NoError(t, err)
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
t.Run("ValidId", func(t *testing.T) {
cmd, resp := client.GetCommandById(newCmd.Id)
CheckNoError(t, resp)
cmd, _, err := client.GetCommandById(newCmd.Id)
require.NoError(t, err)
require.Equal(t, newCmd.Id, cmd.Id)
require.Equal(t, newCmd.CreatorId, cmd.CreatorId)
@ -547,12 +565,13 @@ func TestGetCommand(t *testing.T) {
})
t.Run("InvalidId", func(t *testing.T) {
_, resp := client.GetCommandById(strings.Repeat("z", len(newCmd.Id)))
require.NotNil(t, resp.Error)
_, _, err := client.GetCommandById(strings.Repeat("z", len(newCmd.Id)))
require.Error(t, err)
})
})
t.Run("UserWithNoPermissionForCustomCommands", func(t *testing.T) {
_, resp := th.Client.GetCommandById(newCmd.Id)
_, resp, err := th.Client.GetCommandById(newCmd.Id)
require.Error(t, err)
CheckNotFoundStatus(t, resp)
})
@ -561,13 +580,15 @@ func TestGetCommand(t *testing.T) {
user := th.CreateUser()
th.SystemAdminClient.RemoveTeamMember(th.BasicTeam.Id, user.Id)
th.Client.Login(user.Email, user.Password)
_, resp := th.Client.GetCommandById(newCmd.Id)
_, resp, err := th.Client.GetCommandById(newCmd.Id)
require.Error(t, err)
CheckNotFoundStatus(t, resp)
})
t.Run("NotLoggedIn", func(t *testing.T) {
th.Client.Logout()
_, resp := th.Client.GetCommandById(newCmd.Id)
_, resp, err := th.Client.GetCommandById(newCmd.Id)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
})
}
@ -575,7 +596,7 @@ func TestGetCommand(t *testing.T) {
func TestRegenToken(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
enableCommands := *th.App.Config().ServiceSettings.EnableCommands
defer func() {
@ -590,15 +611,16 @@ func TestRegenToken(t *testing.T) {
Method: model.CommandMethodPost,
Trigger: "trigger"}
createdCmd, resp := th.SystemAdminClient.CreateCommand(newCmd)
CheckNoError(t, resp)
createdCmd, resp, err := th.SystemAdminClient.CreateCommand(newCmd)
require.NoError(t, err)
CheckCreatedStatus(t, resp)
token, resp := th.SystemAdminClient.RegenCommandToken(createdCmd.Id)
CheckNoError(t, resp)
token, _, err := th.SystemAdminClient.RegenCommandToken(createdCmd.Id)
require.NoError(t, err)
require.NotEqual(t, createdCmd.Token, token, "should update the token")
token, resp = Client.RegenCommandToken(createdCmd.Id)
token, resp, err = client.RegenCommandToken(createdCmd.Id)
require.Error(t, err)
CheckNotFoundStatus(t, resp)
require.Empty(t, token, "should not return the token")
}
@ -606,7 +628,7 @@ func TestRegenToken(t *testing.T) {
func TestExecuteInvalidCommand(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
channel := th.BasicChannel
enableCommands := *th.App.Config().ServiceSettings.EnableCommands
@ -637,40 +659,46 @@ func TestExecuteInvalidCommand(t *testing.T) {
Trigger: "getcommand",
}
_, err := th.App.CreateCommand(getCmd)
require.Nil(t, err, "failed to create get command")
_, appErr := th.App.CreateCommand(getCmd)
require.Nil(t, appErr, "failed to create get command")
_, resp := Client.ExecuteCommand(channel.Id, "")
_, resp, err := client.ExecuteCommand(channel.Id, "")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = Client.ExecuteCommand(channel.Id, "/")
_, resp, err = client.ExecuteCommand(channel.Id, "/")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = Client.ExecuteCommand(channel.Id, "getcommand")
_, resp, err = client.ExecuteCommand(channel.Id, "getcommand")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = Client.ExecuteCommand(channel.Id, "/junk")
_, resp, err = client.ExecuteCommand(channel.Id, "/junk")
require.Error(t, err)
CheckNotFoundStatus(t, resp)
otherUser := th.CreateUser()
Client.Login(otherUser.Email, otherUser.Password)
client.Login(otherUser.Email, otherUser.Password)
_, resp = Client.ExecuteCommand(channel.Id, "/getcommand")
_, resp, err = client.ExecuteCommand(channel.Id, "/getcommand")
require.Error(t, err)
CheckForbiddenStatus(t, resp)
Client.Logout()
client.Logout()
_, resp = Client.ExecuteCommand(channel.Id, "/getcommand")
_, resp, err = client.ExecuteCommand(channel.Id, "/getcommand")
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
_, resp = th.SystemAdminClient.ExecuteCommand(channel.Id, "/getcommand")
CheckNoError(t, resp)
_, _, err = th.SystemAdminClient.ExecuteCommand(channel.Id, "/getcommand")
require.NoError(t, err)
}
func TestExecuteGetCommand(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
channel := th.BasicChannel
enableCommands := *th.App.Config().ServiceSettings.EnableCommands
@ -718,11 +746,11 @@ func TestExecuteGetCommand(t *testing.T) {
Token: token,
}
_, err := th.App.CreateCommand(getCmd)
require.Nil(t, err, "failed to create get command")
_, appErr := th.App.CreateCommand(getCmd)
require.Nil(t, appErr, "failed to create get command")
commandResponse, resp := Client.ExecuteCommand(channel.Id, "/getcommand")
CheckNoError(t, resp)
commandResponse, _, err := client.ExecuteCommand(channel.Id, "/getcommand")
require.NoError(t, err)
assert.True(t, len(commandResponse.TriggerId) == 26)
expectedCommandResponse.TriggerId = commandResponse.TriggerId
@ -732,7 +760,7 @@ func TestExecuteGetCommand(t *testing.T) {
func TestExecutePostCommand(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
channel := th.BasicChannel
enableCommands := *th.App.Config().ServiceSettings.EnableCommands
@ -778,11 +806,11 @@ func TestExecutePostCommand(t *testing.T) {
Token: token,
}
_, err := th.App.CreateCommand(postCmd)
require.Nil(t, err, "failed to create get command")
_, appErr := th.App.CreateCommand(postCmd)
require.Nil(t, appErr, "failed to create get command")
commandResponse, resp := Client.ExecuteCommand(channel.Id, "/postcommand")
CheckNoError(t, resp)
commandResponse, _, err := client.ExecuteCommand(channel.Id, "/postcommand")
require.NoError(t, err)
assert.True(t, len(commandResponse.TriggerId) == 26)
expectedCommandResponse.TriggerId = commandResponse.TriggerId
@ -792,7 +820,7 @@ func TestExecutePostCommand(t *testing.T) {
func TestExecuteCommandAgainstChannelOnAnotherTeam(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
channel := th.BasicChannel
enableCommands := *th.App.Config().ServiceSettings.EnableCommands
@ -832,12 +860,13 @@ func TestExecuteCommandAgainstChannelOnAnotherTeam(t *testing.T) {
Method: model.CommandMethodPost,
Trigger: "postcommand",
}
_, err := th.App.CreateCommand(postCmd)
require.Nil(t, err, "failed to create post command")
_, appErr := th.App.CreateCommand(postCmd)
require.Nil(t, appErr, "failed to create post command")
// the execute command endpoint will always search for the command by trigger and team id, inferring team id from the
// channel id, so there is no way to use that slash command on a channel that belongs to some other team
_, resp := Client.ExecuteCommand(channel.Id, "/postcommand")
_, resp, err := client.ExecuteCommand(channel.Id, "/postcommand")
require.Error(t, err)
CheckNotFoundStatus(t, resp)
}
@ -883,16 +912,17 @@ func TestExecuteCommandAgainstChannelUserIsNotIn(t *testing.T) {
Method: model.CommandMethodPost,
Trigger: "postcommand",
}
_, err := th.App.CreateCommand(postCmd)
require.Nil(t, err, "failed to create post command")
_, appErr := th.App.CreateCommand(postCmd)
require.Nil(t, appErr, "failed to create post command")
// make a channel on that team, ensuring that our test user isn't in it
channel2 := th.CreateChannelWithClientAndTeam(client, model.ChannelTypeOpen, team2.Id)
success, _ := client.RemoveUserFromChannel(channel2.Id, th.BasicUser.Id)
require.True(t, success, "Failed to remove user from channel")
_, err := th.Client.RemoveUserFromChannel(channel2.Id, th.BasicUser.Id)
require.NoError(t, err, "Failed to remove user from channel")
// we should not be able to run the slash command in channel2, because we aren't in it
_, resp := client.ExecuteCommandWithTeam(channel2.Id, team2.Id, "/postcommand")
_, resp, err := client.ExecuteCommandWithTeam(channel2.Id, team2.Id, "/postcommand")
require.Error(t, err)
CheckForbiddenStatus(t, resp)
}
@ -941,19 +971,22 @@ func TestExecuteCommandInDirectMessageChannel(t *testing.T) {
Method: model.CommandMethodPost,
Trigger: "postcommand",
}
_, err := th.App.CreateCommand(postCmd)
require.Nil(t, err, "failed to create post command")
_, appErr := th.App.CreateCommand(postCmd)
require.Nil(t, appErr, "failed to create post command")
// make a direct message channel
dmChannel, response := client.CreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id)
dmChannel, response, err := client.CreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id)
require.NoError(t, err)
CheckCreatedStatus(t, response)
// we should be able to run the slash command in the DM channel
_, resp := client.ExecuteCommandWithTeam(dmChannel.Id, team2.Id, "/postcommand")
_, resp, err := client.ExecuteCommandWithTeam(dmChannel.Id, team2.Id, "/postcommand")
require.NoError(t, err)
CheckOKStatus(t, resp)
// but we can't run the slash command in the DM channel if we sub in some other team's id
_, resp = client.ExecuteCommandWithTeam(dmChannel.Id, th.BasicTeam.Id, "/postcommand")
_, resp, err = client.ExecuteCommandWithTeam(dmChannel.Id, th.BasicTeam.Id, "/postcommand")
require.Error(t, err)
CheckNotFoundStatus(t, resp)
}
@ -1005,26 +1038,30 @@ func TestExecuteCommandInTeamUserIsNotOn(t *testing.T) {
Method: model.CommandMethodPost,
Trigger: "postcommand",
}
_, err := th.App.CreateCommand(postCmd)
require.Nil(t, err, "failed to create post command")
_, appErr := th.App.CreateCommand(postCmd)
require.Nil(t, appErr, "failed to create post command")
// make a direct message channel
dmChannel, response := client.CreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id)
dmChannel, response, err := client.CreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id)
require.NoError(t, err)
CheckCreatedStatus(t, response)
// we should be able to run the slash command in the DM channel
_, resp := client.ExecuteCommandWithTeam(dmChannel.Id, team2.Id, "/postcommand")
_, resp, err := client.ExecuteCommandWithTeam(dmChannel.Id, team2.Id, "/postcommand")
require.NoError(t, err)
CheckOKStatus(t, resp)
// if the user is removed from the team, they should NOT be able to run the slash command in the DM channel
success, _ := client.RemoveTeamMember(team2.Id, th.BasicUser.Id)
require.True(t, success, "Failed to remove user from team")
_, err = th.Client.RemoveTeamMember(team2.Id, th.BasicUser.Id)
require.NoError(t, err, "Failed to remove user from team")
_, resp = client.ExecuteCommandWithTeam(dmChannel.Id, team2.Id, "/postcommand")
_, resp, err = client.ExecuteCommandWithTeam(dmChannel.Id, team2.Id, "/postcommand")
require.Error(t, err)
CheckForbiddenStatus(t, resp)
// if we omit the team id from the request, the slash command will fail because this is a DM channel, and the
// team id can't be inherited from the channel
_, resp = client.ExecuteCommand(dmChannel.Id, "/postcommand")
_, resp, err = client.ExecuteCommand(dmChannel.Id, "/postcommand")
require.Error(t, err)
CheckForbiddenStatus(t, resp)
}

View file

@ -18,20 +18,23 @@ func TestEchoCommand(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
channel1 := th.BasicChannel
echoTestString := "/echo test"
r1 := Client.Must(Client.ExecuteCommand(channel1.Id, echoTestString)).(*model.CommandResponse)
r1, _, err := client.ExecuteCommand(channel1.Id, echoTestString)
require.NoError(t, err)
require.NotNil(t, r1, "Echo command failed to execute")
r1 = Client.Must(Client.ExecuteCommand(channel1.Id, "/echo ")).(*model.CommandResponse)
r1, _, err = client.ExecuteCommand(channel1.Id, "/echo ")
require.NoError(t, err)
require.NotNil(t, r1, "Echo command failed to execute")
time.Sleep(100 * time.Millisecond)
p1 := Client.Must(Client.GetPostsForChannel(channel1.Id, 0, 2, "", false)).(*model.PostList)
p1, _, err := client.GetPostsForChannel(channel1.Id, 0, 2, "", false)
require.NoError(t, err)
require.Len(t, p1.Order, 2, "Echo command failed to send")
}
@ -39,7 +42,7 @@ func TestGroupmsgCommands(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
team := th.BasicTeam
user1 := th.BasicUser
user2 := th.BasicUser2
@ -53,42 +56,53 @@ func TestGroupmsgCommands(t *testing.T) {
th.LinkUserToTeam(user3, team)
th.LinkUserToTeam(user4, team)
rs1 := Client.Must(Client.ExecuteCommand(th.BasicChannel.Id, "/groupmsg "+user2.Username+","+user3.Username)).(*model.CommandResponse)
rs1, _, err := client.ExecuteCommand(th.BasicChannel.Id, "/groupmsg "+user2.Username+","+user3.Username)
require.NoError(t, err)
group1 := model.GetGroupNameFromUserIds([]string{user1.Id, user2.Id, user3.Id})
require.True(t, strings.HasSuffix(rs1.GotoLocation, "/"+team.Name+"/channels/"+group1), "failed to create group channel")
rs2 := Client.Must(Client.ExecuteCommand(th.BasicChannel.Id, "/groupmsg "+user3.Username+","+user4.Username+" foobar")).(*model.CommandResponse)
rs2, _, err := client.ExecuteCommand(th.BasicChannel.Id, "/groupmsg "+user3.Username+","+user4.Username+" foobar")
require.NoError(t, err)
group2 := model.GetGroupNameFromUserIds([]string{user1.Id, user3.Id, user4.Id})
require.True(t, strings.HasSuffix(rs2.GotoLocation, "/"+team.Name+"/channels/"+group2), "failed to create second direct channel")
result := Client.Must(Client.SearchPosts(team.Id, "foobar", false)).(*model.PostList)
result, _, err := client.SearchPosts(team.Id, "foobar", false)
require.NoError(t, err)
require.NotEqual(t, 0, len(result.Order), "post did not get sent to direct message")
rs3 := Client.Must(Client.ExecuteCommand(th.BasicChannel.Id, "/groupmsg "+user2.Username+","+user3.Username)).(*model.CommandResponse)
rs3, _, err := client.ExecuteCommand(th.BasicChannel.Id, "/groupmsg "+user2.Username+","+user3.Username)
require.NoError(t, err)
require.True(t, strings.HasSuffix(rs3.GotoLocation, "/"+team.Name+"/channels/"+group1), "failed to go back to existing group channel")
Client.Must(Client.ExecuteCommand(th.BasicChannel.Id, "/groupmsg "+user2.Username+" foobar"))
Client.Must(Client.ExecuteCommand(th.BasicChannel.Id, "/groupmsg "+user2.Username+","+user3.Username+","+user4.Username+","+user5.Username+","+user6.Username+","+user7.Username+","+user8.Username+","+user9.Username+" foobar"))
Client.Must(Client.ExecuteCommand(th.BasicChannel.Id, "/groupmsg junk foobar"))
Client.Must(Client.ExecuteCommand(th.BasicChannel.Id, "/groupmsg junk,junk2 foobar"))
_, _, err = client.ExecuteCommand(th.BasicChannel.Id, "/groupmsg "+user2.Username+" foobar")
require.NoError(t, err)
_, _, err = client.ExecuteCommand(th.BasicChannel.Id, "/groupmsg "+user2.Username+","+user3.Username+","+user4.Username+","+user5.Username+","+user6.Username+","+user7.Username+","+user8.Username+","+user9.Username+" foobar")
require.NoError(t, err)
_, _, err = client.ExecuteCommand(th.BasicChannel.Id, "/groupmsg junk foobar")
require.NoError(t, err)
_, _, err = client.ExecuteCommand(th.BasicChannel.Id, "/groupmsg junk,junk2 foobar")
require.NoError(t, err)
}
func TestInvitePeopleCommand(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
channel := th.BasicChannel
r1 := Client.Must(Client.ExecuteCommand(channel.Id, "/invite_people test@example.com")).(*model.CommandResponse)
r1, _, err := client.ExecuteCommand(channel.Id, "/invite_people test@example.com")
require.NoError(t, err)
require.NotNil(t, r1, "Command failed to execute")
r2 := Client.Must(Client.ExecuteCommand(channel.Id, "/invite_people test1@example.com test2@example.com")).(*model.CommandResponse)
r2, _, err := client.ExecuteCommand(channel.Id, "/invite_people test1@example.com test2@example.com")
require.NoError(t, err)
require.NotNil(t, r2, "Command failed to execute")
r3 := Client.Must(Client.ExecuteCommand(channel.Id, "/invite_people")).(*model.CommandResponse)
r3, _, err := client.ExecuteCommand(channel.Id, "/invite_people")
require.NoError(t, err)
require.NotNil(t, r3, "Command failed to execute")
}
@ -97,30 +111,39 @@ func testJoinCommands(t *testing.T, alias string) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
team := th.BasicTeam
user2 := th.BasicUser2
channel0 := &model.Channel{DisplayName: "00", Name: "00" + model.NewId() + "a", Type: model.ChannelTypeOpen, TeamId: team.Id}
channel0 = Client.Must(Client.CreateChannel(channel0)).(*model.Channel)
channel0, _, err := client.CreateChannel(channel0)
require.NoError(t, err)
channel1 := &model.Channel{DisplayName: "AA", Name: "aa" + model.NewId() + "a", Type: model.ChannelTypeOpen, TeamId: team.Id}
channel1 = Client.Must(Client.CreateChannel(channel1)).(*model.Channel)
Client.Must(Client.RemoveUserFromChannel(channel1.Id, th.BasicUser.Id))
channel1, _, err = client.CreateChannel(channel1)
require.NoError(t, err)
_, err = client.RemoveUserFromChannel(channel1.Id, th.BasicUser.Id)
require.NoError(t, err)
channel2 := &model.Channel{DisplayName: "BB", Name: "bb" + model.NewId() + "a", Type: model.ChannelTypeOpen, TeamId: team.Id}
channel2 = Client.Must(Client.CreateChannel(channel2)).(*model.Channel)
Client.Must(Client.RemoveUserFromChannel(channel2.Id, th.BasicUser.Id))
channel2, _, err = client.CreateChannel(channel2)
require.NoError(t, err)
_, err = client.RemoveUserFromChannel(channel2.Id, th.BasicUser.Id)
require.NoError(t, err)
channel3 := Client.Must(Client.CreateDirectChannel(th.BasicUser.Id, user2.Id)).(*model.Channel)
channel3, _, err := client.CreateDirectChannel(th.BasicUser.Id, user2.Id)
require.NoError(t, err)
rs5 := Client.Must(Client.ExecuteCommand(channel0.Id, "/"+alias+" "+channel2.Name)).(*model.CommandResponse)
rs5, _, err := client.ExecuteCommand(channel0.Id, "/"+alias+" "+channel2.Name)
require.NoError(t, err)
require.True(t, strings.HasSuffix(rs5.GotoLocation, "/"+team.Name+"/channels/"+channel2.Name), "failed to join channel")
rs6 := Client.Must(Client.ExecuteCommand(channel0.Id, "/"+alias+" "+channel3.Name)).(*model.CommandResponse)
rs6, _, err := client.ExecuteCommand(channel0.Id, "/"+alias+" "+channel3.Name)
require.NoError(t, err)
require.False(t, strings.HasSuffix(rs6.GotoLocation, "/"+team.Name+"/channels/"+channel3.Name), "should not have joined direct message channel")
c1 := Client.Must(Client.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, false, "")).([]*model.Channel)
c1, _, err := client.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, false, "")
require.NoError(t, err)
found := false
for _, c := range c1 {
@ -132,9 +155,12 @@ func testJoinCommands(t *testing.T, alias string) {
// test case insensitively
channel4 := &model.Channel{DisplayName: "BB", Name: "bb" + model.NewId() + "a", Type: model.ChannelTypeOpen, TeamId: team.Id}
channel4 = Client.Must(Client.CreateChannel(channel4)).(*model.Channel)
Client.Must(Client.RemoveUserFromChannel(channel4.Id, th.BasicUser.Id))
rs7 := Client.Must(Client.ExecuteCommand(channel0.Id, "/"+alias+" "+strings.ToUpper(channel4.Name))).(*model.CommandResponse)
channel4, _, err = client.CreateChannel(channel4)
require.NoError(t, err)
_, err = client.RemoveUserFromChannel(channel4.Id, th.BasicUser.Id)
require.NoError(t, err)
rs7, _, err := client.ExecuteCommand(channel0.Id, "/"+alias+" "+strings.ToUpper(channel4.Name))
require.NoError(t, err)
require.True(t, strings.HasSuffix(rs7.GotoLocation, "/"+team.Name+"/channels/"+channel4.Name), "failed to join channel")
}
@ -146,7 +172,7 @@ func TestLoadTestHelpCommands(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
channel := th.BasicChannel
enableTesting := *th.App.Config().ServiceSettings.EnableTesting
@ -156,7 +182,8 @@ func TestLoadTestHelpCommands(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableTesting = true })
rs := Client.Must(Client.ExecuteCommand(channel.Id, "/test help")).(*model.CommandResponse)
rs, _, err := client.ExecuteCommand(channel.Id, "/test help")
require.NoError(t, err)
require.True(t, strings.Contains(rs.Text, "Mattermost testing commands to help"), rs.Text)
time.Sleep(2 * time.Second)
@ -166,7 +193,7 @@ func TestLoadTestSetupCommands(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
channel := th.BasicChannel
enableTesting := *th.App.Config().ServiceSettings.EnableTesting
@ -176,7 +203,8 @@ func TestLoadTestSetupCommands(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableTesting = true })
rs := Client.Must(Client.ExecuteCommand(channel.Id, "/test setup fuzz 1 1 1")).(*model.CommandResponse)
rs, _, err := client.ExecuteCommand(channel.Id, "/test setup fuzz 1 1 1")
require.NoError(t, err)
require.Equal(t, "Created environment", rs.Text, rs.Text)
time.Sleep(2 * time.Second)
@ -186,7 +214,7 @@ func TestLoadTestUsersCommands(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
channel := th.BasicChannel
enableTesting := *th.App.Config().ServiceSettings.EnableTesting
@ -196,7 +224,8 @@ func TestLoadTestUsersCommands(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableTesting = true })
rs := Client.Must(Client.ExecuteCommand(channel.Id, "/test users fuzz 1 2")).(*model.CommandResponse)
rs, _, err := client.ExecuteCommand(channel.Id, "/test users fuzz 1 2")
require.NoError(t, err)
require.Equal(t, "Added users", rs.Text, rs.Text)
time.Sleep(2 * time.Second)
@ -206,7 +235,7 @@ func TestLoadTestChannelsCommands(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
channel := th.BasicChannel
enableTesting := *th.App.Config().ServiceSettings.EnableTesting
@ -216,7 +245,8 @@ func TestLoadTestChannelsCommands(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableTesting = true })
rs := Client.Must(Client.ExecuteCommand(channel.Id, "/test channels fuzz 1 2")).(*model.CommandResponse)
rs, _, err := client.ExecuteCommand(channel.Id, "/test channels fuzz 1 2")
require.NoError(t, err)
require.Equal(t, "Added channels", rs.Text, rs.Text)
time.Sleep(2 * time.Second)
@ -226,7 +256,7 @@ func TestLoadTestPostsCommands(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
channel := th.BasicChannel
enableTesting := *th.App.Config().ServiceSettings.EnableTesting
@ -236,7 +266,8 @@ func TestLoadTestPostsCommands(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableTesting = true })
rs := Client.Must(Client.ExecuteCommand(channel.Id, "/test posts fuzz 2 3 2")).(*model.CommandResponse)
rs, _, err := client.ExecuteCommand(channel.Id, "/test posts fuzz 2 3 2")
require.NoError(t, err)
require.Equal(t, "Added posts", rs.Text, rs.Text)
time.Sleep(2 * time.Second)
@ -246,31 +277,40 @@ func TestLeaveCommands(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
team := th.BasicTeam
user2 := th.BasicUser2
channel1 := &model.Channel{DisplayName: "AA", Name: "aa" + model.NewId() + "a", Type: model.ChannelTypeOpen, TeamId: team.Id}
channel1 = Client.Must(Client.CreateChannel(channel1)).(*model.Channel)
Client.Must(Client.AddChannelMember(channel1.Id, th.BasicUser.Id))
channel1, _, err := client.CreateChannel(channel1)
require.NoError(t, err)
_, _, err = client.AddChannelMember(channel1.Id, th.BasicUser.Id)
require.NoError(t, err)
channel2 := &model.Channel{DisplayName: "BB", Name: "bb" + model.NewId() + "a", Type: model.ChannelTypePrivate, TeamId: team.Id}
channel2 = Client.Must(Client.CreateChannel(channel2)).(*model.Channel)
Client.Must(Client.AddChannelMember(channel2.Id, th.BasicUser.Id))
Client.Must(Client.AddChannelMember(channel2.Id, user2.Id))
channel2, _, err = client.CreateChannel(channel2)
require.NoError(t, err)
_, _, err = client.AddChannelMember(channel2.Id, th.BasicUser.Id)
require.NoError(t, err)
_, _, err = client.AddChannelMember(channel2.Id, user2.Id)
require.NoError(t, err)
channel3 := Client.Must(Client.CreateDirectChannel(th.BasicUser.Id, user2.Id)).(*model.Channel)
channel3, _, err := client.CreateDirectChannel(th.BasicUser.Id, user2.Id)
require.NoError(t, err)
rs1 := Client.Must(Client.ExecuteCommand(channel1.Id, "/leave")).(*model.CommandResponse)
rs1, _, err := client.ExecuteCommand(channel1.Id, "/leave")
require.NoError(t, err)
require.True(t, strings.HasSuffix(rs1.GotoLocation, "/"+team.Name+"/channels/"+model.DefaultChannelName), "failed to leave open channel 1")
rs2 := Client.Must(Client.ExecuteCommand(channel2.Id, "/leave")).(*model.CommandResponse)
rs2, _, err := client.ExecuteCommand(channel2.Id, "/leave")
require.NoError(t, err)
require.True(t, strings.HasSuffix(rs2.GotoLocation, "/"+team.Name+"/channels/"+model.DefaultChannelName), "failed to leave private channel 1")
_, err := Client.ExecuteCommand(channel3.Id, "/leave")
require.NotNil(t, err, "should fail leaving direct channel")
_, _, err = client.ExecuteCommand(channel3.Id, "/leave")
require.Error(t, err)
cdata := Client.Must(Client.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, false, "")).([]*model.Channel)
cdata, _, err := client.GetChannelsForTeamForUser(th.BasicTeam.Id, th.BasicUser.Id, false, "")
require.NoError(t, err)
found := false
for _, c := range cdata {
@ -282,8 +322,8 @@ func TestLeaveCommands(t *testing.T) {
for _, c := range cdata {
if c.Name == model.DefaultChannelName {
_, err := Client.RemoveUserFromChannel(c.Id, th.BasicUser.Id)
require.NotNil(t, err, "should have errored on leaving default channel")
_, err := client.RemoveUserFromChannel(c.Id, th.BasicUser.Id)
require.Error(t, err, "should have errored on leaving default channel")
break
}
}
@ -293,24 +333,27 @@ func TestLogoutTestCommand(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
th.Client.Must(th.Client.ExecuteCommand(th.BasicChannel.Id, "/logout"))
_, _, err := th.Client.ExecuteCommand(th.BasicChannel.Id, "/logout")
require.NoError(t, err)
}
func TestMeCommand(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
channel := th.BasicChannel
testString := "/me hello"
r1 := Client.Must(Client.ExecuteCommand(channel.Id, testString)).(*model.CommandResponse)
r1, _, err := client.ExecuteCommand(channel.Id, testString)
require.NoError(t, err)
require.NotNil(t, r1, "Command failed to execute")
time.Sleep(100 * time.Millisecond)
p1 := Client.Must(Client.GetPostsForChannel(channel.Id, 0, 2, "", false)).(*model.PostList)
p1, _, err := client.GetPostsForChannel(channel.Id, 0, 2, "", false)
require.NoError(t, err)
require.Len(t, p1.Order, 2, "Command failed to send")
pt := p1.Posts[p1.Order[0]].Type
@ -325,39 +368,47 @@ func TestMsgCommands(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
team := th.BasicTeam
user1 := th.BasicUser
user2 := th.BasicUser2
user3 := th.CreateUser()
th.LinkUserToTeam(user3, team)
Client.Must(Client.CreateDirectChannel(th.BasicUser.Id, user2.Id))
Client.Must(Client.CreateDirectChannel(th.BasicUser.Id, user3.Id))
_, _, err := client.CreateDirectChannel(th.BasicUser.Id, user2.Id)
require.NoError(t, err)
_, _, err = client.CreateDirectChannel(th.BasicUser.Id, user3.Id)
require.NoError(t, err)
rs1 := Client.Must(Client.ExecuteCommand(th.BasicChannel.Id, "/msg "+user2.Username)).(*model.CommandResponse)
rs1, _, err := client.ExecuteCommand(th.BasicChannel.Id, "/msg "+user2.Username)
require.NoError(t, err)
require.Condition(t, func() bool {
return strings.HasSuffix(rs1.GotoLocation, "/"+team.Name+"/channels/"+user1.Id+"__"+user2.Id) ||
strings.HasSuffix(rs1.GotoLocation, "/"+team.Name+"/channels/"+user2.Id+"__"+user1.Id)
}, "failed to create direct channel")
rs2 := Client.Must(Client.ExecuteCommand(th.BasicChannel.Id, "/msg "+user3.Username+" foobar")).(*model.CommandResponse)
rs2, _, err := client.ExecuteCommand(th.BasicChannel.Id, "/msg "+user3.Username+" foobar")
require.NoError(t, err)
require.Condition(t, func() bool {
return strings.HasSuffix(rs2.GotoLocation, "/"+team.Name+"/channels/"+user1.Id+"__"+user3.Id) ||
strings.HasSuffix(rs2.GotoLocation, "/"+team.Name+"/channels/"+user3.Id+"__"+user1.Id)
}, "failed to create second direct channel")
result := Client.Must(Client.SearchPosts(th.BasicTeam.Id, "foobar", false)).(*model.PostList)
result, _, err := client.SearchPosts(th.BasicTeam.Id, "foobar", false)
require.NoError(t, err)
require.NotEqual(t, 0, len(result.Order), "post did not get sent to direct message")
rs3 := Client.Must(Client.ExecuteCommand(th.BasicChannel.Id, "/msg "+user2.Username)).(*model.CommandResponse)
rs3, _, err := client.ExecuteCommand(th.BasicChannel.Id, "/msg "+user2.Username)
require.NoError(t, err)
require.Condition(t, func() bool {
return strings.HasSuffix(rs3.GotoLocation, "/"+team.Name+"/channels/"+user1.Id+"__"+user2.Id) ||
strings.HasSuffix(rs3.GotoLocation, "/"+team.Name+"/channels/"+user2.Id+"__"+user1.Id)
}, "failed to go back to existing direct channel")
Client.Must(Client.ExecuteCommand(th.BasicChannel.Id, "/msg "+th.BasicUser.Username+" foobar"))
Client.Must(Client.ExecuteCommand(th.BasicChannel.Id, "/msg junk foobar"))
_, _, err = client.ExecuteCommand(th.BasicChannel.Id, "/msg "+th.BasicUser.Username+" foobar")
require.NoError(t, err)
_, _, err = client.ExecuteCommand(th.BasicChannel.Id, "/msg junk foobar")
require.NoError(t, err)
}
func TestOpenCommands(t *testing.T) {
@ -368,38 +419,43 @@ func TestSearchCommand(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
th.Client.Must(th.Client.ExecuteCommand(th.BasicChannel.Id, "/search"))
_, _, err := th.Client.ExecuteCommand(th.BasicChannel.Id, "/search")
require.NoError(t, err)
}
func TestSettingsCommand(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
th.Client.Must(th.Client.ExecuteCommand(th.BasicChannel.Id, "/settings"))
_, _, err := th.Client.ExecuteCommand(th.BasicChannel.Id, "/settings")
require.NoError(t, err)
}
func TestShortcutsCommand(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
th.Client.Must(th.Client.ExecuteCommand(th.BasicChannel.Id, "/shortcuts"))
_, _, err := th.Client.ExecuteCommand(th.BasicChannel.Id, "/shortcuts")
require.NoError(t, err)
}
func TestShrugCommand(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
channel := th.BasicChannel
testString := "/shrug"
r1 := Client.Must(Client.ExecuteCommand(channel.Id, testString)).(*model.CommandResponse)
r1, _, err := client.ExecuteCommand(channel.Id, testString)
require.NoError(t, err)
require.NotNil(t, r1, "Command failed to execute")
time.Sleep(100 * time.Millisecond)
p1 := Client.Must(Client.GetPostsForChannel(channel.Id, 0, 2, "", false)).(*model.PostList)
p1, _, err := client.GetPostsForChannel(channel.Id, 0, 2, "", false)
require.NoError(t, err)
require.Len(t, p1.Order, 2, "Command failed to send")
require.Equal(t, `¯\\\_(ツ)\_/¯`, p1.Posts[p1.Order[0]].Message, "invalid shrug response")
}
@ -414,15 +470,17 @@ func TestStatusCommands(t *testing.T) {
}
func commandAndTest(t *testing.T, th *TestHelper, status string) {
Client := th.Client
client := th.Client
channel := th.BasicChannel
user := th.BasicUser
r1 := Client.Must(Client.ExecuteCommand(channel.Id, "/"+status)).(*model.CommandResponse)
r1, _, err := client.ExecuteCommand(channel.Id, "/"+status)
require.NoError(t, err)
require.NotEqual(t, "Command failed to execute", r1)
time.Sleep(1000 * time.Millisecond)
rstatus := Client.Must(Client.GetUserStatus(user.Id, "")).(*model.Status)
rstatus, _, err := client.GetUserStatus(user.Id, "")
require.NoError(t, err)
require.Equal(t, status, rstatus.Status, "Error setting status")
}

View file

@ -23,14 +23,15 @@ import (
func TestGetConfig(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
client := th.Client
_, resp := Client.GetConfig()
_, resp, err := client.GetConfig()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
cfg, resp := client.GetConfig()
CheckNoError(t, resp)
cfg, _, err := client.GetConfig()
require.NoError(t, err)
require.NotEqual(t, "", cfg.TeamSettings.SiteName)
@ -77,8 +78,8 @@ func TestGetConfigWithAccessTag(t *testing.T) {
th.AddPermissionToRole(model.PermissionSysconsoleReadEnvironmentRateLimiting.Id, model.SystemUserRoleId)
defer th.RemovePermissionFromRole(model.PermissionSysconsoleReadEnvironmentRateLimiting.Id, model.SystemUserRoleId)
cfg, resp := th.Client.GetConfig()
CheckNoError(t, resp)
cfg, _, err := th.Client.GetConfig()
require.NoError(t, err)
t.Run("Cannot read value without permission", func(t *testing.T) {
assert.Nil(t, cfg.SupportSettings.SupportEmail)
@ -98,7 +99,7 @@ func TestGetConfigAnyFlagsAccess(t *testing.T) {
defer th.TearDown()
th.Client.Login(th.BasicUser.Username, th.BasicUser.Password)
_, resp := th.Client.GetConfig()
_, resp, _ := th.Client.GetConfig()
t.Run("Check permissions error with no sysconsole read permission", func(t *testing.T) {
CheckForbiddenStatus(t, resp)
@ -108,8 +109,8 @@ func TestGetConfigAnyFlagsAccess(t *testing.T) {
th.AddPermissionToRole(model.PermissionSysconsoleReadEnvironmentRateLimiting.Id, model.SystemUserRoleId)
defer th.RemovePermissionFromRole(model.PermissionSysconsoleReadEnvironmentRateLimiting.Id, model.SystemUserRoleId)
cfg, resp := th.Client.GetConfig()
CheckNoError(t, resp)
cfg, _, err := th.Client.GetConfig()
require.NoError(t, err)
t.Run("Can read value with permission", func(t *testing.T) {
assert.NotNil(t, cfg.FeatureFlags)
})
@ -118,59 +119,59 @@ func TestGetConfigAnyFlagsAccess(t *testing.T) {
func TestReloadConfig(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
client := th.Client
t.Run("as system user", func(t *testing.T) {
ok, resp := Client.ReloadConfig()
resp, err := client.ReloadConfig()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
require.False(t, ok, "should not Reload the config due no permission.")
})
t.Run("as system admin", func(t *testing.T) {
ok, resp := th.SystemAdminClient.ReloadConfig()
CheckNoError(t, resp)
require.True(t, ok, "should Reload the config")
_, err := th.SystemAdminClient.ReloadConfig()
require.NoError(t, err)
})
t.Run("as restricted system admin", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
ok, resp := Client.ReloadConfig()
resp, err := client.ReloadConfig()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
require.False(t, ok, "should not Reload the config due no permission.")
})
}
func TestUpdateConfig(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
client := th.Client
cfg, resp := th.SystemAdminClient.GetConfig()
CheckNoError(t, resp)
cfg, _, err := th.SystemAdminClient.GetConfig()
require.NoError(t, err)
_, resp = Client.UpdateConfig(cfg)
_, resp, err := client.UpdateConfig(cfg)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
SiteName := th.App.Config().TeamSettings.SiteName
*cfg.TeamSettings.SiteName = "MyFancyName"
cfg, resp = client.UpdateConfig(cfg)
CheckNoError(t, resp)
cfg, _, err = client.UpdateConfig(cfg)
require.NoError(t, err)
require.Equal(t, "MyFancyName", *cfg.TeamSettings.SiteName, "It should update the SiteName")
//Revert the change
cfg.TeamSettings.SiteName = SiteName
cfg, resp = client.UpdateConfig(cfg)
CheckNoError(t, resp)
cfg, _, err = client.UpdateConfig(cfg)
require.NoError(t, err)
require.Equal(t, SiteName, cfg.TeamSettings.SiteName, "It should update the SiteName")
t.Run("Should set defaults for missing fields", func(t *testing.T) {
_, appErr := th.SystemAdminClient.DoApiPut(th.SystemAdminClient.GetConfigRoute(), "{}")
require.Nil(t, appErr)
_, err = th.SystemAdminClient.DoApiPut(th.SystemAdminClient.GetConfigRoute(), "{}")
require.NoError(t, err)
})
t.Run("Should fail with validation error if invalid config setting is passed", func(t *testing.T) {
@ -178,23 +179,24 @@ func TestUpdateConfig(t *testing.T) {
badcfg := cfg.Clone()
badcfg.PasswordSettings.MinimumLength = model.NewInt(4)
badcfg.PasswordSettings.MinimumLength = model.NewInt(4)
_, resp = client.UpdateConfig(badcfg)
_, resp, err = client.UpdateConfig(badcfg)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
CheckErrorMessage(t, resp, "model.config.is_valid.password_length.app_error")
CheckErrorID(t, err, "model.config.is_valid.password_length.app_error")
})
t.Run("Should not be able to modify PluginSettings.EnableUploads", func(t *testing.T) {
oldEnableUploads := *th.App.Config().PluginSettings.EnableUploads
*cfg.PluginSettings.EnableUploads = !oldEnableUploads
cfg, resp = client.UpdateConfig(cfg)
CheckNoError(t, resp)
cfg, _, err = client.UpdateConfig(cfg)
require.NoError(t, err)
assert.Equal(t, oldEnableUploads, *cfg.PluginSettings.EnableUploads)
assert.Equal(t, oldEnableUploads, *th.App.Config().PluginSettings.EnableUploads)
cfg.PluginSettings.EnableUploads = nil
cfg, resp = client.UpdateConfig(cfg)
CheckNoError(t, resp)
cfg, _, err = client.UpdateConfig(cfg)
require.NoError(t, err)
assert.Equal(t, oldEnableUploads, *cfg.PluginSettings.EnableUploads)
assert.Equal(t, oldEnableUploads, *th.App.Config().PluginSettings.EnableUploads)
})
@ -203,14 +205,14 @@ func TestUpdateConfig(t *testing.T) {
oldPublicKeys := th.App.Config().PluginSettings.SignaturePublicKeyFiles
cfg.PluginSettings.SignaturePublicKeyFiles = append(cfg.PluginSettings.SignaturePublicKeyFiles, "new_signature")
cfg, resp = client.UpdateConfig(cfg)
CheckNoError(t, resp)
cfg, _, err = client.UpdateConfig(cfg)
require.NoError(t, err)
assert.Equal(t, oldPublicKeys, cfg.PluginSettings.SignaturePublicKeyFiles)
assert.Equal(t, oldPublicKeys, th.App.Config().PluginSettings.SignaturePublicKeyFiles)
cfg.PluginSettings.SignaturePublicKeyFiles = nil
cfg, resp = client.UpdateConfig(cfg)
CheckNoError(t, resp)
cfg, _, err = client.UpdateConfig(cfg)
require.NoError(t, err)
assert.Equal(t, oldPublicKeys, cfg.PluginSettings.SignaturePublicKeyFiles)
assert.Equal(t, oldPublicKeys, th.App.Config().PluginSettings.SignaturePublicKeyFiles)
})
@ -224,18 +226,19 @@ func TestUpdateConfig(t *testing.T) {
cfg.ServiceSettings.SiteURL = &nonEmptyURL
// Set the SiteURL
cfg, resp = th.SystemAdminClient.UpdateConfig(cfg)
CheckNoError(t, resp)
cfg, _, err = th.SystemAdminClient.UpdateConfig(cfg)
require.NoError(t, err)
require.Equal(t, nonEmptyURL, *cfg.ServiceSettings.SiteURL)
// Check that the Site URL can't be cleared
cfg.ServiceSettings.SiteURL = sToP("")
cfg, resp = th.SystemAdminClient.UpdateConfig(cfg)
cfg, resp, err = th.SystemAdminClient.UpdateConfig(cfg)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
CheckErrorMessage(t, resp, "api.config.update_config.clear_siteurl.app_error")
CheckErrorID(t, err, "api.config.update_config.clear_siteurl.app_error")
// Check that the Site URL wasn't cleared
cfg, resp = th.SystemAdminClient.GetConfig()
CheckNoError(t, resp)
cfg, _, err = th.SystemAdminClient.GetConfig()
require.NoError(t, err)
require.Equal(t, nonEmptyURL, *cfg.ServiceSettings.SiteURL)
})
}
@ -247,15 +250,15 @@ func TestGetConfigWithoutManageSystemPermission(t *testing.T) {
t.Run("any sysconsole read permission provides config read access", func(t *testing.T) {
// forbidden by default
_, resp := th.Client.GetConfig()
_, resp, err := th.Client.GetConfig()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
// add any sysconsole read permission
th.AddPermissionToRole(model.SysconsoleReadPermissions[0].Id, model.SystemUserRoleId)
_, resp = th.Client.GetConfig()
_, _, err = th.Client.GetConfig()
// should be readable now
CheckNoError(t, resp)
require.NoError(t, err)
})
}
@ -270,18 +273,18 @@ func TestUpdateConfigWithoutManageSystemPermission(t *testing.T) {
t.Run("sysconsole read permission does not provides config write access", func(t *testing.T) {
// should be readable because has a sysconsole read permission
cfg, resp := th.Client.GetConfig()
CheckNoError(t, resp)
_, resp = th.Client.UpdateConfig(cfg)
cfg, _, err := th.Client.GetConfig()
require.NoError(t, err)
_, resp, err := th.Client.UpdateConfig(cfg)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("the wrong write permission does not grant access", func(t *testing.T) {
// should be readable because has a sysconsole read permission
cfg, resp := th.SystemAdminClient.GetConfig()
CheckNoError(t, resp)
cfg, _, err := th.SystemAdminClient.GetConfig()
require.NoError(t, err)
originalValue := *cfg.ServiceSettings.AllowCorsFrom
@ -292,19 +295,19 @@ func TestUpdateConfigWithoutManageSystemPermission(t *testing.T) {
// try update a config value allowed by sysconsole WRITE integrations
mockVal := model.NewId()
cfg.ServiceSettings.AllowCorsFrom = &mockVal
_, resp = th.Client.UpdateConfig(cfg)
CheckNoError(t, resp)
_, _, err = th.Client.UpdateConfig(cfg)
require.NoError(t, err)
// ensure the config setting was not updated
cfg, resp = th.SystemAdminClient.GetConfig()
CheckNoError(t, resp)
cfg, _, err = th.SystemAdminClient.GetConfig()
require.NoError(t, err)
assert.Equal(t, *cfg.ServiceSettings.AllowCorsFrom, originalValue)
})
t.Run("config value is writeable by specific system console permission", func(t *testing.T) {
// should be readable because has a sysconsole read permission
cfg, resp := th.SystemAdminClient.GetConfig()
CheckNoError(t, resp)
cfg, _, err := th.SystemAdminClient.GetConfig()
require.NoError(t, err)
th.AddPermissionToRole(model.PermissionSysconsoleWriteIntegrationsCors.Id, model.SystemUserRoleId)
defer th.RemovePermissionFromRole(model.PermissionSysconsoleWriteIntegrationsCors.Id, model.SystemUserRoleId)
@ -314,12 +317,12 @@ func TestUpdateConfigWithoutManageSystemPermission(t *testing.T) {
// try update a config value allowed by sysconsole WRITE integrations
mockVal := model.NewId()
cfg.ServiceSettings.AllowCorsFrom = &mockVal
_, resp = th.Client.UpdateConfig(cfg)
CheckNoError(t, resp)
_, _, err = th.Client.UpdateConfig(cfg)
require.NoError(t, err)
// ensure the config setting was updated
cfg, resp = th.Client.GetConfig()
CheckNoError(t, resp)
cfg, _, err = th.Client.GetConfig()
require.NoError(t, err)
assert.Equal(t, *cfg.ServiceSettings.AllowCorsFrom, mockVal)
})
}
@ -342,23 +345,23 @@ func TestUpdateConfigMessageExportSpecialHandling(t *testing.T) {
})
// Turn it on, timestamp should be updated.
cfg, resp := th.SystemAdminClient.GetConfig()
CheckNoError(t, resp)
cfg, _, err := th.SystemAdminClient.GetConfig()
require.NoError(t, err)
*cfg.MessageExportSettings.EnableExport = true
_, resp = th.SystemAdminClient.UpdateConfig(cfg)
CheckNoError(t, resp)
_, _, err = th.SystemAdminClient.UpdateConfig(cfg)
require.NoError(t, err)
assert.True(t, *th.App.Config().MessageExportSettings.EnableExport)
assert.NotEqual(t, int64(0), *th.App.Config().MessageExportSettings.ExportFromTimestamp)
// Turn it off, timestamp should be cleared.
cfg, resp = th.SystemAdminClient.GetConfig()
CheckNoError(t, resp)
cfg, _, err = th.SystemAdminClient.GetConfig()
require.NoError(t, err)
*cfg.MessageExportSettings.EnableExport = false
_, resp = th.SystemAdminClient.UpdateConfig(cfg)
CheckNoError(t, resp)
_, _, err = th.SystemAdminClient.UpdateConfig(cfg)
require.NoError(t, err)
assert.False(t, *th.App.Config().MessageExportSettings.EnableExport)
assert.Equal(t, int64(0), *th.App.Config().MessageExportSettings.ExportFromTimestamp)
@ -370,23 +373,23 @@ func TestUpdateConfigMessageExportSpecialHandling(t *testing.T) {
})
// Turn it on, timestamp should *not* be updated.
cfg, resp = th.SystemAdminClient.GetConfig()
CheckNoError(t, resp)
cfg, _, err = th.SystemAdminClient.GetConfig()
require.NoError(t, err)
*cfg.MessageExportSettings.EnableExport = true
_, resp = th.SystemAdminClient.UpdateConfig(cfg)
CheckNoError(t, resp)
_, _, err = th.SystemAdminClient.UpdateConfig(cfg)
require.NoError(t, err)
assert.True(t, *th.App.Config().MessageExportSettings.EnableExport)
assert.Equal(t, int64(12345), *th.App.Config().MessageExportSettings.ExportFromTimestamp)
// Turn it off, timestamp should be cleared.
cfg, resp = th.SystemAdminClient.GetConfig()
CheckNoError(t, resp)
cfg, _, err = th.SystemAdminClient.GetConfig()
require.NoError(t, err)
*cfg.MessageExportSettings.EnableExport = false
_, resp = th.SystemAdminClient.UpdateConfig(cfg)
CheckNoError(t, resp)
_, _, err = th.SystemAdminClient.UpdateConfig(cfg)
require.NoError(t, err)
assert.False(t, *th.App.Config().MessageExportSettings.EnableExport)
assert.Equal(t, int64(0), *th.App.Config().MessageExportSettings.ExportFromTimestamp)
@ -398,35 +401,35 @@ func TestUpdateConfigRestrictSystemAdmin(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
t.Run("Restrict flag should be honored for sysadmin", func(t *testing.T) {
originalCfg, resp := th.SystemAdminClient.GetConfig()
CheckNoError(t, resp)
originalCfg, _, err := th.SystemAdminClient.GetConfig()
require.NoError(t, err)
cfg := originalCfg.Clone()
*cfg.TeamSettings.SiteName = "MyFancyName" // Allowed
*cfg.ServiceSettings.SiteURL = "http://example.com" // Ignored
returnedCfg, resp := th.SystemAdminClient.UpdateConfig(cfg)
CheckNoError(t, resp)
returnedCfg, _, err := th.SystemAdminClient.UpdateConfig(cfg)
require.NoError(t, err)
require.Equal(t, "MyFancyName", *returnedCfg.TeamSettings.SiteName)
require.Equal(t, *originalCfg.ServiceSettings.SiteURL, *returnedCfg.ServiceSettings.SiteURL)
actualCfg, resp := th.SystemAdminClient.GetConfig()
CheckNoError(t, resp)
actualCfg, _, err := th.SystemAdminClient.GetConfig()
require.NoError(t, err)
require.Equal(t, returnedCfg, actualCfg)
})
t.Run("Restrict flag should be ignored by local mode", func(t *testing.T) {
originalCfg, resp := th.LocalClient.GetConfig()
CheckNoError(t, resp)
originalCfg, _, err := th.LocalClient.GetConfig()
require.NoError(t, err)
cfg := originalCfg.Clone()
*cfg.TeamSettings.SiteName = "MyFancyName" // Allowed
*cfg.ServiceSettings.SiteURL = "http://example.com" // Ignored
returnedCfg, resp := th.LocalClient.UpdateConfig(cfg)
CheckNoError(t, resp)
returnedCfg, _, err := th.LocalClient.UpdateConfig(cfg)
require.NoError(t, err)
require.Equal(t, "MyFancyName", *returnedCfg.TeamSettings.SiteName)
require.Equal(t, "http://example.com", *returnedCfg.ServiceSettings.SiteURL)
@ -452,13 +455,13 @@ func TestUpdateConfigDiffInAuditRecord(t *testing.T) {
th := SetupWithServerOptions(t, options)
defer th.TearDown()
cfg, resp := th.SystemAdminClient.GetConfig()
CheckNoError(t, resp)
cfg, _, err := th.SystemAdminClient.GetConfig()
require.NoError(t, err)
timeoutVal := *cfg.ServiceSettings.ReadTimeout
cfg.ServiceSettings.ReadTimeout = model.NewInt(timeoutVal + 1)
cfg, resp = th.SystemAdminClient.UpdateConfig(cfg)
CheckNoError(t, resp)
cfg, _, err = th.SystemAdminClient.UpdateConfig(cfg)
require.NoError(t, err)
defer th.App.UpdateConfig(func(cfg *model.Config) {
cfg.ServiceSettings.ReadTimeout = model.NewInt(timeoutVal)
})
@ -490,8 +493,8 @@ func TestGetEnvironmentConfig(t *testing.T) {
t.Run("as system admin", func(t *testing.T) {
SystemAdminClient := th.SystemAdminClient
envConfig, resp := SystemAdminClient.GetEnvironmentConfig()
CheckNoError(t, resp)
envConfig, _, err := SystemAdminClient.GetEnvironmentConfig()
require.NoError(t, err)
serviceSettings, ok := envConfig["ServiceSettings"]
require.True(t, ok, "should've returned ServiceSettings")
@ -521,23 +524,24 @@ func TestGetEnvironmentConfig(t *testing.T) {
TeamAdminClient := th.CreateClient()
th.LoginTeamAdminWithClient(TeamAdminClient)
envConfig, resp := TeamAdminClient.GetEnvironmentConfig()
CheckNoError(t, resp)
envConfig, _, err := TeamAdminClient.GetEnvironmentConfig()
require.NoError(t, err)
require.Empty(t, envConfig)
})
t.Run("as regular user", func(t *testing.T) {
Client := th.Client
client := th.Client
envConfig, resp := Client.GetEnvironmentConfig()
CheckNoError(t, resp)
envConfig, _, err := client.GetEnvironmentConfig()
require.NoError(t, err)
require.Empty(t, envConfig)
})
t.Run("as not-regular user", func(t *testing.T) {
Client := th.CreateClient()
client := th.CreateClient()
_, resp := Client.GetEnvironmentConfig()
_, resp, err := client.GetEnvironmentConfig()
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
})
}
@ -554,10 +558,10 @@ func TestGetOldClientConfig(t *testing.T) {
*cfg.ServiceSettings.GoogleDeveloperKey = testKey
})
Client := th.Client
client := th.Client
config, resp := Client.GetOldClientConfig("")
CheckNoError(t, resp)
config, _, err := client.GetOldClientConfig("")
require.NoError(t, err)
require.NotEmpty(t, config["Version"], "config not returned correctly")
require.Equal(t, testKey, config["GoogleDeveloperKey"])
@ -568,29 +572,29 @@ func TestGetOldClientConfig(t *testing.T) {
*cfg.ServiceSettings.GoogleDeveloperKey = testKey
})
Client := th.CreateClient()
client := th.CreateClient()
config, resp := Client.GetOldClientConfig("")
CheckNoError(t, resp)
config, _, err := client.GetOldClientConfig("")
require.NoError(t, err)
require.NotEmpty(t, config["Version"], "config not returned correctly")
require.Empty(t, config["GoogleDeveloperKey"], "config should be missing developer key")
})
t.Run("missing format", func(t *testing.T) {
Client := th.Client
client := th.Client
_, err := Client.DoApiGet("/config/client", "")
require.NotNil(t, err)
require.Equal(t, http.StatusNotImplemented, err.StatusCode)
resp, err := client.DoApiGet("/config/client", "")
require.Error(t, err)
require.Equal(t, http.StatusNotImplemented, resp.StatusCode)
})
t.Run("invalid format", func(t *testing.T) {
Client := th.Client
client := th.Client
_, err := Client.DoApiGet("/config/client?format=junk", "")
require.NotNil(t, err)
require.Equal(t, http.StatusBadRequest, err.StatusCode)
resp, err := client.DoApiGet("/config/client?format=junk", "")
require.Error(t, err)
require.Equal(t, http.StatusBadRequest, resp.StatusCode)
})
}
@ -599,12 +603,14 @@ func TestPatchConfig(t *testing.T) {
defer th.TearDown()
t.Run("config is missing", func(t *testing.T) {
_, response := th.Client.PatchConfig(nil)
_, response, err := th.Client.PatchConfig(nil)
require.Error(t, err)
CheckBadRequestStatus(t, response)
})
t.Run("user is not system admin", func(t *testing.T) {
_, response := th.Client.PatchConfig(&model.Config{})
_, response, err := th.Client.PatchConfig(&model.Config{})
require.Error(t, err)
CheckForbiddenStatus(t, response)
})
@ -615,7 +621,7 @@ func TestPatchConfig(t *testing.T) {
ConsoleLevel: model.NewString("INFO"),
}}
updatedConfig, _ := th.SystemAdminClient.PatchConfig(&config)
updatedConfig, _, _ := th.SystemAdminClient.PatchConfig(&config)
assert.Equal(t, "DEBUG", *updatedConfig.LogSettings.ConsoleLevel)
})
@ -627,13 +633,13 @@ func TestPatchConfig(t *testing.T) {
ConsoleLevel: model.NewString("INFO"),
}}
oldConfig, _ := th.LocalClient.GetConfig()
updatedConfig, _ := th.LocalClient.PatchConfig(&config)
oldConfig, _, _ := th.LocalClient.GetConfig()
updatedConfig, _, _ := th.LocalClient.PatchConfig(&config)
assert.Equal(t, "INFO", *updatedConfig.LogSettings.ConsoleLevel)
// reset the config
_, resp := th.LocalClient.UpdateConfig(oldConfig)
CheckNoError(t, resp)
_, _, err := th.LocalClient.UpdateConfig(oldConfig)
require.NoError(t, err)
})
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
@ -642,18 +648,19 @@ func TestPatchConfig(t *testing.T) {
MinimumLength: model.NewInt(4),
}}
_, response := client.PatchConfig(&config)
_, response, err := client.PatchConfig(&config)
assert.Equal(t, http.StatusBadRequest, response.StatusCode)
assert.NotNil(t, response.Error)
assert.Equal(t, "model.config.is_valid.password_length.app_error", response.Error.Id)
assert.Error(t, err)
CheckErrorID(t, err, "model.config.is_valid.password_length.app_error")
})
t.Run("should patch the config", func(t *testing.T) {
*th.App.Config().ExperimentalSettings.RestrictSystemAdmin = false
th.App.UpdateConfig(func(cfg *model.Config) { cfg.TeamSettings.ExperimentalDefaultChannels = []string{"some-channel"} })
oldConfig, _ := client.GetConfig()
oldConfig, _, err := client.GetConfig()
require.NoError(t, err)
assert.False(t, *oldConfig.PasswordSettings.Lowercase)
assert.NotEqual(t, 15, *oldConfig.PasswordSettings.MinimumLength)
@ -676,9 +683,11 @@ func TestPatchConfig(t *testing.T) {
},
}
_, response := client.PatchConfig(&config)
_, response, err := client.PatchConfig(&config)
require.NoError(t, err)
updatedConfig, _ := client.GetConfig()
updatedConfig, _, err := client.GetConfig()
require.NoError(t, err)
assert.True(t, *updatedConfig.PasswordSettings.Lowercase)
assert.Equal(t, "INFO", *updatedConfig.LogSettings.ConsoleLevel)
assert.Equal(t, []string{"another-channel"}, updatedConfig.TeamSettings.ExperimentalDefaultChannels)
@ -686,8 +695,8 @@ func TestPatchConfig(t *testing.T) {
assert.Equal(t, "no-cache, no-store, must-revalidate", response.Header.Get("Cache-Control"))
// reset the config
_, resp := client.UpdateConfig(oldConfig)
CheckNoError(t, resp)
_, _, err = client.UpdateConfig(oldConfig)
require.NoError(t, err)
})
t.Run("should sanitize config", func(t *testing.T) {
@ -695,7 +704,8 @@ func TestPatchConfig(t *testing.T) {
Symbol: model.NewBool(true),
}}
updatedConfig, _ := client.PatchConfig(&config)
updatedConfig, _, err := client.PatchConfig(&config)
require.NoError(t, err)
assert.Equal(t, model.FakeSetting, *updatedConfig.SqlSettings.DataSource)
})
@ -705,19 +715,21 @@ func TestPatchConfig(t *testing.T) {
EnableUploads: model.NewBool(true),
}}
updatedConfig, resp := client.PatchConfig(&config)
updatedConfig, resp, err := client.PatchConfig(&config)
if client == th.LocalClient {
require.NoError(t, err)
CheckOKStatus(t, resp)
assert.Equal(t, true, *updatedConfig.PluginSettings.EnableUploads)
} else {
require.Error(t, err)
CheckForbiddenStatus(t, resp)
}
})
})
t.Run("System Admin should not be able to clear Site URL", func(t *testing.T) {
cfg, resp := th.SystemAdminClient.GetConfig()
CheckNoError(t, resp)
cfg, _, err := th.SystemAdminClient.GetConfig()
require.NoError(t, err)
siteURL := cfg.ServiceSettings.SiteURL
defer th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.SiteURL = siteURL })
@ -728,8 +740,8 @@ func TestPatchConfig(t *testing.T) {
SiteURL: model.NewString(nonEmptyURL),
},
}
updatedConfig, resp := th.SystemAdminClient.PatchConfig(&config)
CheckNoError(t, resp)
updatedConfig, _, err := th.SystemAdminClient.PatchConfig(&config)
require.NoError(t, err)
require.Equal(t, nonEmptyURL, *updatedConfig.ServiceSettings.SiteURL)
// Check that the Site URL can't be cleared
@ -738,18 +750,19 @@ func TestPatchConfig(t *testing.T) {
SiteURL: model.NewString(""),
},
}
_, resp = th.SystemAdminClient.PatchConfig(&config)
_, resp, err := th.SystemAdminClient.PatchConfig(&config)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
CheckErrorMessage(t, resp, "api.config.update_config.clear_siteurl.app_error")
CheckErrorID(t, err, "api.config.update_config.clear_siteurl.app_error")
// Check that the Site URL wasn't cleared
cfg, resp = th.SystemAdminClient.GetConfig()
CheckNoError(t, resp)
cfg, _, err = th.SystemAdminClient.GetConfig()
require.NoError(t, err)
require.Equal(t, nonEmptyURL, *cfg.ServiceSettings.SiteURL)
// Check that sending an empty config returns no error.
_, resp = th.SystemAdminClient.PatchConfig(&model.Config{})
CheckNoError(t, resp)
_, _, err = th.SystemAdminClient.PatchConfig(&model.Config{})
require.NoError(t, err)
})
}
@ -758,7 +771,8 @@ func TestMigrateConfig(t *testing.T) {
defer th.TearDown()
t.Run("user is not system admin", func(t *testing.T) {
_, response := th.Client.MigrateConfig("from", "to")
response, err := th.Client.MigrateConfig("from", "to")
require.Error(t, err)
CheckForbiddenStatus(t, response)
})
@ -771,7 +785,7 @@ func TestMigrateConfig(t *testing.T) {
require.NoError(t, err)
defer f.RemoveFile("to.json")
_, response := client.MigrateConfig("from.json", "to.json")
CheckNoError(t, response)
_, err = client.MigrateConfig("from.json", "to.json")
require.NoError(t, err)
})
}

View file

@ -5,12 +5,15 @@ package api4
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestDataRetentionGetPolicy(t *testing.T) {
th := Setup(t)
defer th.TearDown()
_, resp := th.Client.GetDataRetentionPolicy()
_, resp, err := th.Client.GetDataRetentionPolicy()
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
}

View file

@ -7,6 +7,7 @@ import (
"testing"
"github.com/mattermost/mattermost-server/v6/model"
"github.com/stretchr/testify/require"
)
func TestElasticsearchTest(t *testing.T) {
@ -14,19 +15,22 @@ func TestElasticsearchTest(t *testing.T) {
defer th.TearDown()
t.Run("as system user", func(t *testing.T) {
_, resp := th.Client.TestElasticsearch()
resp, err := th.Client.TestElasticsearch()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("as system admin", func(t *testing.T) {
_, resp := th.SystemAdminClient.TestElasticsearch()
resp, err := th.SystemAdminClient.TestElasticsearch()
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
})
t.Run("as restricted system admin", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
_, resp := th.SystemAdminClient.TestElasticsearch()
resp, err := th.SystemAdminClient.TestElasticsearch()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
}
@ -36,19 +40,22 @@ func TestElasticsearchPurgeIndexes(t *testing.T) {
defer th.TearDown()
t.Run("as system user", func(t *testing.T) {
_, resp := th.Client.PurgeElasticsearchIndexes()
resp, err := th.Client.PurgeElasticsearchIndexes()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("as system admin", func(t *testing.T) {
_, resp := th.SystemAdminClient.PurgeElasticsearchIndexes()
resp, err := th.SystemAdminClient.PurgeElasticsearchIndexes()
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
})
t.Run("as restricted system admin", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
_, resp := th.SystemAdminClient.PurgeElasticsearchIndexes()
resp, err := th.SystemAdminClient.PurgeElasticsearchIndexes()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
}

View file

@ -23,7 +23,7 @@ import (
func TestCreateEmoji(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
EnableCustomEmoji := *th.App.Config().ServiceSettings.EnableCustomEmoji
defer func() {
@ -58,15 +58,16 @@ func TestCreateEmoji(t *testing.T) {
}
// try to create an emoji when they're disabled
_, resp := Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
_, resp, err := client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
// enable emoji creation for next cases
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = true })
// try to create a valid gif emoji when they're enabled
newEmoji, resp := Client.CreateEmoji(emoji, utils.CreateTestGif(t, emojiWidth, emojiHeight), "image.gif")
CheckNoError(t, resp)
newEmoji, _, err := client.CreateEmoji(emoji, utils.CreateTestGif(t, emojiWidth, emojiHeight), "image.gif")
require.NoError(t, err)
require.Equal(t, newEmoji.Name, emoji.Name, "create with wrong name")
checkEmojiFile(newEmoji.Id, "gif")
@ -75,9 +76,10 @@ func TestCreateEmoji(t *testing.T) {
CreatorId: th.BasicUser.Id,
Name: newEmoji.Name,
}
_, resp = Client.CreateEmoji(emoji2, utils.CreateTestGif(t, 10, 10), "image.gif")
_, resp, err = client.CreateEmoji(emoji2, utils.CreateTestGif(t, 10, 10), "image.gif")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
CheckErrorMessage(t, resp, "api.emoji.create.duplicate.app_error")
CheckErrorID(t, err, "api.emoji.create.duplicate.app_error")
// try to create a valid animated gif emoji
emoji = &model.Emoji{
@ -85,8 +87,8 @@ func TestCreateEmoji(t *testing.T) {
Name: model.NewId(),
}
newEmoji, resp = Client.CreateEmoji(emoji, utils.CreateTestAnimatedGif(t, emojiWidth, emojiHeight, 10), "image.gif")
CheckNoError(t, resp)
newEmoji, _, err = client.CreateEmoji(emoji, utils.CreateTestAnimatedGif(t, emojiWidth, emojiHeight, 10), "image.gif")
require.NoError(t, err)
require.Equal(t, newEmoji.Name, emoji.Name, "create with wrong name")
checkEmojiFile(newEmoji.Id, "gif")
@ -96,8 +98,8 @@ func TestCreateEmoji(t *testing.T) {
Name: model.NewId(),
}
newEmoji, resp = Client.CreateEmoji(emoji, utils.CreateTestJpeg(t, emojiWidth, emojiHeight), "image.jpeg")
CheckNoError(t, resp)
newEmoji, _, err = client.CreateEmoji(emoji, utils.CreateTestJpeg(t, emojiWidth, emojiHeight), "image.jpeg")
require.NoError(t, err)
require.Equal(t, newEmoji.Name, emoji.Name, "create with wrong name")
checkEmojiFile(newEmoji.Id, "png") // emoji must be converted from jpeg to png
@ -107,8 +109,8 @@ func TestCreateEmoji(t *testing.T) {
Name: model.NewId(),
}
newEmoji, resp = Client.CreateEmoji(emoji, utils.CreateTestPng(t, emojiWidth, emojiHeight), "image.png")
CheckNoError(t, resp)
newEmoji, _, err = client.CreateEmoji(emoji, utils.CreateTestPng(t, emojiWidth, emojiHeight), "image.png")
require.NoError(t, err)
require.Equal(t, newEmoji.Name, emoji.Name, "create with wrong name")
checkEmojiFile(newEmoji.Id, "png")
@ -118,8 +120,8 @@ func TestCreateEmoji(t *testing.T) {
Name: model.NewId(),
}
newEmoji, resp = Client.CreateEmoji(emoji, utils.CreateTestGif(t, 1000, 10), "image.gif")
CheckNoError(t, resp)
newEmoji, _, err = client.CreateEmoji(emoji, utils.CreateTestGif(t, 1000, 10), "image.gif")
require.NoError(t, err)
require.Equal(t, newEmoji.Name, emoji.Name, "create with wrong name")
// try to create an emoji that's too wide
@ -128,8 +130,8 @@ func TestCreateEmoji(t *testing.T) {
Name: model.NewId(),
}
_, resp = Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, app.MaxEmojiOriginalWidth+1), "image.gif")
require.NotNil(t, resp.Error, "should fail - emoji is too wide")
_, _, err = client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, app.MaxEmojiOriginalWidth+1), "image.gif")
require.Error(t, err, "should fail - emoji is too wide")
// try to create an emoji that's too tall
emoji = &model.Emoji{
@ -137,8 +139,8 @@ func TestCreateEmoji(t *testing.T) {
Name: model.NewId(),
}
_, resp = Client.CreateEmoji(emoji, utils.CreateTestGif(t, app.MaxEmojiOriginalHeight+1, 10), "image.gif")
require.NotNil(t, resp.Error, "should fail - emoji is too tall")
_, _, err = client.CreateEmoji(emoji, utils.CreateTestGif(t, app.MaxEmojiOriginalHeight+1, 10), "image.gif")
require.Error(t, err, "should fail - emoji is too tall")
// try to create an emoji that's too large
emoji = &model.Emoji{
@ -146,8 +148,8 @@ func TestCreateEmoji(t *testing.T) {
Name: model.NewId(),
}
_, resp = Client.CreateEmoji(emoji, utils.CreateTestAnimatedGif(t, 100, 100, 10000), "image.gif")
require.NotNil(t, resp.Error, "should fail - emoji is too big")
_, _, err = client.CreateEmoji(emoji, utils.CreateTestAnimatedGif(t, 100, 100, 10000), "image.gif")
require.Error(t, err, "should fail - emoji is too big")
// try to create an emoji with data that isn't an image
emoji = &model.Emoji{
@ -155,9 +157,10 @@ func TestCreateEmoji(t *testing.T) {
Name: model.NewId(),
}
_, resp = Client.CreateEmoji(emoji, make([]byte, 100), "image.gif")
_, resp, err = client.CreateEmoji(emoji, make([]byte, 100), "image.gif")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
CheckErrorMessage(t, resp, "api.emoji.upload.image.app_error")
CheckErrorID(t, err, "api.emoji.upload.image.app_error")
// try to create an emoji as another user
emoji = &model.Emoji{
@ -165,7 +168,8 @@ func TestCreateEmoji(t *testing.T) {
Name: model.NewId(),
}
_, resp = Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
_, resp, err = client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
require.Error(t, err)
CheckForbiddenStatus(t, resp)
// try to create an emoji without permissions
@ -176,7 +180,8 @@ func TestCreateEmoji(t *testing.T) {
Name: model.NewId(),
}
_, resp = Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
_, resp, err = client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
require.Error(t, err)
CheckForbiddenStatus(t, resp)
// create an emoji with permissions in one team
@ -187,14 +192,14 @@ func TestCreateEmoji(t *testing.T) {
Name: model.NewId(),
}
_, resp = Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
CheckNoError(t, resp)
_, _, err = client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
require.NoError(t, err)
}
func TestGetEmojiList(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
EnableCustomEmoji := *th.App.Config().ServiceSettings.EnableCustomEmoji
defer func() {
@ -218,13 +223,13 @@ func TestGetEmojiList(t *testing.T) {
}
for idx, emoji := range emojis {
newEmoji, resp := Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
CheckNoError(t, resp)
newEmoji, _, err := client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
require.NoError(t, err)
emojis[idx] = newEmoji
}
listEmoji, resp := Client.GetEmojiList(0, 100)
CheckNoError(t, resp)
listEmoji, _, err := client.GetEmojiList(0, 100)
require.NoError(t, err)
for _, emoji := range emojis {
found := false
for _, savedEmoji := range listEmoji {
@ -236,10 +241,10 @@ func TestGetEmojiList(t *testing.T) {
require.Truef(t, found, "failed to get emoji with id %v, %v", emoji.Id, len(listEmoji))
}
_, resp = Client.DeleteEmoji(emojis[0].Id)
CheckNoError(t, resp)
listEmoji, resp = Client.GetEmojiList(0, 100)
CheckNoError(t, resp)
_, err = client.DeleteEmoji(emojis[0].Id)
require.NoError(t, err)
listEmoji, _, err = client.GetEmojiList(0, 100)
require.NoError(t, err)
found := false
for _, savedEmoji := range listEmoji {
if savedEmoji.Id == emojis[0].Id {
@ -249,13 +254,13 @@ func TestGetEmojiList(t *testing.T) {
}
require.Falsef(t, found, "should not get a deleted emoji %v", emojis[0].Id)
listEmoji, resp = Client.GetEmojiList(0, 1)
CheckNoError(t, resp)
listEmoji, _, err = client.GetEmojiList(0, 1)
require.NoError(t, err)
require.Len(t, listEmoji, 1, "should only return 1")
listEmoji, resp = Client.GetSortedEmojiList(0, 100, model.EmojiSortByName)
CheckNoError(t, resp)
listEmoji, _, err = client.GetSortedEmojiList(0, 100, model.EmojiSortByName)
require.NoError(t, err)
require.Greater(t, len(listEmoji), 0, "should return more than 0")
}
@ -263,7 +268,7 @@ func TestGetEmojiList(t *testing.T) {
func TestDeleteEmoji(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
EnableCustomEmoji := *th.App.Config().ServiceSettings.EnableCustomEmoji
defer func() {
@ -281,47 +286,47 @@ func TestDeleteEmoji(t *testing.T) {
Name: model.NewId(),
}
newEmoji, resp := Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
CheckNoError(t, resp)
newEmoji, _, err := client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
require.NoError(t, err)
ok, resp := Client.DeleteEmoji(newEmoji.Id)
CheckNoError(t, resp)
require.True(t, ok, "delete did not return OK")
_, err = client.DeleteEmoji(newEmoji.Id)
require.NoError(t, err)
_, resp = Client.GetEmoji(newEmoji.Id)
require.NotNil(t, resp, "nil response")
require.NotNil(t, resp.Error, "expected error fetching deleted emoji")
_, _, err = client.GetEmoji(newEmoji.Id)
require.Error(t, err, "expected error fetching deleted emoji")
//Admin can delete other users emoji
newEmoji, resp = Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
CheckNoError(t, resp)
newEmoji, _, err = client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
require.NoError(t, err)
ok, resp = th.SystemAdminClient.DeleteEmoji(newEmoji.Id)
CheckNoError(t, resp)
require.True(t, ok, "delete did not return OK")
_, err = th.SystemAdminClient.DeleteEmoji(newEmoji.Id)
require.NoError(t, err)
_, resp = th.SystemAdminClient.GetEmoji(newEmoji.Id)
require.NotNil(t, resp, "nil response")
require.NotNil(t, resp.Error, "expected error fetching deleted emoji")
_, _, err = th.SystemAdminClient.GetEmoji(newEmoji.Id)
require.Error(t, err, "expected error fetching deleted emoji")
// Try to delete just deleted emoji
_, resp = Client.DeleteEmoji(newEmoji.Id)
resp, err := client.DeleteEmoji(newEmoji.Id)
require.Error(t, err)
CheckNotFoundStatus(t, resp)
//Try to delete non-existing emoji
_, resp = Client.DeleteEmoji(model.NewId())
resp, err = client.DeleteEmoji(model.NewId())
require.Error(t, err)
CheckNotFoundStatus(t, resp)
//Try to delete without Id
_, resp = Client.DeleteEmoji("")
resp, err = client.DeleteEmoji("")
require.Error(t, err)
CheckNotFoundStatus(t, resp)
//Try to delete my custom emoji without permissions
newEmoji, resp = Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
CheckNoError(t, resp)
newEmoji, _, err = client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
require.NoError(t, err)
th.RemovePermissionFromRole(model.PermissionDeleteEmojis.Id, model.SystemUserRoleId)
_, resp = Client.DeleteEmoji(newEmoji.Id)
resp, err = client.DeleteEmoji(newEmoji.Id)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
th.AddPermissionToRole(model.PermissionDeleteEmojis.Id, model.SystemUserRoleId)
@ -331,22 +336,23 @@ func TestDeleteEmoji(t *testing.T) {
Name: model.NewId(),
}
newEmoji, resp = Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
CheckNoError(t, resp)
newEmoji, _, err = client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
require.NoError(t, err)
th.RemovePermissionFromRole(model.PermissionDeleteEmojis.Id, model.SystemUserRoleId)
th.AddPermissionToRole(model.PermissionDeleteOthersEmojis.Id, model.SystemUserRoleId)
Client.Logout()
client.Logout()
th.LoginBasic2()
_, resp = Client.DeleteEmoji(newEmoji.Id)
resp, err = client.DeleteEmoji(newEmoji.Id)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
th.RemovePermissionFromRole(model.PermissionDeleteOthersEmojis.Id, model.SystemUserRoleId)
th.AddPermissionToRole(model.PermissionDeleteEmojis.Id, model.SystemUserRoleId)
Client.Logout()
client.Logout()
th.LoginBasic()
//Try to delete other user's custom emoji without DELETE_OTHERS_EMOJIS permissions
@ -355,16 +361,17 @@ func TestDeleteEmoji(t *testing.T) {
Name: model.NewId(),
}
newEmoji, resp = Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
CheckNoError(t, resp)
newEmoji, _, err = client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
require.NoError(t, err)
Client.Logout()
client.Logout()
th.LoginBasic2()
_, resp = Client.DeleteEmoji(newEmoji.Id)
resp, err = client.DeleteEmoji(newEmoji.Id)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
Client.Logout()
client.Logout()
th.LoginBasic()
//Try to delete other user's custom emoji with permissions
@ -373,29 +380,29 @@ func TestDeleteEmoji(t *testing.T) {
Name: model.NewId(),
}
newEmoji, resp = Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
CheckNoError(t, resp)
newEmoji, _, err = client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
require.NoError(t, err)
th.AddPermissionToRole(model.PermissionDeleteEmojis.Id, model.SystemUserRoleId)
th.AddPermissionToRole(model.PermissionDeleteOthersEmojis.Id, model.SystemUserRoleId)
Client.Logout()
client.Logout()
th.LoginBasic2()
_, resp = Client.DeleteEmoji(newEmoji.Id)
CheckNoError(t, resp)
_, err = client.DeleteEmoji(newEmoji.Id)
require.NoError(t, err)
Client.Logout()
client.Logout()
th.LoginBasic()
//Try to delete my custom emoji with permissions at team level
newEmoji, resp = Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
CheckNoError(t, resp)
newEmoji, _, err = client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
require.NoError(t, err)
th.RemovePermissionFromRole(model.PermissionDeleteEmojis.Id, model.SystemUserRoleId)
th.AddPermissionToRole(model.PermissionDeleteEmojis.Id, model.TeamUserRoleId)
_, resp = Client.DeleteEmoji(newEmoji.Id)
CheckNoError(t, resp)
_, err = client.DeleteEmoji(newEmoji.Id)
require.NoError(t, err)
th.AddPermissionToRole(model.PermissionDeleteEmojis.Id, model.SystemUserRoleId)
th.RemovePermissionFromRole(model.PermissionDeleteEmojis.Id, model.TeamUserRoleId)
@ -405,8 +412,8 @@ func TestDeleteEmoji(t *testing.T) {
Name: model.NewId(),
}
newEmoji, resp = Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
CheckNoError(t, resp)
newEmoji, _, err = client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
require.NoError(t, err)
th.RemovePermissionFromRole(model.PermissionDeleteEmojis.Id, model.SystemUserRoleId)
th.RemovePermissionFromRole(model.PermissionDeleteOthersEmojis.Id, model.SystemUserRoleId)
@ -414,17 +421,17 @@ func TestDeleteEmoji(t *testing.T) {
th.AddPermissionToRole(model.PermissionDeleteEmojis.Id, model.TeamUserRoleId)
th.AddPermissionToRole(model.PermissionDeleteOthersEmojis.Id, model.TeamUserRoleId)
Client.Logout()
client.Logout()
th.LoginBasic2()
_, resp = Client.DeleteEmoji(newEmoji.Id)
CheckNoError(t, resp)
_, err = client.DeleteEmoji(newEmoji.Id)
require.NoError(t, err)
}
func TestGetEmoji(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
EnableCustomEmoji := *th.App.Config().ServiceSettings.EnableCustomEmoji
defer func() {
@ -437,21 +444,22 @@ func TestGetEmoji(t *testing.T) {
Name: model.NewId(),
}
newEmoji, resp := Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
CheckNoError(t, resp)
newEmoji, _, err := client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
require.NoError(t, err)
emoji, resp = Client.GetEmoji(newEmoji.Id)
CheckNoError(t, resp)
emoji, _, err = client.GetEmoji(newEmoji.Id)
require.NoError(t, err)
require.Equal(t, newEmoji.Id, emoji.Id, "wrong emoji was returned")
_, resp = Client.GetEmoji(model.NewId())
_, resp, err := client.GetEmoji(model.NewId())
require.Error(t, err)
CheckNotFoundStatus(t, resp)
}
func TestGetEmojiByName(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = true })
@ -460,25 +468,27 @@ func TestGetEmojiByName(t *testing.T) {
Name: model.NewId(),
}
newEmoji, resp := Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
CheckNoError(t, resp)
newEmoji, _, err := client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
require.NoError(t, err)
emoji, resp = Client.GetEmojiByName(newEmoji.Name)
CheckNoError(t, resp)
emoji, _, err = client.GetEmojiByName(newEmoji.Name)
require.NoError(t, err)
assert.Equal(t, newEmoji.Name, emoji.Name)
_, resp = Client.GetEmojiByName(model.NewId())
_, resp, err := client.GetEmojiByName(model.NewId())
require.Error(t, err)
CheckNotFoundStatus(t, resp)
Client.Logout()
_, resp = Client.GetEmojiByName(newEmoji.Name)
client.Logout()
_, resp, err = client.GetEmojiByName(newEmoji.Name)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
}
func TestGetEmojiImage(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = true })
@ -487,20 +497,21 @@ func TestGetEmojiImage(t *testing.T) {
Name: model.NewId(),
}
emoji1, resp := Client.CreateEmoji(emoji1, utils.CreateTestGif(t, 10, 10), "image.gif")
CheckNoError(t, resp)
emoji1, _, err := client.CreateEmoji(emoji1, utils.CreateTestGif(t, 10, 10), "image.gif")
require.NoError(t, err)
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = false })
_, resp = Client.GetEmojiImage(emoji1.Id)
_, resp, err := client.GetEmojiImage(emoji1.Id)
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
CheckErrorMessage(t, resp, "api.emoji.disabled.app_error")
CheckErrorID(t, err, "api.emoji.disabled.app_error")
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = true })
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.DriverName = "local" })
emojiImage, resp := Client.GetEmojiImage(emoji1.Id)
CheckNoError(t, resp)
emojiImage, _, err := client.GetEmojiImage(emoji1.Id)
require.NoError(t, err)
require.Greater(t, len(emojiImage), 0, "should return the image")
_, imageType, err := image.DecodeConfig(bytes.NewReader(emojiImage))
@ -512,11 +523,11 @@ func TestGetEmojiImage(t *testing.T) {
Name: model.NewId(),
}
emoji2, resp = Client.CreateEmoji(emoji2, utils.CreateTestAnimatedGif(t, 10, 10, 10), "image.gif")
CheckNoError(t, resp)
emoji2, _, err = client.CreateEmoji(emoji2, utils.CreateTestAnimatedGif(t, 10, 10, 10), "image.gif")
require.NoError(t, err)
emojiImage, resp = Client.GetEmojiImage(emoji2.Id)
CheckNoError(t, resp)
emojiImage, _, err = client.GetEmojiImage(emoji2.Id)
require.NoError(t, err)
require.Greater(t, len(emojiImage), 0, "no image returned")
_, imageType, err = image.DecodeConfig(bytes.NewReader(emojiImage))
@ -527,11 +538,11 @@ func TestGetEmojiImage(t *testing.T) {
CreatorId: th.BasicUser.Id,
Name: model.NewId(),
}
emoji3, resp = Client.CreateEmoji(emoji3, utils.CreateTestJpeg(t, 10, 10), "image.jpg")
CheckNoError(t, resp)
emoji3, _, err = client.CreateEmoji(emoji3, utils.CreateTestJpeg(t, 10, 10), "image.jpg")
require.NoError(t, err)
emojiImage, resp = Client.GetEmojiImage(emoji3.Id)
CheckNoError(t, resp)
emojiImage, _, err = client.GetEmojiImage(emoji3.Id)
require.NoError(t, err)
require.Greater(t, len(emojiImage), 0, "no image returned")
_, imageType, err = image.DecodeConfig(bytes.NewReader(emojiImage))
@ -542,34 +553,37 @@ func TestGetEmojiImage(t *testing.T) {
CreatorId: th.BasicUser.Id,
Name: model.NewId(),
}
emoji4, resp = Client.CreateEmoji(emoji4, utils.CreateTestPng(t, 10, 10), "image.png")
CheckNoError(t, resp)
emoji4, _, err = client.CreateEmoji(emoji4, utils.CreateTestPng(t, 10, 10), "image.png")
require.NoError(t, err)
emojiImage, resp = Client.GetEmojiImage(emoji4.Id)
CheckNoError(t, resp)
emojiImage, _, err = client.GetEmojiImage(emoji4.Id)
require.NoError(t, err)
require.Greater(t, len(emojiImage), 0, "no image returned")
_, imageType, err = image.DecodeConfig(bytes.NewReader(emojiImage))
require.NoError(t, err, "unable to idenitify received image")
require.Equal(t, imageType, "png", "expected png")
_, resp = Client.DeleteEmoji(emoji4.Id)
CheckNoError(t, resp)
_, err = client.DeleteEmoji(emoji4.Id)
require.NoError(t, err)
_, resp = Client.GetEmojiImage(emoji4.Id)
_, resp, err = client.GetEmojiImage(emoji4.Id)
require.Error(t, err)
CheckNotFoundStatus(t, resp)
_, resp = Client.GetEmojiImage(model.NewId())
_, resp, err = client.GetEmojiImage(model.NewId())
require.Error(t, err)
CheckNotFoundStatus(t, resp)
_, resp = Client.GetEmojiImage("")
_, resp, err = client.GetEmojiImage("")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
}
func TestSearchEmoji(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = true })
@ -588,14 +602,14 @@ func TestSearchEmoji(t *testing.T) {
}
for idx, emoji := range emojis {
newEmoji, resp := Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
CheckNoError(t, resp)
newEmoji, _, err := client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
require.NoError(t, err)
emojis[idx] = newEmoji
}
search := &model.EmojiSearch{Term: searchTerm1}
remojis, resp := Client.SearchEmoji(search)
CheckNoError(t, resp)
remojis, resp, err := client.SearchEmoji(search)
require.NoError(t, err)
CheckOKStatus(t, resp)
found := false
@ -609,8 +623,8 @@ func TestSearchEmoji(t *testing.T) {
search.Term = searchTerm2
search.PrefixOnly = true
remojis, resp = Client.SearchEmoji(search)
CheckNoError(t, resp)
remojis, resp, err = client.SearchEmoji(search)
require.NoError(t, err)
CheckOKStatus(t, resp)
found = false
@ -623,8 +637,8 @@ func TestSearchEmoji(t *testing.T) {
assert.False(t, found)
search.PrefixOnly = false
remojis, resp = Client.SearchEmoji(search)
CheckNoError(t, resp)
remojis, resp, err = client.SearchEmoji(search)
require.NoError(t, err)
CheckOKStatus(t, resp)
found = false
@ -637,18 +651,20 @@ func TestSearchEmoji(t *testing.T) {
assert.True(t, found)
search.Term = ""
_, resp = Client.SearchEmoji(search)
_, resp, err = client.SearchEmoji(search)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
Client.Logout()
_, resp = Client.SearchEmoji(search)
client.Logout()
_, resp, err = client.SearchEmoji(search)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
}
func TestAutocompleteEmoji(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = true })
@ -666,13 +682,13 @@ func TestAutocompleteEmoji(t *testing.T) {
}
for idx, emoji := range emojis {
newEmoji, resp := Client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
CheckNoError(t, resp)
newEmoji, _, err := client.CreateEmoji(emoji, utils.CreateTestGif(t, 10, 10), "image.gif")
require.NoError(t, err)
emojis[idx] = newEmoji
}
remojis, resp := Client.AutocompleteEmoji(searchTerm1, "")
CheckNoError(t, resp)
remojis, resp, err := client.AutocompleteEmoji(searchTerm1, "")
require.NoError(t, err)
CheckOKStatus(t, resp)
found1 := false
@ -690,10 +706,12 @@ func TestAutocompleteEmoji(t *testing.T) {
assert.True(t, found1)
assert.False(t, found2)
_, resp = Client.AutocompleteEmoji("", "")
_, resp, err = client.AutocompleteEmoji("", "")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
Client.Logout()
_, resp = Client.AutocompleteEmoji(searchTerm1, "")
client.Logout()
_, resp, err = client.AutocompleteEmoji(searchTerm1, "")
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
}

View file

@ -22,15 +22,15 @@ func TestListExports(t *testing.T) {
defer th.TearDown()
t.Run("no permissions", func(t *testing.T) {
exports, resp := th.Client.ListExports()
require.NotNil(t, resp.Error)
require.Equal(t, "api.context.permissions.app_error", resp.Error.Id)
exports, _, err := th.Client.ListExports()
require.Error(t, err)
CheckErrorID(t, err, "api.context.permissions.app_error")
require.Nil(t, exports)
})
th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) {
exports, resp := c.ListExports()
require.Nil(t, resp.Error)
exports, _, err := c.ListExports()
require.NoError(t, err)
require.Empty(t, exports)
}, "no exports")
@ -47,8 +47,8 @@ func TestListExports(t *testing.T) {
require.NoError(t, err)
f.Close()
exports, resp := c.ListExports()
require.Nil(t, resp.Error)
exports, _, err := c.ListExports()
require.NoError(t, err)
require.Len(t, exports, 1)
require.Equal(t, exports[0], "export.zip")
}, "expected exports")
@ -63,16 +63,16 @@ func TestListExports(t *testing.T) {
require.NoError(t, err)
defer os.RemoveAll(exportDir)
exports, resp := c.ListExports()
require.Nil(t, resp.Error)
exports, _, err := c.ListExports()
require.NoError(t, err)
require.Empty(t, exports)
f, err := os.Create(filepath.Join(exportDir, "export.zip"))
require.NoError(t, err)
f.Close()
exports, resp = c.ListExports()
require.Nil(t, resp.Error)
exports, _, err = c.ListExports()
require.NoError(t, err)
require.Len(t, exports, 1)
require.Equal(t, "export.zip", exports[0])
}, "change export directory")
@ -83,10 +83,9 @@ func TestDeleteExport(t *testing.T) {
defer th.TearDown()
t.Run("no permissions", func(t *testing.T) {
ok, resp := th.Client.DeleteExport("export.zip")
require.NotNil(t, resp.Error)
require.Equal(t, "api.context.permissions.app_error", resp.Error.Id)
require.False(t, ok)
_, err := th.Client.DeleteExport("export.zip")
require.Error(t, err)
CheckErrorID(t, err, "api.context.permissions.app_error")
})
dataDir, found := fileutils.FindDir("data")
@ -102,23 +101,21 @@ func TestDeleteExport(t *testing.T) {
require.NoError(t, err)
f.Close()
exports, resp := c.ListExports()
require.Nil(t, resp.Error)
exports, _, err := c.ListExports()
require.NoError(t, err)
require.Len(t, exports, 1)
require.Equal(t, exports[0], exportName)
ok, resp := c.DeleteExport(exportName)
require.Nil(t, resp.Error)
require.True(t, ok)
_, err = c.DeleteExport(exportName)
require.NoError(t, err)
exports, resp = c.ListExports()
require.Nil(t, resp.Error)
exports, _, err = c.ListExports()
require.NoError(t, err)
require.Empty(t, exports)
// verify idempotence
ok, resp = c.DeleteExport(exportName)
require.Nil(t, resp.Error)
require.True(t, ok)
_, err = c.DeleteExport(exportName)
require.NoError(t, err)
}, "successfully delete export")
}
@ -128,9 +125,9 @@ func TestDownloadExport(t *testing.T) {
t.Run("no permissions", func(t *testing.T) {
var buf bytes.Buffer
n, resp := th.Client.DownloadExport("export.zip", &buf, 0)
require.NotNil(t, resp.Error)
require.Equal(t, "api.context.permissions.app_error", resp.Error.Id)
n, _, err := th.Client.DownloadExport("export.zip", &buf, 0)
require.Error(t, err)
CheckErrorID(t, err, "api.context.permissions.app_error")
require.Zero(t, n)
})
@ -140,9 +137,9 @@ func TestDownloadExport(t *testing.T) {
th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) {
var buf bytes.Buffer
n, resp := c.DownloadExport("export.zip", &buf, 0)
require.NotNil(t, resp.Error)
require.Equal(t, "api.export.export_not_found.app_error", resp.Error.Id)
n, _, err := c.DownloadExport("export.zip", &buf, 0)
require.Error(t, err)
CheckErrorID(t, err, "api.export.export_not_found.app_error")
require.Zero(t, n)
}, "not found")
@ -157,8 +154,8 @@ func TestDownloadExport(t *testing.T) {
err = ioutil.WriteFile(filepath.Join(exportDir, exportName), data, 0600)
require.NoError(t, err)
n, resp := c.DownloadExport(exportName, &buf, 0)
require.Nil(t, resp.Error)
n, _, err := c.DownloadExport(exportName, &buf, 0)
require.NoError(t, err)
require.Equal(t, len(data), int(n))
require.Equal(t, data, buf.Bytes())
}, "full download")
@ -175,8 +172,8 @@ func TestDownloadExport(t *testing.T) {
require.NoError(t, err)
offset := 1024 * 512
n, resp := c.DownloadExport(exportName, &buf, int64(offset))
require.Nil(t, resp.Error)
n, _, err := c.DownloadExport(exportName, &buf, int64(offset))
require.NoError(t, err)
require.Equal(t, len(data)-offset, int(n))
require.Equal(t, data[offset:], buf.Bytes())
}, "download with offset")

View file

@ -59,7 +59,7 @@ func fileBytes(t *testing.T, path string) []byte {
}
func testDoUploadFileRequest(t testing.TB, c *model.Client4, url string, blob []byte, contentType string,
contentLength int64) (*model.FileUploadResponse, *model.Response) {
contentLength int64) (*model.FileUploadResponse, *model.Response, error) {
req, err := http.NewRequest("POST", c.ApiUrl+c.GetFilesRoute()+url, bytes.NewReader(blob))
require.NoError(t, err)
@ -77,10 +77,10 @@ func testDoUploadFileRequest(t testing.TB, c *model.Client4, url string, blob []
defer closeBody(resp)
if resp.StatusCode >= 300 {
return nil, model.BuildErrorResponse(resp, model.AppErrorFromJson(resp.Body))
return nil, model.BuildResponse(resp), model.AppErrorFromJson(resp.Body)
}
return model.FileUploadResponseFromJson(resp.Body), model.BuildResponse(resp)
return model.FileUploadResponseFromJson(resp.Body), model.BuildResponse(resp), nil
}
func testUploadFilesPost(
@ -91,7 +91,7 @@ func testUploadFilesPost(
blobs [][]byte,
clientIds []string,
useChunked bool,
) (*model.FileUploadResponse, *model.Response) {
) (*model.FileUploadResponse, *model.Response, error) {
// Do not check len(clientIds), leave it entirely to the user to
// provide. The server will error out if it does not match the number
@ -116,9 +116,9 @@ func testUploadFilesPost(
postURL += fmt.Sprintf("&client_id=%v", url.QueryEscape(clientIds[i]))
}
fur, resp := testDoUploadFileRequest(t, c, postURL, blob, ct, cl)
if resp.Error != nil {
return nil, resp
fur, resp, err := testDoUploadFileRequest(t, c, postURL, blob, ct, cl)
if err != nil {
return nil, resp, err
}
fileUploadResponse.FileInfos = append(fileUploadResponse.FileInfos, fur.FileInfos[0])
@ -131,7 +131,7 @@ func testUploadFilesPost(
}
}
return fileUploadResponse, nil
return fileUploadResponse, nil, nil
}
func testUploadFilesMultipart(
@ -142,8 +142,9 @@ func testUploadFilesMultipart(
blobs [][]byte,
clientIds []string,
) (
fileUploadResponse *model.FileUploadResponse,
response *model.Response,
*model.FileUploadResponse,
*model.Response,
error,
) {
// Do not check len(clientIds), leave it entirely to the user to
// provide. The server will error out if it does not match the number
@ -171,7 +172,8 @@ func testUploadFilesMultipart(
h.Set("Content-Type", ct)
// If we error here, writing to mw, the deferred handler
part, err := mw.CreatePart(h)
var part io.Writer
part, err = mw.CreatePart(h)
require.NoError(t, err)
_, err = io.Copy(part, bytes.NewReader(blob))
@ -179,7 +181,12 @@ func testUploadFilesMultipart(
}
require.NoError(t, mw.Close())
return testDoUploadFileRequest(t, c, "", mwBody.Bytes(), mw.FormDataContentType(), -1)
fur, resp, err := testDoUploadFileRequest(t, c, "", mwBody.Bytes(), mw.FormDataContentType(), -1)
if err != nil {
return nil, resp, err
}
return fur, resp, nil
}
func TestUploadFiles(t *testing.T) {
@ -603,18 +610,17 @@ func TestUploadFiles(t *testing.T) {
var fileResp *model.FileUploadResponse
var resp *model.Response
var err error
if useMultipart {
fileResp, resp = testUploadFilesMultipart(t, client, channelId, tc.names, blobs, tc.clientIds)
fileResp, resp, err = testUploadFilesMultipart(t, client, channelId, tc.names, blobs, tc.clientIds)
} else {
fileResp, resp = testUploadFilesPost(t, client, channelId, tc.names, blobs, tc.clientIds, tc.useChunkedInSimplePost)
fileResp, resp, err = testUploadFilesPost(t, client, channelId, tc.names, blobs, tc.clientIds, tc.useChunkedInSimplePost)
}
if tc.checkResponse != nil {
tc.checkResponse(t, resp)
} else {
if resp != nil {
require.Nil(t, resp.Error)
}
require.NoError(t, err)
}
if tc.skipSuccessValidation {
return
@ -674,10 +680,9 @@ func TestUploadFiles(t *testing.T) {
}
if !tc.skipPayloadValidation {
compare := func(get func(string) ([]byte, *model.Response), name string) {
data, resp := get(ri.Id)
require.NotNil(t, resp)
require.Nil(t, resp.Error)
compare := func(get func(string) ([]byte, *model.Response, error), name string) {
data, _, err := get(ri.Id)
require.NoError(t, err)
expected, err := ioutil.ReadFile(filepath.Join(testDir, name))
require.NoError(t, err)
@ -714,7 +719,7 @@ func TestUploadFiles(t *testing.T) {
func TestGetFile(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
channel := th.BasicChannel
if *th.App.Config().FileSettings.DriverName == "" {
@ -724,38 +729,41 @@ func TestGetFile(t *testing.T) {
sent, err := testutils.ReadTestFile("test.png")
require.NoError(t, err)
fileResp, resp := Client.UploadFile(sent, channel.Id, "test.png")
CheckNoError(t, resp)
fileResp, _, err := client.UploadFile(sent, channel.Id, "test.png")
require.NoError(t, err)
fileId := fileResp.FileInfos[0].Id
data, resp := Client.GetFile(fileId)
CheckNoError(t, resp)
data, _, err := client.GetFile(fileId)
require.NoError(t, err)
require.NotEqual(t, 0, len(data), "should not be empty")
for i := range data {
require.Equal(t, sent[i], data[i], "received file didn't match sent one")
}
_, resp = Client.GetFile("junk")
_, resp, err := client.GetFile("junk")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = Client.GetFile(model.NewId())
_, resp, err = client.GetFile(model.NewId())
require.Error(t, err)
CheckNotFoundStatus(t, resp)
Client.Logout()
_, resp = Client.GetFile(fileId)
client.Logout()
_, resp, err = client.GetFile(fileId)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
_, resp = th.SystemAdminClient.GetFile(fileId)
CheckNoError(t, resp)
_, _, err = th.SystemAdminClient.GetFile(fileId)
require.NoError(t, err)
}
func TestGetFileHeaders(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
channel := th.BasicChannel
if *th.App.Config().FileSettings.DriverName == "" {
@ -764,13 +772,13 @@ func TestGetFileHeaders(t *testing.T) {
testHeaders := func(data []byte, filename string, expectedContentType string, getInline bool) func(*testing.T) {
return func(t *testing.T) {
fileResp, resp := Client.UploadFile(data, channel.Id, filename)
CheckNoError(t, resp)
fileResp, _, err := client.UploadFile(data, channel.Id, filename)
require.NoError(t, err)
fileId := fileResp.FileInfos[0].Id
_, resp = Client.GetFile(fileId)
CheckNoError(t, resp)
_, resp, err := client.GetFile(fileId)
require.NoError(t, err)
CheckStartsWith(t, resp.Header.Get("Content-Type"), expectedContentType, "returned incorrect Content-Type")
@ -780,8 +788,8 @@ func TestGetFileHeaders(t *testing.T) {
CheckStartsWith(t, resp.Header.Get("Content-Disposition"), "attachment", "returned incorrect Content-Disposition")
}
_, resp = Client.DownloadFile(fileId, true)
CheckNoError(t, resp)
_, resp, err = client.DownloadFile(fileId, true)
require.NoError(t, err)
CheckStartsWith(t, resp.Header.Get("Content-Type"), expectedContentType, "returned incorrect Content-Type")
CheckStartsWith(t, resp.Header.Get("Content-Disposition"), "attachment", "returned incorrect Content-Disposition")
@ -809,7 +817,7 @@ func TestGetFileHeaders(t *testing.T) {
func TestGetFileThumbnail(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
channel := th.BasicChannel
if *th.App.Config().FileSettings.DriverName == "" {
@ -819,39 +827,43 @@ func TestGetFileThumbnail(t *testing.T) {
sent, err := testutils.ReadTestFile("test.png")
require.NoError(t, err)
fileResp, resp := Client.UploadFile(sent, channel.Id, "test.png")
CheckNoError(t, resp)
fileResp, _, err := client.UploadFile(sent, channel.Id, "test.png")
require.NoError(t, err)
fileId := fileResp.FileInfos[0].Id
data, resp := Client.GetFileThumbnail(fileId)
CheckNoError(t, resp)
data, _, err := client.GetFileThumbnail(fileId)
require.NoError(t, err)
require.NotEqual(t, 0, len(data), "should not be empty")
_, resp = Client.GetFileThumbnail("junk")
_, resp, err := client.GetFileThumbnail("junk")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = Client.GetFileThumbnail(model.NewId())
_, resp, err = client.GetFileThumbnail(model.NewId())
require.Error(t, err)
CheckNotFoundStatus(t, resp)
Client.Logout()
_, resp = Client.GetFileThumbnail(fileId)
client.Logout()
_, resp, err = client.GetFileThumbnail(fileId)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
otherUser := th.CreateUser()
Client.Login(otherUser.Email, otherUser.Password)
_, resp = Client.GetFileThumbnail(fileId)
client.Login(otherUser.Email, otherUser.Password)
_, resp, err = client.GetFileThumbnail(fileId)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
Client.Logout()
_, resp = th.SystemAdminClient.GetFileThumbnail(fileId)
CheckNoError(t, resp)
client.Logout()
_, _, err = th.SystemAdminClient.GetFileThumbnail(fileId)
require.NoError(t, err)
}
func TestGetFileLink(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
channel := th.BasicChannel
if *th.App.Config().FileSettings.DriverName == "" {
@ -864,12 +876,13 @@ func TestGetFileLink(t *testing.T) {
data, err := testutils.ReadTestFile("test.png")
require.NoError(t, err)
fileResp, uploadResp := Client.UploadFile(data, channel.Id, "test.png")
CheckNoError(t, uploadResp)
fileResp, _, err := client.UploadFile(data, channel.Id, "test.png")
require.NoError(t, err)
fileId := fileResp.FileInfos[0].Id
_, resp := Client.GetFileLink(fileId)
_, resp, err := client.GetFileLink(fileId)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
// Hacky way to assign file to a post (usually would be done by CreatePost call)
@ -877,32 +890,37 @@ func TestGetFileLink(t *testing.T) {
require.NoError(t, err)
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.EnablePublicLink = false })
_, resp = Client.GetFileLink(fileId)
_, resp, err = client.GetFileLink(fileId)
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.EnablePublicLink = true })
link, resp := Client.GetFileLink(fileId)
CheckNoError(t, resp)
link, _, err := client.GetFileLink(fileId)
require.NoError(t, err)
require.NotEqual(t, "", link, "should've received public link")
_, resp = Client.GetFileLink("junk")
_, resp, err = client.GetFileLink("junk")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = Client.GetFileLink(model.NewId())
_, resp, err = client.GetFileLink(model.NewId())
require.Error(t, err)
CheckNotFoundStatus(t, resp)
Client.Logout()
_, resp = Client.GetFileLink(fileId)
client.Logout()
_, resp, err = client.GetFileLink(fileId)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
otherUser := th.CreateUser()
Client.Login(otherUser.Email, otherUser.Password)
_, resp = Client.GetFileLink(fileId)
client.Login(otherUser.Email, otherUser.Password)
_, resp, err = client.GetFileLink(fileId)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
Client.Logout()
_, resp = th.SystemAdminClient.GetFileLink(fileId)
CheckNoError(t, resp)
client.Logout()
_, _, err = th.SystemAdminClient.GetFileLink(fileId)
require.NoError(t, err)
fileInfo, err := th.App.Srv().Store.FileInfo().Get(fileId)
require.NoError(t, err)
@ -912,7 +930,7 @@ func TestGetFileLink(t *testing.T) {
func TestGetFilePreview(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
channel := th.BasicChannel
if *th.App.Config().FileSettings.DriverName == "" {
@ -922,38 +940,42 @@ func TestGetFilePreview(t *testing.T) {
sent, err := testutils.ReadTestFile("test.png")
require.NoError(t, err)
fileResp, resp := Client.UploadFile(sent, channel.Id, "test.png")
CheckNoError(t, resp)
fileResp, _, err := client.UploadFile(sent, channel.Id, "test.png")
require.NoError(t, err)
fileId := fileResp.FileInfos[0].Id
data, resp := Client.GetFilePreview(fileId)
CheckNoError(t, resp)
data, _, err := client.GetFilePreview(fileId)
require.NoError(t, err)
require.NotEqual(t, 0, len(data), "should not be empty")
_, resp = Client.GetFilePreview("junk")
_, resp, err := client.GetFilePreview("junk")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = Client.GetFilePreview(model.NewId())
_, resp, err = client.GetFilePreview(model.NewId())
require.Error(t, err)
CheckNotFoundStatus(t, resp)
Client.Logout()
_, resp = Client.GetFilePreview(fileId)
client.Logout()
_, resp, err = client.GetFilePreview(fileId)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
otherUser := th.CreateUser()
Client.Login(otherUser.Email, otherUser.Password)
_, resp = Client.GetFilePreview(fileId)
client.Login(otherUser.Email, otherUser.Password)
_, resp, err = client.GetFilePreview(fileId)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
Client.Logout()
_, resp = th.SystemAdminClient.GetFilePreview(fileId)
CheckNoError(t, resp)
client.Logout()
_, _, err = th.SystemAdminClient.GetFilePreview(fileId)
require.NoError(t, err)
}
func TestGetFileInfo(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
user := th.BasicUser
channel := th.BasicChannel
@ -964,12 +986,12 @@ func TestGetFileInfo(t *testing.T) {
sent, err := testutils.ReadTestFile("test.png")
require.NoError(t, err)
fileResp, resp := Client.UploadFile(sent, channel.Id, "test.png")
CheckNoError(t, resp)
fileResp, _, err := client.UploadFile(sent, channel.Id, "test.png")
require.NoError(t, err)
fileId := fileResp.FileInfos[0].Id
info, resp := Client.GetFileInfo(fileId)
CheckNoError(t, resp)
info, _, err := client.GetFileInfo(fileId)
require.NoError(t, err)
require.NoError(t, err)
require.Equal(t, fileId, info.Id, "got incorrect file")
@ -980,30 +1002,34 @@ func TestGetFileInfo(t *testing.T) {
require.Equal(t, "", info.PreviewPath, "file preview path shouldn't have been returned to client")
require.Equal(t, "image/png", info.MimeType, "mime type should've been image/png")
_, resp = Client.GetFileInfo("junk")
_, resp, err := client.GetFileInfo("junk")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = Client.GetFileInfo(model.NewId())
_, resp, err = client.GetFileInfo(model.NewId())
require.Error(t, err)
CheckNotFoundStatus(t, resp)
Client.Logout()
_, resp = Client.GetFileInfo(fileId)
client.Logout()
_, resp, err = client.GetFileInfo(fileId)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
otherUser := th.CreateUser()
Client.Login(otherUser.Email, otherUser.Password)
_, resp = Client.GetFileInfo(fileId)
client.Login(otherUser.Email, otherUser.Password)
_, resp, err = client.GetFileInfo(fileId)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
Client.Logout()
_, resp = th.SystemAdminClient.GetFileInfo(fileId)
CheckNoError(t, resp)
client.Logout()
_, _, err = th.SystemAdminClient.GetFileInfo(fileId)
require.NoError(t, err)
}
func TestGetPublicFile(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
channel := th.BasicChannel
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.EnablePublicLink = true })
@ -1012,8 +1038,8 @@ func TestGetPublicFile(t *testing.T) {
data, err := testutils.ReadTestFile("test.png")
require.NoError(t, err)
fileResp, httpResp := Client.UploadFile(data, channel.Id, "test.png")
CheckNoError(t, httpResp)
fileResp, _, err := client.UploadFile(data, channel.Id, "test.png")
require.NoError(t, err)
fileId := fileResp.FileInfos[0].Id
@ -1023,7 +1049,7 @@ func TestGetPublicFile(t *testing.T) {
info, err := th.App.Srv().Store.FileInfo().Get(fileId)
require.NoError(t, err)
link := th.App.GeneratePublicLink(Client.Url, info)
link := th.App.GeneratePublicLink(client.Url, info)
resp, err := http.Get(link)
require.NoError(t, err)
@ -1056,7 +1082,7 @@ func TestGetPublicFile(t *testing.T) {
require.NoError(t, th.cleanupTestFile(fileInfo))
th.cleanupTestFile(info)
link = th.App.GeneratePublicLink(Client.Url, info)
link = th.App.GeneratePublicLink(client.Url, info)
resp, err = http.Get(link)
require.NoError(t, err)
require.Equal(t, http.StatusNotFound, resp.StatusCode, "should've failed to get file after it is deleted")
@ -1078,7 +1104,7 @@ func TestSearchFiles(t *testing.T) {
require.NoError(t, err)
th.LoginBasic()
Client := th.Client
client := th.Client
filename := "search for fileInfo1"
fileInfo1, appErr := th.App.UploadFile(th.Context, data, th.BasicChannel.Id, filename)
@ -1108,8 +1134,8 @@ func TestSearchFiles(t *testing.T) {
fileInfo5, appErr := th.App.UploadFile(th.Context, data, archivedChannel.Id, "tagged for fileInfo3")
require.Nil(t, appErr)
post := &model.Post{ChannelId: archivedChannel.Id, Message: model.NewId() + "a"}
rpost, resp := Client.CreatePost(post)
CheckNoError(t, resp)
rpost, _, err := client.CreatePost(post)
require.NoError(t, err)
err = th.App.Srv().Store.FileInfo().AttachToPost(fileInfo5.Id, rpost.Id, th.BasicUser.Id)
require.NoError(t, err)
th.Client.DeleteChannel(archivedChannel.Id)
@ -1122,8 +1148,8 @@ func TestSearchFiles(t *testing.T) {
IsOrSearch: &isOrSearch,
TimeZoneOffset: &timezoneOffset,
}
fileInfos, resp := Client.SearchFilesWithParams(th.BasicTeam.Id, &searchParams)
CheckNoError(t, resp)
fileInfos, _, err := client.SearchFilesWithParams(th.BasicTeam.Id, &searchParams)
require.NoError(t, err)
require.Len(t, fileInfos.Order, 3, "wrong search")
terms = "search"
@ -1136,8 +1162,8 @@ func TestSearchFiles(t *testing.T) {
Page: &page,
PerPage: &perPage,
}
fileInfos2, resp := Client.SearchFilesWithParams(th.BasicTeam.Id, &searchParams)
CheckNoError(t, resp)
fileInfos2, _, err := client.SearchFilesWithParams(th.BasicTeam.Id, &searchParams)
require.NoError(t, err)
// We don't support paging for DB search yet, modify this when we do.
require.Len(t, fileInfos2.Order, 3, "Wrong number of fileInfos")
assert.Equal(t, fileInfos.Order[0], fileInfos2.Order[0])
@ -1151,17 +1177,17 @@ func TestSearchFiles(t *testing.T) {
Page: &page,
PerPage: &perPage,
}
fileInfos2, resp = Client.SearchFilesWithParams(th.BasicTeam.Id, &searchParams)
CheckNoError(t, resp)
fileInfos2, _, err = client.SearchFilesWithParams(th.BasicTeam.Id, &searchParams)
require.NoError(t, err)
// We don't support paging for DB search yet, modify this when we do.
require.Empty(t, fileInfos2.Order, "Wrong number of fileInfos")
fileInfos, resp = Client.SearchFiles(th.BasicTeam.Id, "search", false)
CheckNoError(t, resp)
fileInfos, _, err = client.SearchFiles(th.BasicTeam.Id, "search", false)
require.NoError(t, err)
require.Len(t, fileInfos.Order, 3, "wrong search")
fileInfos, resp = Client.SearchFiles(th.BasicTeam.Id, "fileInfo2", false)
CheckNoError(t, resp)
fileInfos, _, err = client.SearchFiles(th.BasicTeam.Id, "fileInfo2", false)
require.NoError(t, err)
require.Len(t, fileInfos.Order, 1, "wrong number of fileInfos")
require.Equal(t, fileInfo2.Id, fileInfos.Order[0], "wrong search")
@ -1173,35 +1199,39 @@ func TestSearchFiles(t *testing.T) {
TimeZoneOffset: &timezoneOffset,
IncludeDeletedChannels: &includeDeletedChannels,
}
fileInfos, resp = Client.SearchFilesWithParams(th.BasicTeam.Id, &searchParams)
CheckNoError(t, resp)
fileInfos, _, err = client.SearchFilesWithParams(th.BasicTeam.Id, &searchParams)
require.NoError(t, err)
require.Len(t, fileInfos.Order, 3, "wrong search")
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.TeamSettings.ExperimentalViewArchivedChannels = false
})
fileInfos, resp = Client.SearchFilesWithParams(th.BasicTeam.Id, &searchParams)
CheckNoError(t, resp)
fileInfos, _, err = client.SearchFilesWithParams(th.BasicTeam.Id, &searchParams)
require.NoError(t, err)
require.Len(t, fileInfos.Order, 2, "wrong search")
fileInfos, _ = Client.SearchFiles(th.BasicTeam.Id, "*", false)
fileInfos, _, _ = client.SearchFiles(th.BasicTeam.Id, "*", false)
require.Empty(t, fileInfos.Order, "searching for just * shouldn't return any results")
fileInfos, resp = Client.SearchFiles(th.BasicTeam.Id, "fileInfo1 fileInfo2", true)
CheckNoError(t, resp)
fileInfos, _, err = client.SearchFiles(th.BasicTeam.Id, "fileInfo1 fileInfo2", true)
require.NoError(t, err)
require.Len(t, fileInfos.Order, 2, "wrong search results")
_, resp = Client.SearchFiles("junk", "#sgtitlereview", false)
_, resp, err := client.SearchFiles("junk", "#sgtitlereview", false)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = Client.SearchFiles(model.NewId(), "#sgtitlereview", false)
_, resp, err = client.SearchFiles(model.NewId(), "#sgtitlereview", false)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
_, resp = Client.SearchFiles(th.BasicTeam.Id, "", false)
_, resp, err = client.SearchFiles(th.BasicTeam.Id, "", false)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
Client.Logout()
_, resp = Client.SearchFiles(th.BasicTeam.Id, "#sgtitlereview", false)
client.Logout()
_, resp, err = client.SearchFiles(th.BasicTeam.Id, "#sgtitlereview", false)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
}

File diff suppressed because it is too large Load diff

View file

@ -38,21 +38,21 @@ func TestListImports(t *testing.T) {
us.UserId = model.UploadNoUserID
}
u, resp := c.CreateUpload(us)
require.Nil(t, resp.Error)
u, _, err := c.CreateUpload(us)
require.NoError(t, err)
require.NotNil(t, u)
finfo, resp := c.UploadData(u.Id, file)
require.Nil(t, resp.Error)
finfo, _, err := c.UploadData(u.Id, file)
require.NoError(t, err)
require.NotNil(t, finfo)
return u.Id
}
t.Run("no permissions", func(t *testing.T) {
imports, resp := th.Client.ListImports()
require.NotNil(t, resp.Error)
require.Equal(t, "api.context.permissions.app_error", resp.Error.Id)
imports, _, err := th.Client.ListImports()
require.Error(t, err)
CheckErrorID(t, err, "api.context.permissions.app_error")
require.Nil(t, imports)
})
@ -60,8 +60,8 @@ func TestListImports(t *testing.T) {
require.True(t, found)
th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) {
imports, resp := c.ListImports()
require.Nil(t, resp.Error)
imports, _, err := c.ListImports()
require.NoError(t, err)
require.Empty(t, imports)
}, "no imports")
@ -74,8 +74,8 @@ func TestListImports(t *testing.T) {
require.NoError(t, err)
f.Close()
imports, resp := c.ListImports()
require.Nil(t, resp.Error)
imports, _, err := c.ListImports()
require.NoError(t, err)
require.NotEmpty(t, imports)
require.Len(t, imports, 2)
require.Contains(t, imports, id+"_import_test.zip")
@ -90,13 +90,13 @@ func TestListImports(t *testing.T) {
importDir := filepath.Join(dataDir, "import_new")
imports, resp := c.ListImports()
require.Nil(t, resp.Error)
imports, _, err := c.ListImports()
require.NoError(t, err)
require.Empty(t, imports)
id := uploadNewImport(c, t)
imports, resp = c.ListImports()
require.Nil(t, resp.Error)
imports, _, err = c.ListImports()
require.NoError(t, err)
require.NotEmpty(t, imports)
require.Len(t, imports, 1)
require.Equal(t, id+"_import_test.zip", imports[0])

View file

@ -43,7 +43,7 @@ func (th *testHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
func TestPostActionCookies(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost,127.0.0.1"
@ -127,14 +127,12 @@ func TestPostActionCookies(t *testing.T) {
assert.Equal(t, 32, len(th.App.PostActionCookieSecret()))
post = model.AddPostActionCookies(post, th.App.PostActionCookieSecret())
ok, resp := Client.DoPostActionWithCookie(post.Id, test.Action.Id, "", test.Action.Cookie)
resp, err := client.DoPostActionWithCookie(post.Id, test.Action.Id, "", test.Action.Cookie)
require.NotNil(t, resp)
if test.ExpectedSucess {
assert.True(t, ok)
assert.Nil(t, resp.Error)
assert.NoError(t, err)
} else {
assert.False(t, ok)
assert.NotNil(t, resp.Error)
assert.Error(t, err)
}
assert.Equal(t, test.ExpectedStatusCode, resp.StatusCode)
assert.NotNil(t, resp.RequestId)
@ -146,14 +144,14 @@ func TestPostActionCookies(t *testing.T) {
func TestOpenDialog(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost,127.0.0.1"
})
_, triggerId, err := model.GenerateTriggerId(th.BasicUser.Id, th.App.AsymmetricSigningKey())
require.Nil(t, err)
_, triggerId, appErr := model.GenerateTriggerId(th.BasicUser.Id, th.App.AsymmetricSigningKey())
require.Nil(t, appErr)
request := model.OpenDialogRequest{
TriggerId: triggerId,
@ -175,51 +173,47 @@ func TestOpenDialog(t *testing.T) {
},
}
pass, resp := Client.OpenInteractiveDialog(request)
CheckNoError(t, resp)
assert.True(t, pass)
_, err := client.OpenInteractiveDialog(request)
require.NoError(t, err)
// Should fail on bad trigger ID
request.TriggerId = "junk"
pass, resp = Client.OpenInteractiveDialog(request)
resp, err := client.OpenInteractiveDialog(request)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
assert.False(t, pass)
// URL is required
request.TriggerId = triggerId
request.URL = ""
pass, resp = Client.OpenInteractiveDialog(request)
resp, err = client.OpenInteractiveDialog(request)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
assert.False(t, pass)
// Should pass with markdown formatted introduction text
request.URL = "http://localhost:8065"
request.Dialog.IntroductionText = "**Some** _introduction text"
pass, resp = Client.OpenInteractiveDialog(request)
CheckNoError(t, resp)
assert.True(t, pass)
_, err = client.OpenInteractiveDialog(request)
require.NoError(t, err)
// Should pass with empty introduction text
request.Dialog.IntroductionText = ""
pass, resp = Client.OpenInteractiveDialog(request)
CheckNoError(t, resp)
assert.True(t, pass)
_, err = client.OpenInteractiveDialog(request)
require.NoError(t, err)
// Should pass with no elements
request.Dialog.Elements = nil
pass, resp = Client.OpenInteractiveDialog(request)
CheckNoError(t, resp)
assert.True(t, pass)
_, err = client.OpenInteractiveDialog(request)
require.NoError(t, err)
request.Dialog.Elements = []model.DialogElement{}
pass, resp = Client.OpenInteractiveDialog(request)
CheckNoError(t, resp)
assert.True(t, pass)
_, err = client.OpenInteractiveDialog(request)
require.NoError(t, err)
}
func TestSubmitDialog(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
th.App.UpdateConfig(func(cfg *model.Config) {
*cfg.ServiceSettings.AllowedUntrustedInternalConnections = "localhost,127.0.0.1"
@ -253,25 +247,28 @@ func TestSubmitDialog(t *testing.T) {
submit.URL = ts.URL
submitResp, resp := Client.SubmitInteractiveDialog(submit)
CheckNoError(t, resp)
submitResp, _, err := client.SubmitInteractiveDialog(submit)
require.NoError(t, err)
assert.NotNil(t, submitResp)
submit.URL = ""
submitResp, resp = Client.SubmitInteractiveDialog(submit)
submitResp, resp, err := client.SubmitInteractiveDialog(submit)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
assert.Nil(t, submitResp)
submit.URL = ts.URL
submit.ChannelId = model.NewId()
submitResp, resp = Client.SubmitInteractiveDialog(submit)
submitResp, resp, err = client.SubmitInteractiveDialog(submit)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
assert.Nil(t, submitResp)
submit.URL = ts.URL
submit.ChannelId = th.BasicChannel.Id
submit.TeamId = model.NewId()
submitResp, resp = Client.SubmitInteractiveDialog(submit)
submitResp, resp, err = client.SubmitInteractiveDialog(submit)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
assert.Nil(t, submitResp)
}

View file

@ -25,11 +25,12 @@ func TestCreateJob(t *testing.T) {
},
}
_, resp := th.SystemManagerClient.CreateJob(job)
_, resp, err := th.SystemManagerClient.CreateJob(job)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
received, resp := th.SystemAdminClient.CreateJob(job)
require.Nil(t, resp.Error)
received, _, err := th.SystemAdminClient.CreateJob(job)
require.NoError(t, err)
defer th.App.Srv().Store.Job().Delete(received.Id)
@ -37,11 +38,13 @@ func TestCreateJob(t *testing.T) {
Type: model.NewId(),
}
_, resp = th.SystemAdminClient.CreateJob(job)
_, resp, err = th.SystemAdminClient.CreateJob(job)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
job.Type = model.JobTypeElasticsearchPostIndexing
_, resp = th.Client.CreateJob(job)
_, resp, err = th.Client.CreateJob(job)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
}
@ -59,19 +62,22 @@ func TestGetJob(t *testing.T) {
defer th.App.Srv().Store.Job().Delete(job.Id)
received, resp := th.SystemAdminClient.GetJob(job.Id)
require.Nil(t, resp.Error)
received, _, err := th.SystemAdminClient.GetJob(job.Id)
require.NoError(t, err)
require.Equal(t, job.Id, received.Id, "incorrect job received")
require.Equal(t, job.Status, received.Status, "incorrect job received")
_, resp = th.SystemAdminClient.GetJob("1234")
_, resp, err := th.SystemAdminClient.GetJob("1234")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = th.Client.GetJob(job.Id)
_, resp, err = th.Client.GetJob(job.Id)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
_, resp = th.SystemAdminClient.GetJob(model.NewId())
_, resp, err = th.SystemAdminClient.GetJob(model.NewId())
require.Error(t, err)
CheckNotFoundStatus(t, resp)
}
@ -106,19 +112,20 @@ func TestGetJobs(t *testing.T) {
defer th.App.Srv().Store.Job().Delete(job.Id)
}
received, resp := th.SystemAdminClient.GetJobs(0, 2)
require.Nil(t, resp.Error)
received, _, err := th.SystemAdminClient.GetJobs(0, 2)
require.NoError(t, err)
require.Len(t, received, 2, "received wrong number of jobs")
require.Equal(t, jobs[2].Id, received[0].Id, "should've received newest job first")
require.Equal(t, jobs[0].Id, received[1].Id, "should've received second newest job second")
received, resp = th.SystemAdminClient.GetJobs(1, 2)
require.Nil(t, resp.Error)
received, _, err = th.SystemAdminClient.GetJobs(1, 2)
require.NoError(t, err)
require.Equal(t, jobs[1].Id, received[0].Id, "should've received oldest job last")
_, resp = th.Client.GetJobs(0, 60)
_, resp, err := th.Client.GetJobs(0, 60)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
}
@ -157,30 +164,33 @@ func TestGetJobsByType(t *testing.T) {
defer th.App.Srv().Store.Job().Delete(job.Id)
}
received, resp := th.SystemAdminClient.GetJobsByType(jobType, 0, 2)
require.Nil(t, resp.Error)
received, _, err := th.SystemAdminClient.GetJobsByType(jobType, 0, 2)
require.NoError(t, err)
require.Len(t, received, 2, "received wrong number of jobs")
require.Equal(t, jobs[2].Id, received[0].Id, "should've received newest job first")
require.Equal(t, jobs[0].Id, received[1].Id, "should've received second newest job second")
received, resp = th.SystemAdminClient.GetJobsByType(jobType, 1, 2)
require.Nil(t, resp.Error)
received, _, err = th.SystemAdminClient.GetJobsByType(jobType, 1, 2)
require.NoError(t, err)
require.Len(t, received, 1, "received wrong number of jobs")
require.Equal(t, jobs[1].Id, received[0].Id, "should've received oldest job last")
_, resp = th.SystemAdminClient.GetJobsByType("", 0, 60)
_, resp, err := th.SystemAdminClient.GetJobsByType("", 0, 60)
require.Error(t, err)
CheckNotFoundStatus(t, resp)
_, resp = th.SystemAdminClient.GetJobsByType(strings.Repeat("a", 33), 0, 60)
_, resp, err = th.SystemAdminClient.GetJobsByType(strings.Repeat("a", 33), 0, 60)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = th.Client.GetJobsByType(jobType, 0, 60)
_, resp, err = th.Client.GetJobsByType(jobType, 0, 60)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
_, resp = th.SystemManagerClient.GetJobsByType(model.JobTypeElasticsearchPostIndexing, 0, 60)
require.Nil(t, resp.Error)
_, _, err = th.SystemManagerClient.GetJobsByType(model.JobTypeElasticsearchPostIndexing, 0, 60)
require.NoError(t, err)
}
func TestDownloadJob(t *testing.T) {
@ -197,7 +207,8 @@ func TestDownloadJob(t *testing.T) {
}
// DownloadExportResults is not set to true so we should get a not implemented error status
_, resp := th.Client.DownloadJob(job.Id)
_, resp, err := th.Client.DownloadJob(job.Id)
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
th.App.UpdateConfig(func(cfg *model.Config) {
@ -205,16 +216,18 @@ func TestDownloadJob(t *testing.T) {
})
// Normal user cannot download the results of these job (non-existent job)
_, resp = th.Client.DownloadJob(job.Id)
_, resp, err = th.Client.DownloadJob(job.Id)
require.Error(t, err)
CheckNotFoundStatus(t, resp)
// System admin trying to download the results of a non-existent job
_, resp = th.SystemAdminClient.DownloadJob(job.Id)
_, resp, err = th.SystemAdminClient.DownloadJob(job.Id)
require.Error(t, err)
CheckNotFoundStatus(t, resp)
// Here we have a job that exist in our database but the results do not exist therefore when we try to download the results
// as a system admin, we should get a not found status.
_, err := th.App.Srv().Store.Job().Save(job)
_, err = th.App.Srv().Store.Job().Save(job)
require.NoError(t, err)
defer th.App.Srv().Store.Job().Delete(job.Id)
@ -224,14 +237,17 @@ func TestDownloadJob(t *testing.T) {
os.Create(filePath)
// Normal user cannot download the results of these job (not the right permission)
_, resp = th.Client.DownloadJob(job.Id)
_, resp, err = th.Client.DownloadJob(job.Id)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
th.SystemManagerClient.DownloadJob(job.Id)
// System manager with default permissions cannot download the results of these job (Doesn't have correct permissions)
_, resp = th.SystemManagerClient.DownloadJob(job.Id)
_, resp, err = th.SystemManagerClient.DownloadJob(job.Id)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
_, resp = th.SystemAdminClient.DownloadJob(job.Id)
_, resp, err = th.SystemAdminClient.DownloadJob(job.Id)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
job.Data["is_downloadable"] = "true"
@ -239,7 +255,8 @@ func TestDownloadJob(t *testing.T) {
require.True(t, updateStatus)
require.NoError(t, err)
_, resp = th.SystemAdminClient.DownloadJob(job.Id)
_, resp, err = th.SystemAdminClient.DownloadJob(job.Id)
require.Error(t, err)
CheckNotFoundStatus(t, resp)
// Now we stub the results of the job into the same directory and try to download it again
@ -249,8 +266,8 @@ func TestDownloadJob(t *testing.T) {
require.NoError(t, mkdirAllErr)
os.Create(filePath)
_, resp = th.SystemAdminClient.DownloadJob(job.Id)
require.Nil(t, resp.Error)
_, _, err = th.SystemAdminClient.DownloadJob(job.Id)
require.NoError(t, err)
// Here we are creating a new job which doesn't have type of message export
jobName = model.NewId()
@ -267,7 +284,8 @@ func TestDownloadJob(t *testing.T) {
defer th.App.Srv().Store.Job().Delete(job.Id)
// System admin shouldn't be able to download since the job type is not message export
_, resp = th.SystemAdminClient.DownloadJob(job.Id)
_, resp, err = th.SystemAdminClient.DownloadJob(job.Id)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
}
@ -300,18 +318,21 @@ func TestCancelJob(t *testing.T) {
defer th.App.Srv().Store.Job().Delete(job.Id)
}
_, resp := th.Client.CancelJob(jobs[0].Id)
resp, err := th.Client.CancelJob(jobs[0].Id)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
_, resp = th.SystemAdminClient.CancelJob(jobs[0].Id)
require.Nil(t, resp.Error)
_, err = th.SystemAdminClient.CancelJob(jobs[0].Id)
require.NoError(t, err)
_, resp = th.SystemAdminClient.CancelJob(jobs[1].Id)
require.Nil(t, resp.Error)
_, err = th.SystemAdminClient.CancelJob(jobs[1].Id)
require.NoError(t, err)
_, resp = th.SystemAdminClient.CancelJob(jobs[2].Id)
resp, err = th.SystemAdminClient.CancelJob(jobs[2].Id)
require.Error(t, err)
CheckInternalErrorStatus(t, resp)
_, resp = th.SystemAdminClient.CancelJob(model.NewId())
resp, err = th.SystemAdminClient.CancelJob(model.NewId())
require.Error(t, err)
CheckNotFoundStatus(t, resp)
}

View file

@ -104,23 +104,24 @@ func TestTestLdap(t *testing.T) {
defer th.TearDown()
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
_, resp := client.TestLdap()
resp, err := client.TestLdap()
CheckNotImplementedStatus(t, resp)
require.NotNil(t, resp.Error)
require.Equal(t, "api.ldap_groups.license_error", resp.Error.Id)
require.Error(t, err)
CheckErrorID(t, err, "api.ldap_groups.license_error")
})
th.App.Srv().SetLicense(model.NewTestLicense("ldap_groups"))
_, resp := th.Client.TestLdap()
resp, err := th.Client.TestLdap()
CheckForbiddenStatus(t, resp)
require.NotNil(t, resp.Error)
require.Equal(t, "api.context.permissions.app_error", resp.Error.Id)
require.Error(t, err)
CheckErrorID(t, err, "api.context.permissions.app_error")
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
_, resp = client.TestLdap()
resp, err = client.TestLdap()
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
require.NotNil(t, resp.Error)
require.Equal(t, "ent.ldap.disabled.app_error", resp.Error.Id)
require.Error(t, err)
CheckErrorID(t, err, "ent.ldap.disabled.app_error")
})
}
@ -129,10 +130,10 @@ func TestSyncLdap(t *testing.T) {
defer th.TearDown()
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
_, resp := client.TestLdap()
resp, err := client.TestLdap()
CheckNotImplementedStatus(t, resp)
require.NotNil(t, resp.Error)
require.Equal(t, "api.ldap_groups.license_error", resp.Error.Id)
require.Error(t, err)
CheckErrorID(t, err, "api.ldap_groups.license_error")
})
th.App.Srv().SetLicense(model.NewTestLicense("ldap_groups"))
@ -155,18 +156,19 @@ func TestSyncLdap(t *testing.T) {
th.App.Srv().Ldap = ldapMock
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
_, resp := client.SyncLdap(false)
_, err := client.SyncLdap(false)
<-ready
CheckNoError(t, resp)
require.Equal(t, false, includeRemovedMembers)
require.NoError(t, err)
require.False(t, includeRemovedMembers)
_, resp = client.SyncLdap(true)
_, err = client.SyncLdap(true)
<-ready
CheckNoError(t, resp)
require.Equal(t, true, includeRemovedMembers)
require.NoError(t, err)
require.True(t, includeRemovedMembers)
})
_, resp := th.Client.SyncLdap(false)
resp, err := th.Client.SyncLdap(false)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
}
@ -174,11 +176,13 @@ func TestGetLdapGroups(t *testing.T) {
th := Setup(t)
defer th.TearDown()
_, resp := th.Client.GetLdapGroups()
_, resp, err := th.Client.GetLdapGroups()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
_, resp := client.GetLdapGroups()
_, resp, err := client.GetLdapGroups()
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
})
}
@ -189,10 +193,12 @@ func TestLinkLdapGroup(t *testing.T) {
th := Setup(t)
defer th.TearDown()
_, resp := th.Client.LinkLdapGroup(entryUUID)
_, resp, err := th.Client.LinkLdapGroup(entryUUID)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
_, resp = th.SystemAdminClient.LinkLdapGroup(entryUUID)
_, resp, err = th.SystemAdminClient.LinkLdapGroup(entryUUID)
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
}
@ -202,10 +208,12 @@ func TestUnlinkLdapGroup(t *testing.T) {
th := Setup(t)
defer th.TearDown()
_, resp := th.Client.UnlinkLdapGroup(entryUUID)
_, resp, err := th.Client.UnlinkLdapGroup(entryUUID)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
_, resp = th.SystemAdminClient.UnlinkLdapGroup(entryUUID)
_, resp, err = th.SystemAdminClient.UnlinkLdapGroup(entryUUID)
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
}
@ -213,14 +221,17 @@ func TestMigrateIdLdap(t *testing.T) {
th := Setup(t)
defer th.TearDown()
_, resp := th.Client.MigrateIdLdap("objectGUID")
resp, err := th.Client.MigrateIdLdap("objectGUID")
require.Error(t, err)
CheckForbiddenStatus(t, resp)
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
_, resp = client.MigrateIdLdap("")
resp, err = client.MigrateIdLdap("")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = client.MigrateIdLdap("objectGUID")
resp, err = client.MigrateIdLdap("objectGUID")
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
})
}
@ -229,20 +240,20 @@ func TestUploadPublicCertificate(t *testing.T) {
th := Setup(t)
defer th.TearDown()
_, resp := th.Client.UploadLdapPublicCertificate([]byte(spPublicCertificate))
require.NotNil(t, resp.Error, "Should have failed. No System Admin privileges")
_, err := th.Client.UploadLdapPublicCertificate([]byte(spPublicCertificate))
require.Error(t, err, "Should have failed. No System Admin privileges")
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
_, resp = client.UploadLdapPublicCertificate([]byte(spPrivateKey))
require.Nil(t, resp.Error, "Should have passed. System Admin privileges %v", resp.Error)
_, err = client.UploadLdapPublicCertificate([]byte(spPrivateKey))
require.NoErrorf(t, err, "Should have passed. System Admin privileges %v", err)
})
_, resp = th.Client.DeleteLdapPublicCertificate()
require.NotNil(t, resp.Error, "Should have failed. No System Admin privileges")
_, err = th.Client.DeleteLdapPublicCertificate()
require.Error(t, err, "Should have failed. No System Admin privileges")
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
_, resp := client.DeleteLdapPublicCertificate()
require.Nil(t, resp.Error, "Should have passed. System Admin privileges %v", resp.Error)
_, err := client.DeleteLdapPublicCertificate()
require.NoError(t, err, "Should have passed. System Admin privileges")
})
}
@ -250,19 +261,19 @@ func TestUploadPrivateCertificate(t *testing.T) {
th := Setup(t)
defer th.TearDown()
_, resp := th.Client.UploadLdapPrivateCertificate([]byte(spPrivateKey))
require.NotNil(t, resp.Error, "Should have failed. No System Admin privileges")
_, err := th.Client.UploadLdapPrivateCertificate([]byte(spPrivateKey))
require.Error(t, err, "Should have failed. No System Admin privileges")
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
_, resp = client.UploadLdapPrivateCertificate([]byte(spPrivateKey))
require.Nil(t, resp.Error, "Should have passed. System Admin privileges %v", resp.Error)
_, err = client.UploadLdapPrivateCertificate([]byte(spPrivateKey))
require.NoErrorf(t, err, "Should have passed. System Admin privileges %v", err)
})
_, resp = th.Client.DeleteLdapPrivateCertificate()
require.NotNil(t, resp.Error, "Should have failed. No System Admin privileges")
_, err = th.Client.DeleteLdapPrivateCertificate()
require.Error(t, err, "Should have failed. No System Admin privileges")
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
_, resp := client.DeleteLdapPrivateCertificate()
require.Nil(t, resp.Error, "Should have passed. System Admin privileges %v", resp.Error)
_, err := client.DeleteLdapPrivateCertificate()
require.NoErrorf(t, err, "Should have passed. System Admin privileges %v", err)
})
}

View file

@ -22,30 +22,30 @@ import (
func TestGetOldClientLicense(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
client := th.Client
license, resp := Client.GetOldClientLicense("")
CheckNoError(t, resp)
license, _, err := client.GetOldClientLicense("")
require.NoError(t, err)
require.NotEqual(t, license["IsLicensed"], "", "license not returned correctly")
Client.Logout()
client.Logout()
_, resp = Client.GetOldClientLicense("")
CheckNoError(t, resp)
_, _, err = client.GetOldClientLicense("")
require.NoError(t, err)
_, err := Client.DoApiGet("/license/client", "")
require.NotNil(t, err, "get /license/client did not return an error")
require.Equal(t, err.StatusCode, http.StatusNotImplemented,
resp, err := client.DoApiGet("/license/client", "")
require.Error(t, err, "get /license/client did not return an error")
require.Equal(t, http.StatusNotImplemented, resp.StatusCode,
"expected 501 Not Implemented")
_, err = Client.DoApiGet("/license/client?format=junk", "")
require.NotNil(t, err, "get /license/client?format=junk did not return an error")
require.Equal(t, err.StatusCode, http.StatusBadRequest,
resp, err = client.DoApiGet("/license/client?format=junk", "")
require.Error(t, err, "get /license/client?format=junk did not return an error")
require.Equal(t, http.StatusBadRequest, resp.StatusCode,
"expected 400 Bad Request")
license, resp = th.SystemAdminClient.GetOldClientLicense("")
CheckNoError(t, resp)
license, _, err = th.SystemAdminClient.GetOldClientLicense("")
require.NoError(t, err)
require.NotEmpty(t, license["IsLicensed"], "license not returned correctly")
}
@ -53,34 +53,34 @@ func TestGetOldClientLicense(t *testing.T) {
func TestUploadLicenseFile(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
client := th.Client
LocalClient := th.LocalClient
t.Run("as system user", func(t *testing.T) {
ok, resp := Client.UploadLicenseFile([]byte{})
resp, err := client.UploadLicenseFile([]byte{})
require.Error(t, err)
CheckForbiddenStatus(t, resp)
require.False(t, ok)
})
th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) {
ok, resp := c.UploadLicenseFile([]byte{})
resp, err := c.UploadLicenseFile([]byte{})
require.Error(t, err)
CheckBadRequestStatus(t, resp)
require.False(t, ok)
}, "as system admin user")
t.Run("as restricted system admin user", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
ok, resp := th.SystemAdminClient.UploadLicenseFile([]byte{})
resp, err := th.SystemAdminClient.UploadLicenseFile([]byte{})
require.Error(t, err)
CheckForbiddenStatus(t, resp)
require.False(t, ok)
})
t.Run("restricted admin setting not honoured through local client", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
ok, resp := LocalClient.UploadLicenseFile([]byte{})
resp, err := LocalClient.UploadLicenseFile([]byte{})
require.Error(t, err)
CheckBadRequestStatus(t, resp)
require.False(t, ok)
})
t.Run("server has already gone through trial", func(t *testing.T) {
@ -117,10 +117,9 @@ func TestUploadLicenseFile(t *testing.T) {
licenseManagerMock.On("CanStartTrial").Return(false, nil).Once()
th.App.Srv().LicenseManager = licenseManagerMock
ok, resp := th.SystemAdminClient.UploadLicenseFile([]byte("sadasdasdasdasdasdsa"))
require.False(t, ok)
resp, err := th.SystemAdminClient.UploadLicenseFile([]byte("sadasdasdasdasdasdsa"))
CheckErrorID(t, err, "api.license.request-trial.can-start-trial.not-allowed")
require.Equal(t, http.StatusBadRequest, resp.StatusCode)
require.Equal(t, "api.license.request-trial.can-start-trial.not-allowed", resp.Error.Id)
})
t.Run("allow uploading sanctioned trials even if server already gone through trial", func(t *testing.T) {
@ -156,45 +155,42 @@ func TestUploadLicenseFile(t *testing.T) {
licenseManagerMock.On("CanStartTrial").Return(false, nil).Once()
th.App.Srv().LicenseManager = licenseManagerMock
ok, resp := th.SystemAdminClient.UploadLicenseFile([]byte("sadasdasdasdasdasdsa"))
require.False(t, ok)
resp, err := th.SystemAdminClient.UploadLicenseFile([]byte("sadasdasdasdasdasdsa"))
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
require.Nil(t, resp.Error)
})
}
func TestRemoveLicenseFile(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
client := th.Client
LocalClient := th.LocalClient
t.Run("as system user", func(t *testing.T) {
ok, resp := Client.RemoveLicenseFile()
resp, err := client.RemoveLicenseFile()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
require.False(t, ok)
})
th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) {
ok, resp := c.RemoveLicenseFile()
CheckNoError(t, resp)
require.True(t, ok)
_, err := c.RemoveLicenseFile()
require.NoError(t, err)
}, "as system admin user")
t.Run("as restricted system admin user", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
ok, resp := th.SystemAdminClient.RemoveLicenseFile()
resp, err := th.SystemAdminClient.RemoveLicenseFile()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
require.False(t, ok)
})
t.Run("restricted admin setting not honoured through local client", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
ok, resp := LocalClient.RemoveLicenseFile()
CheckNoError(t, resp)
require.True(t, ok)
_, err := LocalClient.RemoveLicenseFile()
require.NoError(t, err)
})
}
@ -209,32 +205,29 @@ func TestRequestTrialLicense(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.SiteURL = "http://localhost:8065/" })
t.Run("permission denied", func(t *testing.T) {
ok, resp := th.Client.RequestTrialLicense(1000)
resp, err := th.Client.RequestTrialLicense(1000)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
require.False(t, ok)
})
t.Run("blank site url", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.SiteURL = "" })
defer th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.SiteURL = "http://localhost:8065/" })
ok, resp := th.SystemAdminClient.RequestTrialLicense(1000)
resp, err := th.SystemAdminClient.RequestTrialLicense(1000)
CheckErrorID(t, err, "api.license.request_trial_license.no-site-url.app_error")
CheckBadRequestStatus(t, resp)
require.Equal(t, "api.license.request_trial_license.no-site-url.app_error", resp.Error.Id)
require.False(t, ok)
})
t.Run("trial license user count less than current users", func(t *testing.T) {
ok, resp := th.SystemAdminClient.RequestTrialLicense(1)
resp, err := th.SystemAdminClient.RequestTrialLicense(1)
CheckErrorID(t, err, "api.license.add_license.unique_users.app_error")
CheckBadRequestStatus(t, resp)
require.Equal(t, "api.license.add_license.unique_users.app_error", resp.Error.Id)
require.False(t, ok)
})
th.App.Srv().LicenseManager = nil
t.Run("trial license should fail if LicenseManager is nil", func(t *testing.T) {
ok, resp := th.SystemAdminClient.RequestTrialLicense(1)
resp, err := th.SystemAdminClient.RequestTrialLicense(1)
CheckErrorID(t, err, "api.license.upgrade_needed.app_error")
CheckForbiddenStatus(t, resp)
require.False(t, ok)
require.Equal(t, "api.license.upgrade_needed.app_error", resp.Error.Id)
})
}

View file

@ -17,8 +17,8 @@ import (
func TestCreateOAuthApp(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
AdminClient := th.SystemAdminClient
client := th.Client
adminClient := th.SystemAdminClient
defaultRolePermissions := th.SaveDefaultRolePermissions()
enableOAuthServiceProvider := th.App.Config().ServiceSettings.EnableOAuthServiceProvider
@ -34,8 +34,8 @@ func TestCreateOAuthApp(t *testing.T) {
oapp := &model.OAuthApp{Name: GenerateTestAppName(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}, IsTrusted: true}
rapp, resp := AdminClient.CreateOAuthApp(oapp)
CheckNoError(t, resp)
rapp, resp, err := adminClient.CreateOAuthApp(oapp)
require.NoError(t, err)
CheckCreatedStatus(t, resp)
assert.Equal(t, oapp.Name, rapp.Name, "names did not match")
assert.Equal(t, oapp.IsTrusted, rapp.IsTrusted, "trusted did no match")
@ -43,40 +43,44 @@ func TestCreateOAuthApp(t *testing.T) {
// Revoke permission from regular users.
th.RemovePermissionFromRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId)
_, resp = Client.CreateOAuthApp(oapp)
_, resp, err = client.CreateOAuthApp(oapp)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
// Grant permission to regular users.
th.AddPermissionToRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId)
rapp, resp = Client.CreateOAuthApp(oapp)
CheckNoError(t, resp)
rapp, resp, err = client.CreateOAuthApp(oapp)
require.NoError(t, err)
CheckCreatedStatus(t, resp)
assert.False(t, rapp.IsTrusted, "trusted should be false - created by non admin")
oapp.Name = ""
_, resp = AdminClient.CreateOAuthApp(oapp)
_, resp, err = adminClient.CreateOAuthApp(oapp)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
r, err := Client.DoApiPost("/oauth/apps", "garbage")
require.NotNil(t, err, "expected error from garbage post")
r, err := client.DoApiPost("/oauth/apps", "garbage")
require.Error(t, err, "expected error from garbage post")
assert.Equal(t, http.StatusBadRequest, r.StatusCode)
Client.Logout()
_, resp = Client.CreateOAuthApp(oapp)
client.Logout()
_, resp, err = client.CreateOAuthApp(oapp)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = false })
oapp.Name = GenerateTestAppName()
_, resp = AdminClient.CreateOAuthApp(oapp)
_, resp, err = adminClient.CreateOAuthApp(oapp)
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
}
func TestUpdateOAuthApp(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
AdminClient := th.SystemAdminClient
client := th.Client
adminClient := th.SystemAdminClient
defaultRolePermissions := th.SaveDefaultRolePermissions()
enableOAuthServiceProvider := th.App.Config().ServiceSettings.EnableOAuthServiceProvider
@ -98,7 +102,7 @@ func TestUpdateOAuthApp(t *testing.T) {
CallbackUrls: []string{"https://callback.com"},
}
oapp, _ = AdminClient.CreateOAuthApp(oapp)
oapp, _, _ = adminClient.CreateOAuthApp(oapp)
oapp.Name = "oapp_update"
oapp.IsTrusted = true
@ -107,8 +111,8 @@ func TestUpdateOAuthApp(t *testing.T) {
oapp.Description = "test_update"
oapp.CallbackUrls = []string{"https://callback_update.com", "https://another_callback.com"}
updatedApp, resp := AdminClient.UpdateOAuthApp(oapp)
CheckNoError(t, resp)
updatedApp, _, err := adminClient.UpdateOAuthApp(oapp)
require.NoError(t, err)
assert.Equal(t, oapp.Id, updatedApp.Id, "Id should have not updated")
assert.Equal(t, oapp.CreatorId, updatedApp.CreatorId, "CreatorId should have not updated")
assert.Equal(t, oapp.CreateAt, updatedApp.CreateAt, "CreateAt should have not updated")
@ -128,7 +132,8 @@ func TestUpdateOAuthApp(t *testing.T) {
th.LoginBasic2()
updatedApp.CreatorId = th.BasicUser2.Id
_, resp = Client.UpdateOAuthApp(oapp)
_, resp, err := client.UpdateOAuthApp(oapp)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
th.LoginBasic()
@ -136,24 +141,29 @@ func TestUpdateOAuthApp(t *testing.T) {
// Revoke permission from regular users.
th.RemovePermissionFromRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId)
_, resp = Client.UpdateOAuthApp(oapp)
_, resp, err = client.UpdateOAuthApp(oapp)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
oapp.Id = "zhk9d1ggatrqz236c7h87im7bc"
_, resp = AdminClient.UpdateOAuthApp(oapp)
_, resp, err = adminClient.UpdateOAuthApp(oapp)
require.Error(t, err)
CheckNotFoundStatus(t, resp)
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = false })
_, resp = AdminClient.UpdateOAuthApp(oapp)
_, resp, err = adminClient.UpdateOAuthApp(oapp)
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
Client.Logout()
_, resp = Client.UpdateOAuthApp(oapp)
client.Logout()
_, resp, err = client.UpdateOAuthApp(oapp)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
oapp.Id = "junk"
_, resp = AdminClient.UpdateOAuthApp(oapp)
_, resp, err = adminClient.UpdateOAuthApp(oapp)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = true })
@ -169,30 +179,30 @@ func TestUpdateOAuthApp(t *testing.T) {
CallbackUrls: []string{"https://callback.com"},
}
userOapp, resp = Client.CreateOAuthApp(userOapp)
CheckNoError(t, resp)
userOapp, _, err = client.CreateOAuthApp(userOapp)
require.NoError(t, err)
userOapp.IsTrusted = true
userOapp, resp = Client.UpdateOAuthApp(userOapp)
CheckNoError(t, resp)
userOapp, _, err = client.UpdateOAuthApp(userOapp)
require.NoError(t, err)
assert.False(t, userOapp.IsTrusted)
userOapp.IsTrusted = true
userOapp, resp = AdminClient.UpdateOAuthApp(userOapp)
CheckNoError(t, resp)
userOapp, _, err = adminClient.UpdateOAuthApp(userOapp)
require.NoError(t, err)
assert.True(t, userOapp.IsTrusted)
userOapp.IsTrusted = false
userOapp, resp = Client.UpdateOAuthApp(userOapp)
CheckNoError(t, resp)
userOapp, _, err = client.UpdateOAuthApp(userOapp)
require.NoError(t, err)
assert.True(t, userOapp.IsTrusted)
}
func TestGetOAuthApps(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
AdminClient := th.SystemAdminClient
client := th.Client
adminClient := th.SystemAdminClient
defaultRolePermissions := th.SaveDefaultRolePermissions()
enableOAuthServiceProvider := th.App.Config().ServiceSettings.EnableOAuthServiceProvider
@ -207,15 +217,15 @@ func TestGetOAuthApps(t *testing.T) {
oapp := &model.OAuthApp{Name: GenerateTestAppName(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}}
rapp, resp := AdminClient.CreateOAuthApp(oapp)
CheckNoError(t, resp)
rapp, _, err := adminClient.CreateOAuthApp(oapp)
require.NoError(t, err)
oapp.Name = GenerateTestAppName()
rapp2, resp := Client.CreateOAuthApp(oapp)
CheckNoError(t, resp)
rapp2, _, err := client.CreateOAuthApp(oapp)
require.NoError(t, err)
apps, resp := AdminClient.GetOAuthApps(0, 1000)
CheckNoError(t, resp)
apps, _, err := adminClient.GetOAuthApps(0, 1000)
require.NoError(t, err)
found1 := false
found2 := false
@ -230,35 +240,38 @@ func TestGetOAuthApps(t *testing.T) {
assert.Truef(t, found1, "missing oauth app %v", rapp.Id)
assert.Truef(t, found2, "missing oauth app %v", rapp2.Id)
apps, resp = AdminClient.GetOAuthApps(1, 1)
CheckNoError(t, resp)
apps, _, err = adminClient.GetOAuthApps(1, 1)
require.NoError(t, err)
require.Equal(t, 1, len(apps), "paging failed")
apps, resp = Client.GetOAuthApps(0, 1000)
CheckNoError(t, resp)
apps, _, err = client.GetOAuthApps(0, 1000)
require.NoError(t, err)
require.True(t, len(apps) == 1 || apps[0].Id == rapp2.Id, "wrong apps returned")
// Revoke permission from regular users.
th.RemovePermissionFromRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId)
_, resp = Client.GetOAuthApps(0, 1000)
_, resp, err := client.GetOAuthApps(0, 1000)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
Client.Logout()
client.Logout()
_, resp = Client.GetOAuthApps(0, 1000)
_, resp, err = client.GetOAuthApps(0, 1000)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = false })
_, resp = AdminClient.GetOAuthApps(0, 1000)
_, resp, err = adminClient.GetOAuthApps(0, 1000)
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
}
func TestGetOAuthApp(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
AdminClient := th.SystemAdminClient
client := th.Client
adminClient := th.SystemAdminClient
defaultRolePermissions := th.SaveDefaultRolePermissions()
enableOAuthServiceProvider := th.App.Config().ServiceSettings.EnableOAuthServiceProvider
@ -273,56 +286,62 @@ func TestGetOAuthApp(t *testing.T) {
oapp := &model.OAuthApp{Name: GenerateTestAppName(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}}
rapp, resp := AdminClient.CreateOAuthApp(oapp)
CheckNoError(t, resp)
rapp, _, err := adminClient.CreateOAuthApp(oapp)
require.NoError(t, err)
oapp.Name = GenerateTestAppName()
rapp2, resp := Client.CreateOAuthApp(oapp)
CheckNoError(t, resp)
rapp2, _, err := client.CreateOAuthApp(oapp)
require.NoError(t, err)
rrapp, resp := AdminClient.GetOAuthApp(rapp.Id)
CheckNoError(t, resp)
rrapp, _, err := adminClient.GetOAuthApp(rapp.Id)
require.NoError(t, err)
assert.Equal(t, rapp.Id, rrapp.Id, "wrong app")
assert.NotEqual(t, "", rrapp.ClientSecret, "should not be sanitized")
rrapp2, resp := AdminClient.GetOAuthApp(rapp2.Id)
CheckNoError(t, resp)
rrapp2, _, err := adminClient.GetOAuthApp(rapp2.Id)
require.NoError(t, err)
assert.Equal(t, rapp2.Id, rrapp2.Id, "wrong app")
assert.NotEqual(t, "", rrapp2.ClientSecret, "should not be sanitized")
_, resp = Client.GetOAuthApp(rapp2.Id)
CheckNoError(t, resp)
_, _, err = client.GetOAuthApp(rapp2.Id)
require.NoError(t, err)
_, resp = Client.GetOAuthApp(rapp.Id)
_, resp, err := client.GetOAuthApp(rapp.Id)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
// Revoke permission from regular users.
th.RemovePermissionFromRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId)
_, resp = Client.GetOAuthApp(rapp2.Id)
_, resp, err = client.GetOAuthApp(rapp2.Id)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
Client.Logout()
client.Logout()
_, resp = Client.GetOAuthApp(rapp2.Id)
_, resp, err = client.GetOAuthApp(rapp2.Id)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
_, resp = AdminClient.GetOAuthApp("junk")
_, resp, err = adminClient.GetOAuthApp("junk")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = AdminClient.GetOAuthApp(model.NewId())
_, resp, err = adminClient.GetOAuthApp(model.NewId())
require.Error(t, err)
CheckNotFoundStatus(t, resp)
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = false })
_, resp = AdminClient.GetOAuthApp(rapp.Id)
_, resp, err = adminClient.GetOAuthApp(rapp.Id)
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
}
func TestGetOAuthAppInfo(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
AdminClient := th.SystemAdminClient
client := th.Client
adminClient := th.SystemAdminClient
defaultRolePermissions := th.SaveDefaultRolePermissions()
enableOAuthServiceProvider := th.App.Config().ServiceSettings.EnableOAuthServiceProvider
@ -337,56 +356,60 @@ func TestGetOAuthAppInfo(t *testing.T) {
oapp := &model.OAuthApp{Name: GenerateTestAppName(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}}
rapp, resp := AdminClient.CreateOAuthApp(oapp)
CheckNoError(t, resp)
rapp, _, err := adminClient.CreateOAuthApp(oapp)
require.NoError(t, err)
oapp.Name = GenerateTestAppName()
rapp2, resp := Client.CreateOAuthApp(oapp)
CheckNoError(t, resp)
rapp2, _, err := client.CreateOAuthApp(oapp)
require.NoError(t, err)
rrapp, resp := AdminClient.GetOAuthAppInfo(rapp.Id)
CheckNoError(t, resp)
rrapp, _, err := adminClient.GetOAuthAppInfo(rapp.Id)
require.NoError(t, err)
assert.Equal(t, rapp.Id, rrapp.Id, "wrong app")
assert.Equal(t, "", rrapp.ClientSecret, "should be sanitized")
rrapp2, resp := AdminClient.GetOAuthAppInfo(rapp2.Id)
CheckNoError(t, resp)
rrapp2, _, err := adminClient.GetOAuthAppInfo(rapp2.Id)
require.NoError(t, err)
assert.Equal(t, rapp2.Id, rrapp2.Id, "wrong app")
assert.Equal(t, "", rrapp2.ClientSecret, "should be sanitized")
_, resp = Client.GetOAuthAppInfo(rapp2.Id)
CheckNoError(t, resp)
_, _, err = client.GetOAuthAppInfo(rapp2.Id)
require.NoError(t, err)
_, resp = Client.GetOAuthAppInfo(rapp.Id)
CheckNoError(t, resp)
_, _, err = client.GetOAuthAppInfo(rapp.Id)
require.NoError(t, err)
// Revoke permission from regular users.
th.RemovePermissionFromRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId)
_, resp = Client.GetOAuthAppInfo(rapp2.Id)
CheckNoError(t, resp)
_, _, err = client.GetOAuthAppInfo(rapp2.Id)
require.NoError(t, err)
Client.Logout()
client.Logout()
_, resp = Client.GetOAuthAppInfo(rapp2.Id)
_, resp, err := client.GetOAuthAppInfo(rapp2.Id)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
_, resp = AdminClient.GetOAuthAppInfo("junk")
_, resp, err = adminClient.GetOAuthAppInfo("junk")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = AdminClient.GetOAuthAppInfo(model.NewId())
_, resp, err = adminClient.GetOAuthAppInfo(model.NewId())
require.Error(t, err)
CheckNotFoundStatus(t, resp)
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = false })
_, resp = AdminClient.GetOAuthAppInfo(rapp.Id)
_, resp, err = adminClient.GetOAuthAppInfo(rapp.Id)
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
}
func TestDeleteOAuthApp(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
AdminClient := th.SystemAdminClient
client := th.Client
adminClient := th.SystemAdminClient
defaultRolePermissions := th.SaveDefaultRolePermissions()
enableOAuthServiceProvider := th.App.Config().ServiceSettings.EnableOAuthServiceProvider
@ -401,59 +424,64 @@ func TestDeleteOAuthApp(t *testing.T) {
oapp := &model.OAuthApp{Name: GenerateTestAppName(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}}
rapp, resp := AdminClient.CreateOAuthApp(oapp)
CheckNoError(t, resp)
rapp, _, err := adminClient.CreateOAuthApp(oapp)
require.NoError(t, err)
oapp.Name = GenerateTestAppName()
rapp2, resp := Client.CreateOAuthApp(oapp)
CheckNoError(t, resp)
rapp2, _, err := client.CreateOAuthApp(oapp)
require.NoError(t, err)
pass, resp := AdminClient.DeleteOAuthApp(rapp.Id)
CheckNoError(t, resp)
assert.True(t, pass, "should have passed")
_, err = adminClient.DeleteOAuthApp(rapp.Id)
require.NoError(t, err)
_, resp = AdminClient.DeleteOAuthApp(rapp2.Id)
CheckNoError(t, resp)
_, err = adminClient.DeleteOAuthApp(rapp2.Id)
require.NoError(t, err)
rapp, resp = AdminClient.CreateOAuthApp(oapp)
CheckNoError(t, resp)
rapp, _, err = adminClient.CreateOAuthApp(oapp)
require.NoError(t, err)
oapp.Name = GenerateTestAppName()
rapp2, resp = Client.CreateOAuthApp(oapp)
CheckNoError(t, resp)
rapp2, _, err = client.CreateOAuthApp(oapp)
require.NoError(t, err)
_, resp = Client.DeleteOAuthApp(rapp.Id)
resp, err := client.DeleteOAuthApp(rapp.Id)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
_, resp = Client.DeleteOAuthApp(rapp2.Id)
CheckNoError(t, resp)
_, err = client.DeleteOAuthApp(rapp2.Id)
require.NoError(t, err)
// Revoke permission from regular users.
th.RemovePermissionFromRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId)
_, resp = Client.DeleteOAuthApp(rapp.Id)
resp, err = client.DeleteOAuthApp(rapp.Id)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
Client.Logout()
_, resp = Client.DeleteOAuthApp(rapp.Id)
client.Logout()
resp, err = client.DeleteOAuthApp(rapp.Id)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
_, resp = AdminClient.DeleteOAuthApp("junk")
resp, err = adminClient.DeleteOAuthApp("junk")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = AdminClient.DeleteOAuthApp(model.NewId())
resp, err = adminClient.DeleteOAuthApp(model.NewId())
require.Error(t, err)
CheckNotFoundStatus(t, resp)
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = false })
_, resp = AdminClient.DeleteOAuthApp(rapp.Id)
resp, err = adminClient.DeleteOAuthApp(rapp.Id)
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
}
func TestRegenerateOAuthAppSecret(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
AdminClient := th.SystemAdminClient
client := th.Client
adminClient := th.SystemAdminClient
defaultRolePermissions := th.SaveDefaultRolePermissions()
enableOAuthServiceProvider := th.App.Config().ServiceSettings.EnableOAuthServiceProvider
@ -468,60 +496,66 @@ func TestRegenerateOAuthAppSecret(t *testing.T) {
oapp := &model.OAuthApp{Name: GenerateTestAppName(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}}
rapp, resp := AdminClient.CreateOAuthApp(oapp)
CheckNoError(t, resp)
rapp, _, err := adminClient.CreateOAuthApp(oapp)
require.NoError(t, err)
oapp.Name = GenerateTestAppName()
rapp2, resp := Client.CreateOAuthApp(oapp)
CheckNoError(t, resp)
rapp2, _, err := client.CreateOAuthApp(oapp)
require.NoError(t, err)
rrapp, resp := AdminClient.RegenerateOAuthAppSecret(rapp.Id)
CheckNoError(t, resp)
rrapp, _, err := adminClient.RegenerateOAuthAppSecret(rapp.Id)
require.NoError(t, err)
assert.Equal(t, rrapp.Id, rapp.Id, "wrong app")
assert.NotEqual(t, rapp.ClientSecret, rrapp.ClientSecret, "secret didn't change")
_, resp = AdminClient.RegenerateOAuthAppSecret(rapp2.Id)
CheckNoError(t, resp)
_, _, err = adminClient.RegenerateOAuthAppSecret(rapp2.Id)
require.NoError(t, err)
rapp, resp = AdminClient.CreateOAuthApp(oapp)
CheckNoError(t, resp)
rapp, _, err = adminClient.CreateOAuthApp(oapp)
require.NoError(t, err)
oapp.Name = GenerateTestAppName()
rapp2, resp = Client.CreateOAuthApp(oapp)
CheckNoError(t, resp)
rapp2, _, err = client.CreateOAuthApp(oapp)
require.NoError(t, err)
_, resp = Client.RegenerateOAuthAppSecret(rapp.Id)
_, resp, err := client.RegenerateOAuthAppSecret(rapp.Id)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
_, resp = Client.RegenerateOAuthAppSecret(rapp2.Id)
CheckNoError(t, resp)
_, _, err = client.RegenerateOAuthAppSecret(rapp2.Id)
require.NoError(t, err)
// Revoke permission from regular users.
th.RemovePermissionFromRole(model.PermissionManageOAuth.Id, model.SystemUserRoleId)
_, resp = Client.RegenerateOAuthAppSecret(rapp.Id)
_, resp, err = client.RegenerateOAuthAppSecret(rapp.Id)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
Client.Logout()
_, resp = Client.RegenerateOAuthAppSecret(rapp.Id)
client.Logout()
_, resp, err = client.RegenerateOAuthAppSecret(rapp.Id)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
_, resp = AdminClient.RegenerateOAuthAppSecret("junk")
_, resp, err = adminClient.RegenerateOAuthAppSecret("junk")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = AdminClient.RegenerateOAuthAppSecret(model.NewId())
_, resp, err = adminClient.RegenerateOAuthAppSecret(model.NewId())
require.Error(t, err)
CheckNotFoundStatus(t, resp)
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = false })
_, resp = AdminClient.RegenerateOAuthAppSecret(rapp.Id)
_, resp, err = adminClient.RegenerateOAuthAppSecret(rapp.Id)
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
}
func TestGetAuthorizedOAuthAppsForUser(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
AdminClient := th.SystemAdminClient
client := th.Client
adminClient := th.SystemAdminClient
enableOAuth := th.App.Config().ServiceSettings.EnableOAuthServiceProvider
defer func() {
@ -531,8 +565,8 @@ func TestGetAuthorizedOAuthAppsForUser(t *testing.T) {
oapp := &model.OAuthApp{Name: GenerateTestAppName(), Homepage: "https://nowhere.com", Description: "test", CallbackUrls: []string{"https://nowhere.com"}}
rapp, resp := AdminClient.CreateOAuthApp(oapp)
CheckNoError(t, resp)
rapp, _, err := adminClient.CreateOAuthApp(oapp)
require.NoError(t, err)
authRequest := &model.AuthorizeRequest{
ResponseType: model.AuthCodeResponseType,
@ -542,11 +576,11 @@ func TestGetAuthorizedOAuthAppsForUser(t *testing.T) {
State: "123",
}
_, resp = Client.AuthorizeOAuthApp(authRequest)
CheckNoError(t, resp)
_, _, err = client.AuthorizeOAuthApp(authRequest)
require.NoError(t, err)
apps, resp := Client.GetAuthorizedOAuthAppsForUser(th.BasicUser.Id, 0, 1000)
CheckNoError(t, resp)
apps, _, err := client.GetAuthorizedOAuthAppsForUser(th.BasicUser.Id, 0, 1000)
require.NoError(t, err)
found := false
for _, a := range apps {
@ -557,18 +591,21 @@ func TestGetAuthorizedOAuthAppsForUser(t *testing.T) {
}
require.True(t, found, "missing app")
_, resp = Client.GetAuthorizedOAuthAppsForUser(th.BasicUser2.Id, 0, 1000)
_, resp, err := client.GetAuthorizedOAuthAppsForUser(th.BasicUser2.Id, 0, 1000)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
_, resp = Client.GetAuthorizedOAuthAppsForUser("junk", 0, 1000)
_, resp, err = client.GetAuthorizedOAuthAppsForUser("junk", 0, 1000)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
Client.Logout()
_, resp = Client.GetAuthorizedOAuthAppsForUser(th.BasicUser.Id, 0, 1000)
client.Logout()
_, resp, err = client.GetAuthorizedOAuthAppsForUser(th.BasicUser.Id, 0, 1000)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
_, resp = AdminClient.GetAuthorizedOAuthAppsForUser(th.BasicUser.Id, 0, 1000)
CheckNoError(t, resp)
_, _, err = adminClient.GetAuthorizedOAuthAppsForUser(th.BasicUser.Id, 0, 1000)
require.NoError(t, err)
}
func closeBody(r *http.Response) {
@ -577,3 +614,13 @@ func closeBody(r *http.Response) {
r.Body.Close()
}
}
func TestNilAuthorizeOAuthApp(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
client := th.Client
_, _, err := client.AuthorizeOAuthApp(nil)
require.Error(t, err)
CheckErrorID(t, err, "api.context.invalid_body_param.app_error")
}

View file

@ -18,7 +18,7 @@ func TestGetOpenGraphMetadata(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
enableLinkPreviews := *th.App.Config().ServiceSettings.EnableLinkPreviews
allowedInternalConnections := *th.App.Config().ServiceSettings.AllowedUntrustedInternalConnections
@ -59,8 +59,8 @@ func TestGetOpenGraphMetadata(t *testing.T) {
{"path": "/no-og-data/", "title": "", "cacheMissCount": 2},
} {
openGraph, resp := Client.OpenGraph(ts.URL + data["path"].(string))
CheckNoError(t, resp)
openGraph, _, err := client.OpenGraph(ts.URL + data["path"].(string))
require.NoError(t, err)
require.Equalf(t, openGraph["title"], data["title"].(string),
"OG data title mismatch for path \"%s\".")
@ -70,6 +70,7 @@ func TestGetOpenGraphMetadata(t *testing.T) {
}
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableLinkPreviews = false })
_, resp := Client.OpenGraph(ts.URL + "/og-data/")
_, resp, err := client.OpenGraph(ts.URL + "/og-data/")
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
}

View file

@ -7,6 +7,7 @@ import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/mattermost/mattermost-server/v6/model"
)
@ -20,23 +21,24 @@ func TestGetAncillaryPermissions(t *testing.T) {
t.Run("Valid Case, Passing in SubSection Permissions", func(t *testing.T) {
subsectionPermissions = []string{model.PermissionSysconsoleReadReportingSiteStatistics.Id}
expectedAncillaryPermissions = []string{model.PermissionGetAnalytics.Id}
actualAncillaryPermissions, resp := th.Client.GetAncillaryPermissions(subsectionPermissions)
CheckNoError(t, resp)
actualAncillaryPermissions, _, err := th.Client.GetAncillaryPermissions(subsectionPermissions)
require.NoError(t, err)
assert.Equal(t, append(subsectionPermissions, expectedAncillaryPermissions...), actualAncillaryPermissions)
})
t.Run("Invalid Case, Passing in SubSection Permissions That Don't Exist", func(t *testing.T) {
subsectionPermissions = []string{"All", "The", "Things", "She", "Said", "Running", "Through", "My", "Head"}
expectedAncillaryPermissions = []string{}
actualAncillaryPermissions, resp := th.Client.GetAncillaryPermissions(subsectionPermissions)
CheckNoError(t, resp)
actualAncillaryPermissions, _, err := th.Client.GetAncillaryPermissions(subsectionPermissions)
require.NoError(t, err)
assert.Equal(t, append(subsectionPermissions, expectedAncillaryPermissions...), actualAncillaryPermissions)
})
t.Run("Invalid Case, Passing in nothing", func(t *testing.T) {
subsectionPermissions = []string{}
expectedAncillaryPermissions = []string{}
_, resp := th.Client.GetAncillaryPermissions(subsectionPermissions)
_, resp, err := th.Client.GetAncillaryPermissions(subsectionPermissions)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
})
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -17,7 +17,7 @@ import (
func TestGetPreferences(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
// recreate basic user (cached has no default preferences)
th.BasicUser = th.CreateUser()
@ -44,10 +44,10 @@ func TestGetPreferences(t *testing.T) {
},
}
Client.UpdatePreferences(user1.Id, &preferences1)
client.UpdatePreferences(user1.Id, &preferences1)
prefs, resp := Client.GetPreferences(user1.Id)
CheckNoError(t, resp)
prefs, _, err := client.GetPreferences(user1.Id)
require.NoError(t, err)
// 5 because we have 2 initial preferences tutorial_step and recommended_next_steps added when creating a new user
require.Equal(t, len(prefs), 5, "received the wrong number of preferences")
@ -60,23 +60,25 @@ func TestGetPreferences(t *testing.T) {
th.BasicUser2 = th.CreateUser()
th.LoginBasic2()
prefs, resp = Client.GetPreferences(th.BasicUser2.Id)
CheckNoError(t, resp)
prefs, _, err = client.GetPreferences(th.BasicUser2.Id)
require.NoError(t, err)
require.Greater(t, len(prefs), 0, "received the wrong number of preferences")
_, resp = Client.GetPreferences(th.BasicUser.Id)
_, resp, err := client.GetPreferences(th.BasicUser.Id)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
Client.Logout()
_, resp = Client.GetPreferences(th.BasicUser2.Id)
client.Logout()
_, resp, err = client.GetPreferences(th.BasicUser2.Id)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
}
func TestGetPreferencesByCategory(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
th.LoginBasic()
user1 := th.BasicUser
@ -100,38 +102,43 @@ func TestGetPreferencesByCategory(t *testing.T) {
},
}
Client.UpdatePreferences(user1.Id, &preferences1)
client.UpdatePreferences(user1.Id, &preferences1)
prefs, resp := Client.GetPreferencesByCategory(user1.Id, category)
CheckNoError(t, resp)
prefs, _, err := client.GetPreferencesByCategory(user1.Id, category)
require.NoError(t, err)
require.Equal(t, len(prefs), 2, "received the wrong number of preferences")
_, resp = Client.GetPreferencesByCategory(user1.Id, "junk")
_, resp, err := client.GetPreferencesByCategory(user1.Id, "junk")
require.Error(t, err)
CheckNotFoundStatus(t, resp)
th.LoginBasic2()
_, resp = Client.GetPreferencesByCategory(th.BasicUser2.Id, category)
_, resp, err = client.GetPreferencesByCategory(th.BasicUser2.Id, category)
require.Error(t, err)
CheckNotFoundStatus(t, resp)
_, resp = Client.GetPreferencesByCategory(user1.Id, category)
_, resp, err = client.GetPreferencesByCategory(user1.Id, category)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
prefs, resp = Client.GetPreferencesByCategory(th.BasicUser2.Id, "junk")
prefs, resp, err = client.GetPreferencesByCategory(th.BasicUser2.Id, "junk")
require.Error(t, err)
CheckNotFoundStatus(t, resp)
require.Equal(t, len(prefs), 0, "received the wrong number of preferences")
Client.Logout()
_, resp = Client.GetPreferencesByCategory(th.BasicUser2.Id, category)
client.Logout()
_, resp, err = client.GetPreferencesByCategory(th.BasicUser2.Id, category)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
}
func TestGetPreferenceByCategoryAndName(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
th.LoginBasic()
user := th.BasicUser
@ -153,32 +160,36 @@ func TestGetPreferenceByCategoryAndName(t *testing.T) {
},
}
Client.UpdatePreferences(user.Id, &preferences)
client.UpdatePreferences(user.Id, &preferences)
pref, resp := Client.GetPreferenceByCategoryAndName(user.Id, model.PreferenceCategoryDirectChannelShow, name)
CheckNoError(t, resp)
pref, _, err := client.GetPreferenceByCategoryAndName(user.Id, model.PreferenceCategoryDirectChannelShow, name)
require.NoError(t, err)
require.Equal(t, preferences[0].UserId, pref.UserId, "UserId preference not saved")
require.Equal(t, preferences[0].Category, pref.Category, "Category preference not saved")
require.Equal(t, preferences[0].Name, pref.Name, "Name preference not saved")
preferences[0].Value = model.NewId()
Client.UpdatePreferences(user.Id, &preferences)
client.UpdatePreferences(user.Id, &preferences)
_, resp = Client.GetPreferenceByCategoryAndName(user.Id, "junk", preferences[0].Name)
_, resp, err := client.GetPreferenceByCategoryAndName(user.Id, "junk", preferences[0].Name)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = Client.GetPreferenceByCategoryAndName(user.Id, preferences[0].Category, "junk")
_, resp, err = client.GetPreferenceByCategoryAndName(user.Id, preferences[0].Category, "junk")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = Client.GetPreferenceByCategoryAndName(th.BasicUser2.Id, preferences[0].Category, "junk")
_, resp, err = client.GetPreferenceByCategoryAndName(th.BasicUser2.Id, preferences[0].Category, "junk")
require.Error(t, err)
CheckForbiddenStatus(t, resp)
_, resp = Client.GetPreferenceByCategoryAndName(user.Id, preferences[0].Category, preferences[0].Name)
CheckNoError(t, resp)
_, _, err = client.GetPreferenceByCategoryAndName(user.Id, preferences[0].Category, preferences[0].Name)
require.NoError(t, err)
Client.Logout()
_, resp = Client.GetPreferenceByCategoryAndName(user.Id, preferences[0].Category, preferences[0].Name)
client.Logout()
_, resp, err = client.GetPreferenceByCategoryAndName(user.Id, preferences[0].Category, preferences[0].Name)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
}
@ -186,7 +197,7 @@ func TestGetPreferenceByCategoryAndName(t *testing.T) {
func TestUpdatePreferences(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
th.LoginBasic()
user1 := th.BasicUser
@ -210,8 +221,8 @@ func TestUpdatePreferences(t *testing.T) {
},
}
_, resp := Client.UpdatePreferences(user1.Id, &preferences1)
CheckNoError(t, resp)
_, err := client.UpdatePreferences(user1.Id, &preferences1)
require.NoError(t, err)
preferences := model.Preferences{
{
@ -221,7 +232,8 @@ func TestUpdatePreferences(t *testing.T) {
},
}
_, resp = Client.UpdatePreferences(user1.Id, &preferences)
resp, err := client.UpdatePreferences(user1.Id, &preferences)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
preferences = model.Preferences{
@ -231,14 +243,17 @@ func TestUpdatePreferences(t *testing.T) {
},
}
_, resp = Client.UpdatePreferences(user1.Id, &preferences)
resp, err = client.UpdatePreferences(user1.Id, &preferences)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = Client.UpdatePreferences(th.BasicUser2.Id, &preferences)
resp, err = client.UpdatePreferences(th.BasicUser2.Id, &preferences)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
Client.Logout()
_, resp = Client.UpdatePreferences(user1.Id, &preferences1)
client.Logout()
resp, err = client.UpdatePreferences(user1.Id, &preferences1)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
}
@ -247,7 +262,7 @@ func TestUpdatePreferencesWebsocket(t *testing.T) {
defer th.TearDown()
WebSocketClient, err := th.CreateWebSocketClient()
require.Nil(t, err)
require.NoError(t, err)
WebSocketClient.Listen()
time.Sleep(300 * time.Millisecond)
@ -268,8 +283,8 @@ func TestUpdatePreferencesWebsocket(t *testing.T) {
},
}
_, resp := th.Client.UpdatePreferences(userId, preferences)
CheckNoError(t, resp)
_, err = th.Client.UpdatePreferences(userId, preferences)
require.NoError(t, err)
timeout := time.After(300 * time.Millisecond)
@ -308,22 +323,22 @@ func TestUpdateSidebarPreferences(t *testing.T) {
team1 := th.CreateTeam()
th.LinkUserToTeam(user, team1)
_, resp := th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.Nil(t, resp.Error)
_, _, err := th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.NoError(t, err)
channel := th.CreateChannelWithClientAndTeam(th.Client, model.ChannelTypeOpen, team1.Id)
th.AddUserToChannel(user, channel)
// Confirm that the sidebar is populated correctly to begin with
categories, resp := th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.Nil(t, resp.Error)
categories, _, err := th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
require.NotContains(t, categories.Categories[0].Channels, channel.Id)
require.Equal(t, model.SidebarCategoryChannels, categories.Categories[1].Type)
require.Contains(t, categories.Categories[1].Channels, channel.Id)
// Favorite the channel
_, resp = th.Client.UpdatePreferences(user.Id, &model.Preferences{
_, err = th.Client.UpdatePreferences(user.Id, &model.Preferences{
{
UserId: user.Id,
Category: model.PreferenceCategoryFavoriteChannel,
@ -331,18 +346,18 @@ func TestUpdateSidebarPreferences(t *testing.T) {
Value: "true",
},
})
require.Nil(t, resp.Error)
require.NoError(t, err)
// Confirm that the channel was added to the Favorites
categories, resp = th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.Nil(t, resp.Error)
categories, _, err = th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
assert.Contains(t, categories.Categories[0].Channels, channel.Id)
require.Equal(t, model.SidebarCategoryChannels, categories.Categories[1].Type)
assert.NotContains(t, categories.Categories[1].Channels, channel.Id)
// And unfavorite the channel
_, resp = th.Client.UpdatePreferences(user.Id, &model.Preferences{
_, err = th.Client.UpdatePreferences(user.Id, &model.Preferences{
{
UserId: user.Id,
Category: model.PreferenceCategoryFavoriteChannel,
@ -350,11 +365,11 @@ func TestUpdateSidebarPreferences(t *testing.T) {
Value: "false",
},
})
require.Nil(t, resp.Error)
require.NoError(t, err)
// The channel should've been removed from the Favorites
categories, resp = th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.Nil(t, resp.Error)
categories, _, err = th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
require.NotContains(t, categories.Categories[0].Channels, channel.Id)
require.Equal(t, model.SidebarCategoryChannels, categories.Categories[1].Type)
@ -376,7 +391,7 @@ func TestUpdateSidebarPreferences(t *testing.T) {
dmChannel := th.CreateDmChannel(user2)
// Favorite the channel
_, resp := th.Client.UpdatePreferences(user.Id, &model.Preferences{
_, err := th.Client.UpdatePreferences(user.Id, &model.Preferences{
{
UserId: user.Id,
Category: model.PreferenceCategoryFavoriteChannel,
@ -384,25 +399,25 @@ func TestUpdateSidebarPreferences(t *testing.T) {
Value: "true",
},
})
require.Nil(t, resp.Error)
require.NoError(t, err)
// Confirm that the channel was added to the Favorites on all teams
categories, resp := th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.Nil(t, resp.Error)
categories, _, err := th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
assert.Contains(t, categories.Categories[0].Channels, dmChannel.Id)
require.Equal(t, model.SidebarCategoryDirectMessages, categories.Categories[2].Type)
assert.NotContains(t, categories.Categories[2].Channels, dmChannel.Id)
categories, resp = th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team2.Id, "")
require.Nil(t, resp.Error)
categories, _, err = th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team2.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
assert.Contains(t, categories.Categories[0].Channels, dmChannel.Id)
require.Equal(t, model.SidebarCategoryDirectMessages, categories.Categories[2].Type)
assert.NotContains(t, categories.Categories[2].Channels, dmChannel.Id)
// And unfavorite the channel
_, resp = th.Client.UpdatePreferences(user.Id, &model.Preferences{
_, err = th.Client.UpdatePreferences(user.Id, &model.Preferences{
{
UserId: user.Id,
Category: model.PreferenceCategoryFavoriteChannel,
@ -410,18 +425,18 @@ func TestUpdateSidebarPreferences(t *testing.T) {
Value: "false",
},
})
require.Nil(t, resp.Error)
require.NoError(t, err)
// The channel should've been removed from the Favorites on all teams
categories, resp = th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.Nil(t, resp.Error)
categories, _, err = th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
require.NotContains(t, categories.Categories[0].Channels, dmChannel.Id)
require.Equal(t, model.SidebarCategoryDirectMessages, categories.Categories[2].Type)
assert.Contains(t, categories.Categories[2].Channels, dmChannel.Id)
categories, resp = th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team2.Id, "")
require.Nil(t, resp.Error)
categories, _, err = th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team2.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
require.NotContains(t, categories.Categories[0].Channels, dmChannel.Id)
require.Equal(t, model.SidebarCategoryDirectMessages, categories.Categories[2].Type)
@ -442,32 +457,32 @@ func TestUpdateSidebarPreferences(t *testing.T) {
th.LinkUserToTeam(user, team1)
th.LinkUserToTeam(user2, team1)
_, resp := th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.Nil(t, resp.Error)
_, resp = client2.GetSidebarCategoriesForTeamForUser(user2.Id, team1.Id, "")
require.Nil(t, resp.Error)
_, _, err := th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.NoError(t, err)
_, _, err = client2.GetSidebarCategoriesForTeamForUser(user2.Id, team1.Id, "")
require.NoError(t, err)
channel := th.CreateChannelWithClientAndTeam(th.Client, model.ChannelTypeOpen, team1.Id)
th.AddUserToChannel(user, channel)
th.AddUserToChannel(user2, channel)
// Confirm that the sidebar is populated correctly to begin with
categories, resp := th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.Nil(t, resp.Error)
categories, _, err := th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
require.NotContains(t, categories.Categories[0].Channels, channel.Id)
require.Equal(t, model.SidebarCategoryChannels, categories.Categories[1].Type)
require.Contains(t, categories.Categories[1].Channels, channel.Id)
categories, resp = client2.GetSidebarCategoriesForTeamForUser(user2.Id, team1.Id, "")
require.Nil(t, resp.Error)
categories, _, err = client2.GetSidebarCategoriesForTeamForUser(user2.Id, team1.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
require.NotContains(t, categories.Categories[0].Channels, channel.Id)
require.Equal(t, model.SidebarCategoryChannels, categories.Categories[1].Type)
require.Contains(t, categories.Categories[1].Channels, channel.Id)
// Favorite the channel
_, resp = th.Client.UpdatePreferences(user.Id, &model.Preferences{
_, err = th.Client.UpdatePreferences(user.Id, &model.Preferences{
{
UserId: user.Id,
Category: model.PreferenceCategoryFavoriteChannel,
@ -475,18 +490,18 @@ func TestUpdateSidebarPreferences(t *testing.T) {
Value: "true",
},
})
require.Nil(t, resp.Error)
require.NoError(t, err)
// Confirm that the channel was not added to Favorites for the second user
categories, resp = client2.GetSidebarCategoriesForTeamForUser(user2.Id, team1.Id, "")
require.Nil(t, resp.Error)
categories, _, err = client2.GetSidebarCategoriesForTeamForUser(user2.Id, team1.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
assert.NotContains(t, categories.Categories[0].Channels, channel.Id)
require.Equal(t, model.SidebarCategoryChannels, categories.Categories[1].Type)
assert.Contains(t, categories.Categories[1].Channels, channel.Id)
// Favorite the channel for the second user
_, resp = client2.UpdatePreferences(user2.Id, &model.Preferences{
_, err = client2.UpdatePreferences(user2.Id, &model.Preferences{
{
UserId: user2.Id,
Category: model.PreferenceCategoryFavoriteChannel,
@ -494,18 +509,18 @@ func TestUpdateSidebarPreferences(t *testing.T) {
Value: "true",
},
})
require.Nil(t, resp.Error)
require.NoError(t, err)
// Confirm that the channel is now in the Favorites for the second user
categories, resp = client2.GetSidebarCategoriesForTeamForUser(user2.Id, team1.Id, "")
require.Nil(t, resp.Error)
categories, _, err = client2.GetSidebarCategoriesForTeamForUser(user2.Id, team1.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
assert.Contains(t, categories.Categories[0].Channels, channel.Id)
require.Equal(t, model.SidebarCategoryChannels, categories.Categories[1].Type)
assert.NotContains(t, categories.Categories[1].Channels, channel.Id)
// And unfavorite the channel
_, resp = th.Client.UpdatePreferences(user.Id, &model.Preferences{
_, err = th.Client.UpdatePreferences(user.Id, &model.Preferences{
{
UserId: user.Id,
Category: model.PreferenceCategoryFavoriteChannel,
@ -513,11 +528,11 @@ func TestUpdateSidebarPreferences(t *testing.T) {
Value: "false",
},
})
require.Nil(t, resp.Error)
require.NoError(t, err)
// The channel should still be in the second user's favorites
categories, resp = client2.GetSidebarCategoriesForTeamForUser(user2.Id, team1.Id, "")
require.Nil(t, resp.Error)
categories, _, err = client2.GetSidebarCategoriesForTeamForUser(user2.Id, team1.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
assert.Contains(t, categories.Categories[0].Channels, channel.Id)
require.Equal(t, model.SidebarCategoryChannels, categories.Categories[1].Type)
@ -528,11 +543,11 @@ func TestUpdateSidebarPreferences(t *testing.T) {
func TestDeletePreferences(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
th.LoginBasic()
prefs, _ := Client.GetPreferences(th.BasicUser.Id)
prefs, _, _ := client.GetPreferences(th.BasicUser.Id)
originalCount := len(prefs)
// save 10 preferences
@ -546,27 +561,30 @@ func TestDeletePreferences(t *testing.T) {
preferences = append(preferences, preference)
}
Client.UpdatePreferences(th.BasicUser.Id, &preferences)
client.UpdatePreferences(th.BasicUser.Id, &preferences)
// delete 10 preferences
th.LoginBasic2()
_, resp := Client.DeletePreferences(th.BasicUser2.Id, &preferences)
resp, err := client.DeletePreferences(th.BasicUser2.Id, &preferences)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
th.LoginBasic()
_, resp = Client.DeletePreferences(th.BasicUser.Id, &preferences)
CheckNoError(t, resp)
_, err = client.DeletePreferences(th.BasicUser.Id, &preferences)
require.NoError(t, err)
_, resp = Client.DeletePreferences(th.BasicUser2.Id, &preferences)
resp, err = client.DeletePreferences(th.BasicUser2.Id, &preferences)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
prefs, _ = Client.GetPreferences(th.BasicUser.Id)
prefs, _, _ = client.GetPreferences(th.BasicUser.Id)
require.Len(t, prefs, originalCount, "should've deleted preferences")
Client.Logout()
_, resp = Client.DeletePreferences(th.BasicUser.Id, &preferences)
client.Logout()
resp, err = client.DeletePreferences(th.BasicUser.Id, &preferences)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
}
@ -587,18 +605,18 @@ func TestDeletePreferencesWebsocket(t *testing.T) {
Name: model.NewId(),
},
}
_, resp := th.Client.UpdatePreferences(userId, preferences)
CheckNoError(t, resp)
_, err := th.Client.UpdatePreferences(userId, preferences)
require.NoError(t, err)
WebSocketClient, err := th.CreateWebSocketClient()
require.Nil(t, err)
require.NoError(t, err)
WebSocketClient.Listen()
wsResp := <-WebSocketClient.ResponseChannel
require.Equal(t, model.StatusOk, wsResp.Status, "should have responded OK to authentication challenge")
_, resp = th.Client.DeletePreferences(userId, preferences)
CheckNoError(t, resp)
_, err = th.Client.DeletePreferences(userId, preferences)
require.NoError(t, err)
timeout := time.After(30000 * time.Millisecond)
@ -637,22 +655,22 @@ func TestDeleteSidebarPreferences(t *testing.T) {
team1 := th.CreateTeam()
th.LinkUserToTeam(user, team1)
_, resp := th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.Nil(t, resp.Error)
_, _, err := th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.NoError(t, err)
channel := th.CreateChannelWithClientAndTeam(th.Client, model.ChannelTypeOpen, team1.Id)
th.AddUserToChannel(user, channel)
// Confirm that the sidebar is populated correctly to begin with
categories, resp := th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.Nil(t, resp.Error)
categories, _, err := th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
require.NotContains(t, categories.Categories[0].Channels, channel.Id)
require.Equal(t, model.SidebarCategoryChannels, categories.Categories[1].Type)
require.Contains(t, categories.Categories[1].Channels, channel.Id)
// Favorite the channel
_, resp = th.Client.UpdatePreferences(user.Id, &model.Preferences{
_, err = th.Client.UpdatePreferences(user.Id, &model.Preferences{
{
UserId: user.Id,
Category: model.PreferenceCategoryFavoriteChannel,
@ -660,29 +678,28 @@ func TestDeleteSidebarPreferences(t *testing.T) {
Value: "true",
},
})
require.Nil(t, resp.Error)
require.NoError(t, err)
// Confirm that the channel was added to the Favorites
categories, resp = th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.Nil(t, resp.Error)
categories, _, err = th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
assert.Contains(t, categories.Categories[0].Channels, channel.Id)
require.Equal(t, model.SidebarCategoryChannels, categories.Categories[1].Type)
assert.NotContains(t, categories.Categories[1].Channels, channel.Id)
// And unfavorite the channel by deleting the preference
_, resp = th.Client.DeletePreferences(user.Id, &model.Preferences{
_, err = th.Client.DeletePreferences(user.Id, &model.Preferences{
{
UserId: user.Id,
Category: model.PreferenceCategoryFavoriteChannel,
Name: channel.Id,
},
})
require.Nil(t, resp.Error)
require.NoError(t, err)
// The channel should've been removed from the Favorites
categories, resp = th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.Nil(t, resp.Error)
categories, _, err = th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
require.NotContains(t, categories.Categories[0].Channels, channel.Id)
require.Equal(t, model.SidebarCategoryChannels, categories.Categories[1].Type)
@ -704,7 +721,7 @@ func TestDeleteSidebarPreferences(t *testing.T) {
dmChannel := th.CreateDmChannel(user2)
// Favorite the channel
_, resp := th.Client.UpdatePreferences(user.Id, &model.Preferences{
_, err := th.Client.UpdatePreferences(user.Id, &model.Preferences{
{
UserId: user.Id,
Category: model.PreferenceCategoryFavoriteChannel,
@ -712,43 +729,43 @@ func TestDeleteSidebarPreferences(t *testing.T) {
Value: "true",
},
})
require.Nil(t, resp.Error)
require.NoError(t, err)
// Confirm that the channel was added to the Favorites on all teams
categories, resp := th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.Nil(t, resp.Error)
categories, _, err := th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
assert.Contains(t, categories.Categories[0].Channels, dmChannel.Id)
require.Equal(t, model.SidebarCategoryDirectMessages, categories.Categories[2].Type)
assert.NotContains(t, categories.Categories[2].Channels, dmChannel.Id)
categories, resp = th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team2.Id, "")
require.Nil(t, resp.Error)
categories, _, err = th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team2.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
assert.Contains(t, categories.Categories[0].Channels, dmChannel.Id)
require.Equal(t, model.SidebarCategoryDirectMessages, categories.Categories[2].Type)
assert.NotContains(t, categories.Categories[2].Channels, dmChannel.Id)
// And unfavorite the channel by deleting the preference
_, resp = th.Client.DeletePreferences(user.Id, &model.Preferences{
_, err = th.Client.DeletePreferences(user.Id, &model.Preferences{
{
UserId: user.Id,
Category: model.PreferenceCategoryFavoriteChannel,
Name: dmChannel.Id,
},
})
require.Nil(t, resp.Error)
require.NoError(t, err)
// The channel should've been removed from the Favorites on all teams
categories, resp = th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.Nil(t, resp.Error)
categories, _, err = th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
require.NotContains(t, categories.Categories[0].Channels, dmChannel.Id)
require.Equal(t, model.SidebarCategoryDirectMessages, categories.Categories[2].Type)
assert.Contains(t, categories.Categories[2].Channels, dmChannel.Id)
categories, resp = th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team2.Id, "")
require.Nil(t, resp.Error)
categories, _, err = th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team2.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
require.NotContains(t, categories.Categories[0].Channels, dmChannel.Id)
require.Equal(t, model.SidebarCategoryDirectMessages, categories.Categories[2].Type)
@ -769,32 +786,32 @@ func TestDeleteSidebarPreferences(t *testing.T) {
th.LinkUserToTeam(user, team1)
th.LinkUserToTeam(user2, team1)
_, resp := th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.Nil(t, resp.Error)
_, resp = client2.GetSidebarCategoriesForTeamForUser(user2.Id, team1.Id, "")
require.Nil(t, resp.Error)
_, _, err := th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.NoError(t, err)
_, _, err = client2.GetSidebarCategoriesForTeamForUser(user2.Id, team1.Id, "")
require.NoError(t, err)
channel := th.CreateChannelWithClientAndTeam(th.Client, model.ChannelTypeOpen, team1.Id)
th.AddUserToChannel(user, channel)
th.AddUserToChannel(user2, channel)
// Confirm that the sidebar is populated correctly to begin with
categories, resp := th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.Nil(t, resp.Error)
categories, _, err := th.Client.GetSidebarCategoriesForTeamForUser(user.Id, team1.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
require.NotContains(t, categories.Categories[0].Channels, channel.Id)
require.Equal(t, model.SidebarCategoryChannels, categories.Categories[1].Type)
require.Contains(t, categories.Categories[1].Channels, channel.Id)
categories, resp = client2.GetSidebarCategoriesForTeamForUser(user2.Id, team1.Id, "")
require.Nil(t, resp.Error)
categories, _, err = client2.GetSidebarCategoriesForTeamForUser(user2.Id, team1.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
require.NotContains(t, categories.Categories[0].Channels, channel.Id)
require.Equal(t, model.SidebarCategoryChannels, categories.Categories[1].Type)
require.Contains(t, categories.Categories[1].Channels, channel.Id)
// Favorite the channel for both users
_, resp = th.Client.UpdatePreferences(user.Id, &model.Preferences{
_, err = th.Client.UpdatePreferences(user.Id, &model.Preferences{
{
UserId: user.Id,
Category: model.PreferenceCategoryFavoriteChannel,
@ -802,9 +819,9 @@ func TestDeleteSidebarPreferences(t *testing.T) {
Value: "true",
},
})
require.Nil(t, resp.Error)
require.NoError(t, err)
_, resp = client2.UpdatePreferences(user2.Id, &model.Preferences{
_, err = client2.UpdatePreferences(user2.Id, &model.Preferences{
{
UserId: user2.Id,
Category: model.PreferenceCategoryFavoriteChannel,
@ -812,18 +829,18 @@ func TestDeleteSidebarPreferences(t *testing.T) {
Value: "true",
},
})
require.Nil(t, resp.Error)
require.NoError(t, err)
// Confirm that the channel is in the Favorites for the second user
categories, resp = client2.GetSidebarCategoriesForTeamForUser(user2.Id, team1.Id, "")
require.Nil(t, resp.Error)
categories, _, err = client2.GetSidebarCategoriesForTeamForUser(user2.Id, team1.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
assert.Contains(t, categories.Categories[0].Channels, channel.Id)
require.Equal(t, model.SidebarCategoryChannels, categories.Categories[1].Type)
assert.NotContains(t, categories.Categories[1].Channels, channel.Id)
// And unfavorite the channel for the first user by deleting the preference
_, resp = th.Client.UpdatePreferences(user.Id, &model.Preferences{
_, err = th.Client.UpdatePreferences(user.Id, &model.Preferences{
{
UserId: user.Id,
Category: model.PreferenceCategoryFavoriteChannel,
@ -831,11 +848,11 @@ func TestDeleteSidebarPreferences(t *testing.T) {
Value: "false",
},
})
require.Nil(t, resp.Error)
require.NoError(t, err)
// The channel should still be in the second user's favorites
categories, resp = client2.GetSidebarCategoriesForTeamForUser(user2.Id, team1.Id, "")
require.Nil(t, resp.Error)
categories, _, err = client2.GetSidebarCategoriesForTeamForUser(user2.Id, team1.Id, "")
require.NoError(t, err)
require.Equal(t, model.SidebarCategoryFavorites, categories.Categories[0].Type)
assert.Contains(t, categories.Categories[0].Channels, channel.Id)
require.Equal(t, model.SidebarCategoryChannels, categories.Categories[1].Type)

View file

@ -16,7 +16,7 @@ import (
func TestSaveReaction(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
userId := th.BasicUser.Id
postId := th.BasicPost.Id
@ -33,61 +33,63 @@ func TestSaveReaction(t *testing.T) {
}
t.Run("successful-reaction", func(t *testing.T) {
rr, resp := Client.SaveReaction(reaction)
CheckNoError(t, resp)
rr, _, err := client.SaveReaction(reaction)
require.NoError(t, err)
require.Equal(t, reaction.UserId, rr.UserId, "UserId did not match")
require.Equal(t, reaction.PostId, rr.PostId, "PostId did not match")
require.Equal(t, reaction.EmojiName, rr.EmojiName, "EmojiName did not match")
require.NotEqual(t, 0, rr.CreateAt, "CreateAt should exist")
reactions, err := th.App.GetReactionsForPost(postId)
require.Nil(t, err)
reactions, appErr := th.App.GetReactionsForPost(postId)
require.Nil(t, appErr)
require.Equal(t, 1, len(reactions), "didn't save reaction correctly")
})
t.Run("duplicated-reaction", func(t *testing.T) {
_, resp := Client.SaveReaction(reaction)
CheckNoError(t, resp)
reactions, err := th.App.GetReactionsForPost(postId)
require.Nil(t, err)
_, _, err := client.SaveReaction(reaction)
require.NoError(t, err)
reactions, appErr := th.App.GetReactionsForPost(postId)
require.Nil(t, appErr)
require.Equal(t, 1, len(reactions), "should have not save duplicated reaction")
})
t.Run("save-second-reaction", func(t *testing.T) {
reaction.EmojiName = "sad"
rr, resp := Client.SaveReaction(reaction)
CheckNoError(t, resp)
rr, _, err := client.SaveReaction(reaction)
require.NoError(t, err)
require.Equal(t, rr.EmojiName, reaction.EmojiName, "EmojiName did not match")
reactions, err := th.App.GetReactionsForPost(postId)
require.Nil(t, err, "error saving multiple reactions")
reactions, appErr := th.App.GetReactionsForPost(postId)
require.Nil(t, appErr, "error saving multiple reactions")
require.Equal(t, len(reactions), 2, "should have save multiple reactions")
})
t.Run("saving-special-case", func(t *testing.T) {
reaction.EmojiName = "+1"
rr, resp := Client.SaveReaction(reaction)
CheckNoError(t, resp)
rr, _, err := client.SaveReaction(reaction)
require.NoError(t, err)
require.Equal(t, reaction.EmojiName, rr.EmojiName, "EmojiName did not match")
reactions, err := th.App.GetReactionsForPost(postId)
require.Nil(t, err)
reactions, appErr := th.App.GetReactionsForPost(postId)
require.Nil(t, appErr)
require.Equal(t, 3, len(reactions), "should have save multiple reactions")
})
t.Run("react-to-not-existing-post-id", func(t *testing.T) {
reaction.PostId = GenerateTestId()
_, resp := Client.SaveReaction(reaction)
_, resp, err := client.SaveReaction(reaction)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("react-to-not-valid-post-id", func(t *testing.T) {
reaction.PostId = "junk"
_, resp := Client.SaveReaction(reaction)
_, resp, err := client.SaveReaction(reaction)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
})
@ -95,14 +97,16 @@ func TestSaveReaction(t *testing.T) {
reaction.PostId = postId
reaction.UserId = GenerateTestId()
_, resp := Client.SaveReaction(reaction)
_, resp, err := client.SaveReaction(reaction)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("react-as-not-valid-user-id", func(t *testing.T) {
reaction.UserId = "junk"
_, resp := Client.SaveReaction(reaction)
_, resp, err := client.SaveReaction(reaction)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
})
@ -110,35 +114,40 @@ func TestSaveReaction(t *testing.T) {
reaction.UserId = userId
reaction.EmojiName = ""
_, resp := Client.SaveReaction(reaction)
_, resp, err := client.SaveReaction(reaction)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
})
t.Run("react-as-not-valid-emoji-name", func(t *testing.T) {
reaction.EmojiName = strings.Repeat("a", 65)
_, resp := Client.SaveReaction(reaction)
_, resp, err := client.SaveReaction(reaction)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
})
t.Run("react-as-other-user", func(t *testing.T) {
reaction.EmojiName = "smile"
otherUser := th.CreateUser()
Client.Logout()
Client.Login(otherUser.Email, otherUser.Password)
client.Logout()
client.Login(otherUser.Email, otherUser.Password)
_, resp := Client.SaveReaction(reaction)
_, resp, err := client.SaveReaction(reaction)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("react-being-not-logged-in", func(t *testing.T) {
Client.Logout()
_, resp := Client.SaveReaction(reaction)
client.Logout()
_, resp, err := client.SaveReaction(reaction)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
})
t.Run("react-as-other-user-being-system-admin", func(t *testing.T) {
_, resp := th.SystemAdminClient.SaveReaction(reaction)
_, resp, err := th.SystemAdminClient.SaveReaction(reaction)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
@ -146,11 +155,12 @@ func TestSaveReaction(t *testing.T) {
th.LoginBasic()
th.RemovePermissionFromRole(model.PermissionAddReaction.Id, model.ChannelUserRoleId)
_, resp := Client.SaveReaction(reaction)
_, resp, err := client.SaveReaction(reaction)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
reactions, err := th.App.GetReactionsForPost(postId)
require.Nil(t, err)
reactions, appErr := th.App.GetReactionsForPost(postId)
require.Nil(t, appErr)
require.Equal(t, 3, len(reactions), "should have not created a reactions")
th.AddPermissionToRole(model.PermissionAddReaction.Id, model.ChannelUserRoleId)
})
@ -158,8 +168,8 @@ func TestSaveReaction(t *testing.T) {
t.Run("unable-to-react-in-read-only-town-square", func(t *testing.T) {
th.LoginBasic()
channel, err := th.App.GetChannelByName("town-square", th.BasicTeam.Id, true)
assert.Nil(t, err)
channel, appErr := th.App.GetChannelByName("town-square", th.BasicTeam.Id, true)
assert.Nil(t, appErr)
post := th.CreatePostWithClient(th.Client, channel)
th.App.Srv().SetLicense(model.NewTestLicense())
@ -171,11 +181,12 @@ func TestSaveReaction(t *testing.T) {
EmojiName: "smile",
}
_, resp := Client.SaveReaction(reaction)
_, resp, err := client.SaveReaction(reaction)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
reactions, err := th.App.GetReactionsForPost(post.Id)
require.Nil(t, err)
reactions, appErr := th.App.GetReactionsForPost(post.Id)
require.Nil(t, appErr)
require.Equal(t, 0, len(reactions), "should have not created a reaction")
th.App.Srv().RemoveLicense()
@ -194,14 +205,15 @@ func TestSaveReaction(t *testing.T) {
EmojiName: "smile",
}
err := th.App.DeleteChannel(th.Context, channel, userId)
assert.Nil(t, err)
appErr := th.App.DeleteChannel(th.Context, channel, userId)
assert.Nil(t, appErr)
_, resp := Client.SaveReaction(reaction)
_, resp, err := client.SaveReaction(reaction)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
reactions, err := th.App.GetReactionsForPost(post.Id)
require.Nil(t, err)
reactions, appErr := th.App.GetReactionsForPost(post.Id)
require.Nil(t, appErr)
require.Equal(t, 0, len(reactions), "should have not created a reaction")
})
}
@ -209,7 +221,7 @@ func TestSaveReaction(t *testing.T) {
func TestGetReactions(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
userId := th.BasicUser.Id
user2Id := th.BasicUser2.Id
postId := th.BasicPost.Id
@ -251,8 +263,8 @@ func TestGetReactions(t *testing.T) {
}
t.Run("get-reactions", func(t *testing.T) {
rr, resp := Client.GetReactions(postId)
CheckNoError(t, resp)
rr, _, err := client.GetReactions(postId)
require.NoError(t, err)
assert.Len(t, rr, 5)
for _, r := range reactions {
@ -261,34 +273,37 @@ func TestGetReactions(t *testing.T) {
})
t.Run("get-reactions-of-invalid-post-id", func(t *testing.T) {
rr, resp := Client.GetReactions("junk")
rr, resp, err := client.GetReactions("junk")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
assert.Empty(t, rr)
})
t.Run("get-reactions-of-not-existing-post-id", func(t *testing.T) {
_, resp := Client.GetReactions(GenerateTestId())
_, resp, err := client.GetReactions(GenerateTestId())
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("get-reactions-as-anonymous-user", func(t *testing.T) {
Client.Logout()
client.Logout()
_, resp := Client.GetReactions(postId)
_, resp, err := client.GetReactions(postId)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
})
t.Run("get-reactions-as-system-admin", func(t *testing.T) {
_, resp := th.SystemAdminClient.GetReactions(postId)
CheckNoError(t, resp)
_, _, err := th.SystemAdminClient.GetReactions(postId)
require.NoError(t, err)
})
}
func TestDeleteReaction(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
userId := th.BasicUser.Id
user2Id := th.BasicUser2.Id
postId := th.BasicPost.Id
@ -325,47 +340,45 @@ func TestDeleteReaction(t *testing.T) {
t.Run("delete-reaction", func(t *testing.T) {
th.App.SaveReactionForPost(th.Context, r1)
reactions, err := th.App.GetReactionsForPost(postId)
require.Nil(t, err)
reactions, appErr := th.App.GetReactionsForPost(postId)
require.Nil(t, appErr)
require.Equal(t, 1, len(reactions), "didn't save reaction correctly")
ok, resp := Client.DeleteReaction(r1)
CheckNoError(t, resp)
_, err := client.DeleteReaction(r1)
require.NoError(t, err)
require.True(t, ok, "should have returned true")
reactions, err = th.App.GetReactionsForPost(postId)
require.Nil(t, err)
reactions, appErr = th.App.GetReactionsForPost(postId)
require.Nil(t, appErr)
require.Equal(t, 0, len(reactions), "should have deleted reaction")
})
t.Run("delete-reaction-when-post-has-multiple-reactions", func(t *testing.T) {
th.App.SaveReactionForPost(th.Context, r1)
th.App.SaveReactionForPost(th.Context, r2)
reactions, err := th.App.GetReactionsForPost(postId)
require.Nil(t, err)
reactions, appErr := th.App.GetReactionsForPost(postId)
require.Nil(t, appErr)
require.Equal(t, len(reactions), 2, "didn't save reactions correctly")
_, resp := Client.DeleteReaction(r2)
CheckNoError(t, resp)
_, err := client.DeleteReaction(r2)
require.NoError(t, err)
reactions, err = th.App.GetReactionsForPost(postId)
require.Nil(t, err)
reactions, appErr = th.App.GetReactionsForPost(postId)
require.Nil(t, appErr)
require.Equal(t, 1, len(reactions), "should have deleted only 1 reaction")
require.Equal(t, *r1, *reactions[0], "should have deleted 1 reaction only")
})
t.Run("delete-reaction-when-plus-one-reaction-name", func(t *testing.T) {
th.App.SaveReactionForPost(th.Context, r3)
reactions, err := th.App.GetReactionsForPost(postId)
require.Nil(t, err)
reactions, appErr := th.App.GetReactionsForPost(postId)
require.Nil(t, appErr)
require.Equal(t, 2, len(reactions), "didn't save reactions correctly")
_, resp := Client.DeleteReaction(r3)
CheckNoError(t, resp)
_, err := client.DeleteReaction(r3)
require.NoError(t, err)
reactions, err = th.App.GetReactionsForPost(postId)
require.Nil(t, err)
reactions, appErr = th.App.GetReactionsForPost(postId)
require.Nil(t, appErr)
require.Equal(t, 1, len(reactions), "should have deleted 1 reaction only")
require.Equal(t, *r1, *reactions[0], "should have deleted 1 reaction only")
})
@ -373,32 +386,33 @@ func TestDeleteReaction(t *testing.T) {
t.Run("delete-reaction-made-by-another-user", func(t *testing.T) {
th.LoginBasic2()
th.App.SaveReactionForPost(th.Context, r4)
reactions, err := th.App.GetReactionsForPost(postId)
require.Nil(t, err)
reactions, appErr := th.App.GetReactionsForPost(postId)
require.Nil(t, appErr)
require.Equal(t, 2, len(reactions), "didn't save reaction correctly")
th.LoginBasic()
ok, resp := Client.DeleteReaction(r4)
resp, err := client.DeleteReaction(r4)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
require.False(t, ok, "should have returned false")
reactions, err = th.App.GetReactionsForPost(postId)
require.Nil(t, err)
reactions, appErr = th.App.GetReactionsForPost(postId)
require.Nil(t, appErr)
require.Equal(t, 2, len(reactions), "should have not deleted a reaction")
})
t.Run("delete-reaction-from-not-existing-post-id", func(t *testing.T) {
r1.PostId = GenerateTestId()
_, resp := Client.DeleteReaction(r1)
resp, err := client.DeleteReaction(r1)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("delete-reaction-from-not-valid-post-id", func(t *testing.T) {
r1.PostId = "junk"
_, resp := Client.DeleteReaction(r1)
resp, err := client.DeleteReaction(r1)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
})
@ -406,14 +420,16 @@ func TestDeleteReaction(t *testing.T) {
r1.PostId = postId
r1.UserId = GenerateTestId()
_, resp := Client.DeleteReaction(r1)
resp, err := client.DeleteReaction(r1)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("delete-reaction-from-not-valid-user-id", func(t *testing.T) {
r1.UserId = "junk"
_, resp := Client.DeleteReaction(r1)
resp, err := client.DeleteReaction(r1)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
})
@ -421,34 +437,37 @@ func TestDeleteReaction(t *testing.T) {
r1.UserId = userId
r1.EmojiName = ""
_, resp := Client.DeleteReaction(r1)
resp, err := client.DeleteReaction(r1)
require.Error(t, err)
CheckNotFoundStatus(t, resp)
})
t.Run("delete-reaction-with-not-existing-name", func(t *testing.T) {
r1.EmojiName = strings.Repeat("a", 65)
_, resp := Client.DeleteReaction(r1)
resp, err := client.DeleteReaction(r1)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
})
t.Run("delete-reaction-as-anonymous-user", func(t *testing.T) {
Client.Logout()
client.Logout()
r1.EmojiName = "smile"
_, resp := Client.DeleteReaction(r1)
resp, err := client.DeleteReaction(r1)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
})
t.Run("delete-reaction-as-system-admin", func(t *testing.T) {
_, resp := th.SystemAdminClient.DeleteReaction(r1)
CheckNoError(t, resp)
_, err := th.SystemAdminClient.DeleteReaction(r1)
require.NoError(t, err)
_, resp = th.SystemAdminClient.DeleteReaction(r4)
CheckNoError(t, resp)
_, err = th.SystemAdminClient.DeleteReaction(r4)
require.NoError(t, err)
reactions, err := th.App.GetReactionsForPost(postId)
require.Nil(t, err)
reactions, appErr := th.App.GetReactionsForPost(postId)
require.Nil(t, appErr)
require.Equal(t, 0, len(reactions), "should have deleted both reactions")
})
@ -458,11 +477,12 @@ func TestDeleteReaction(t *testing.T) {
th.RemovePermissionFromRole(model.PermissionRemoveReaction.Id, model.ChannelUserRoleId)
th.App.SaveReactionForPost(th.Context, r1)
_, resp := Client.DeleteReaction(r1)
resp, err := client.DeleteReaction(r1)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
reactions, err := th.App.GetReactionsForPost(postId)
require.Nil(t, err)
reactions, appErr := th.App.GetReactionsForPost(postId)
require.Nil(t, appErr)
require.Equal(t, 1, len(reactions), "should have not deleted a reactions")
th.AddPermissionToRole(model.PermissionRemoveReaction.Id, model.ChannelUserRoleId)
})
@ -471,11 +491,12 @@ func TestDeleteReaction(t *testing.T) {
th.RemovePermissionFromRole(model.PermissionRemoveOthersReactions.Id, model.SystemAdminRoleId)
th.App.SaveReactionForPost(th.Context, r1)
_, resp := th.SystemAdminClient.DeleteReaction(r1)
resp, err := th.SystemAdminClient.DeleteReaction(r1)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
reactions, err := th.App.GetReactionsForPost(postId)
require.Nil(t, err)
reactions, appErr := th.App.GetReactionsForPost(postId)
require.Nil(t, appErr)
require.Equal(t, 1, len(reactions), "should have not deleted a reactions")
th.AddPermissionToRole(model.PermissionRemoveOthersReactions.Id, model.SystemAdminRoleId)
})
@ -483,8 +504,8 @@ func TestDeleteReaction(t *testing.T) {
t.Run("unable-to-delete-reactions-in-read-only-town-square", func(t *testing.T) {
th.LoginBasic()
channel, err := th.App.GetChannelByName("town-square", th.BasicTeam.Id, true)
assert.Nil(t, err)
channel, appErr := th.App.GetChannelByName("town-square", th.BasicTeam.Id, true)
assert.Nil(t, appErr)
post := th.CreatePostWithClient(th.Client, channel)
th.App.Srv().SetLicense(model.NewTestLicense())
@ -495,20 +516,21 @@ func TestDeleteReaction(t *testing.T) {
EmojiName: "smile",
}
r1, resp := Client.SaveReaction(reaction)
CheckNoError(t, resp)
r1, _, err := client.SaveReaction(reaction)
require.NoError(t, err)
reactions, err := th.App.GetReactionsForPost(postId)
require.Nil(t, err)
reactions, appErr := th.App.GetReactionsForPost(postId)
require.Nil(t, appErr)
require.Equal(t, 1, len(reactions), "should have created a reaction")
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.ExperimentalTownSquareIsReadOnly = true })
_, resp = th.SystemAdminClient.DeleteReaction(r1)
resp, err := th.SystemAdminClient.DeleteReaction(r1)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
reactions, err = th.App.GetReactionsForPost(postId)
require.Nil(t, err)
reactions, appErr = th.App.GetReactionsForPost(postId)
require.Nil(t, appErr)
require.Equal(t, 1, len(reactions), "should have not deleted a reaction")
th.App.Srv().RemoveLicense()
@ -527,21 +549,22 @@ func TestDeleteReaction(t *testing.T) {
EmojiName: "smile",
}
r1, resp := Client.SaveReaction(reaction)
CheckNoError(t, resp)
r1, _, err := client.SaveReaction(reaction)
require.NoError(t, err)
reactions, err := th.App.GetReactionsForPost(postId)
require.Nil(t, err)
reactions, appErr := th.App.GetReactionsForPost(postId)
require.Nil(t, appErr)
require.Equal(t, 1, len(reactions), "should have created a reaction")
err = th.App.DeleteChannel(th.Context, channel, userId)
assert.Nil(t, err)
appErr = th.App.DeleteChannel(th.Context, channel, userId)
assert.Nil(t, appErr)
_, resp = Client.SaveReaction(r1)
_, resp, err := client.SaveReaction(r1)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
reactions, err = th.App.GetReactionsForPost(post.Id)
require.Nil(t, err)
reactions, appErr = th.App.GetReactionsForPost(post.Id)
require.Nil(t, appErr)
require.Equal(t, 1, len(reactions), "should have not deleted a reaction")
})
}
@ -549,7 +572,7 @@ func TestDeleteReaction(t *testing.T) {
func TestGetBulkReactions(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
userId := th.BasicUser.Id
user2Id := th.BasicUser2.Id
post1 := &model.Post{UserId: userId, ChannelId: th.BasicChannel.Id, Message: "zz" + model.NewId() + "a"}
@ -559,11 +582,11 @@ func TestGetBulkReactions(t *testing.T) {
post4 := &model.Post{UserId: user2Id, ChannelId: th.BasicChannel.Id, Message: "zz" + model.NewId() + "a"}
post5 := &model.Post{UserId: user2Id, ChannelId: th.BasicChannel.Id, Message: "zz" + model.NewId() + "a"}
post1, _ = Client.CreatePost(post1)
post2, _ = Client.CreatePost(post2)
post3, _ = Client.CreatePost(post3)
post4, _ = Client.CreatePost(post4)
post5, _ = Client.CreatePost(post5)
post1, _, _ = client.CreatePost(post1)
post2, _, _ = client.CreatePost(post2)
post3, _, _ = client.CreatePost(post3)
post4, _, _ = client.CreatePost(post4)
post5, _, _ = client.CreatePost(post5)
expectedPostIdsReactionsMap := make(map[string][]*model.Reaction)
expectedPostIdsReactionsMap[post1.Id] = []*model.Reaction{}
@ -605,8 +628,8 @@ func TestGetBulkReactions(t *testing.T) {
postIds := []string{post1.Id, post2.Id, post3.Id, post4.Id, post5.Id}
t.Run("get-reactions", func(t *testing.T) {
postIdsReactionsMap, resp := Client.GetBulkReactions(postIds)
CheckNoError(t, resp)
postIdsReactionsMap, _, err := client.GetBulkReactions(postIds)
require.NoError(t, err)
assert.ElementsMatch(t, expectedPostIdsReactionsMap[post1.Id], postIdsReactionsMap[post1.Id])
assert.ElementsMatch(t, expectedPostIdsReactionsMap[post2.Id], postIdsReactionsMap[post2.Id])
@ -618,9 +641,10 @@ func TestGetBulkReactions(t *testing.T) {
})
t.Run("get-reactions-as-anonymous-user", func(t *testing.T) {
Client.Logout()
client.Logout()
_, resp := Client.GetBulkReactions(postIds)
_, resp, err := client.GetBulkReactions(postIds)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
})
}

View file

@ -32,8 +32,8 @@ func TestGetRole(t *testing.T) {
defer th.App.Srv().Store.Job().Delete(role.Id)
th.TestForAllClients(t, func(t *testing.T, client *model.Client4) {
received, resp := client.GetRole(role.Id)
CheckNoError(t, resp)
received, _, err := client.GetRole(role.Id)
require.NoError(t, err)
assert.Equal(t, received.Id, role.Id)
assert.Equal(t, received.Name, role.Name)
@ -44,10 +44,12 @@ func TestGetRole(t *testing.T) {
})
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
_, resp := client.GetRole("1234")
_, resp, err := client.GetRole("1234")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = client.GetRole(model.NewId())
_, resp, err = client.GetRole(model.NewId())
require.Error(t, err)
CheckNotFoundStatus(t, resp)
})
}
@ -69,8 +71,8 @@ func TestGetRoleByName(t *testing.T) {
defer th.App.Srv().Store.Job().Delete(role.Id)
th.TestForAllClients(t, func(t *testing.T, client *model.Client4) {
received, resp := client.GetRoleByName(role.Name)
CheckNoError(t, resp)
received, _, err := client.GetRoleByName(role.Name)
require.NoError(t, err)
assert.Equal(t, received.Id, role.Id)
assert.Equal(t, received.Name, role.Name)
@ -81,10 +83,12 @@ func TestGetRoleByName(t *testing.T) {
})
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
_, resp := client.GetRoleByName(strings.Repeat("abcdefghij", 10))
_, resp, err := client.GetRoleByName(strings.Repeat("abcdefghij", 10))
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = client.GetRoleByName(model.NewId())
_, resp, err = client.GetRoleByName(model.NewId())
require.Error(t, err)
CheckNotFoundStatus(t, resp)
})
}
@ -129,32 +133,34 @@ func TestGetRolesByNames(t *testing.T) {
th.TestForAllClients(t, func(t *testing.T, client *model.Client4) {
// Check all three roles can be found.
received, resp := client.GetRolesByNames([]string{role1.Name, role2.Name, role3.Name})
CheckNoError(t, resp)
received, _, err := client.GetRolesByNames([]string{role1.Name, role2.Name, role3.Name})
require.NoError(t, err)
assert.Contains(t, received, role1)
assert.Contains(t, received, role2)
assert.Contains(t, received, role3)
// Check a list of non-existent roles.
_, resp = client.GetRolesByNames([]string{model.NewId(), model.NewId()})
CheckNoError(t, resp)
_, _, err = client.GetRolesByNames([]string{model.NewId(), model.NewId()})
require.NoError(t, err)
})
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
// Empty list should error.
_, resp := client.GetRolesByNames([]string{})
_, resp, err := client.GetRolesByNames([]string{})
require.Error(t, err)
CheckBadRequestStatus(t, resp)
})
th.TestForAllClients(t, func(t *testing.T, client *model.Client4) {
// Invalid role name should error.
_, resp := client.GetRolesByNames([]string{model.NewId(), model.NewId(), "!!!!!!"})
_, resp, err := client.GetRolesByNames([]string{model.NewId(), model.NewId(), "!!!!!!"})
require.Error(t, err)
CheckBadRequestStatus(t, resp)
// Empty/whitespace rolenames should be ignored.
_, resp = client.GetRolesByNames([]string{model.NewId(), model.NewId(), "", " "})
CheckNoError(t, resp)
_, _, err = client.GetRolesByNames([]string{model.NewId(), model.NewId(), "", " "})
require.NoError(t, err)
})
}
@ -171,8 +177,8 @@ func TestPatchRole(t *testing.T) {
SchemeManaged: true,
}
role, err := th.App.Srv().Store.Role().Save(role)
assert.NoError(t, err)
role, err2 := th.App.Srv().Store.Role().Save(role)
assert.NoError(t, err2)
defer th.App.Srv().Store.Job().Delete(role.Id)
patch := &model.RolePatch{
@ -186,7 +192,8 @@ func TestPatchRole(t *testing.T) {
assert.NoError(t, err)
defer th.App.Srv().Store.Job().Delete(adminRole.Id)
_, resp := client.PatchRole(adminRole.Id, patch)
_, resp, err := client.PatchRole(adminRole.Id, patch)
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
// Cannot give other roles read / write to system roles or manage roles because only system admin can do these actions
@ -198,27 +205,30 @@ func TestPatchRole(t *testing.T) {
Permissions: &[]string{model.PermissionSysconsoleWriteUserManagementSystemRoles.Id},
}
_, resp = client.PatchRole(systemManager.Id, patchWriteSystemRoles)
_, resp, err = client.PatchRole(systemManager.Id, patchWriteSystemRoles)
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
patchReadSystemRoles := &model.RolePatch{
Permissions: &[]string{model.PermissionSysconsoleReadUserManagementSystemRoles.Id},
}
_, resp = client.PatchRole(systemManager.Id, patchReadSystemRoles)
_, resp, err = client.PatchRole(systemManager.Id, patchReadSystemRoles)
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
patchManageRoles := &model.RolePatch{
Permissions: &[]string{model.PermissionManageRoles.Id},
}
_, resp = client.PatchRole(systemManager.Id, patchManageRoles)
_, resp, err = client.PatchRole(systemManager.Id, patchManageRoles)
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
})
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
received, resp := client.PatchRole(role.Id, patch)
CheckNoError(t, resp)
received, _, err := client.PatchRole(role.Id, patch)
require.NoError(t, err)
assert.Equal(t, received.Id, role.Id)
assert.Equal(t, received.Name, role.Name)
@ -230,17 +240,20 @@ func TestPatchRole(t *testing.T) {
assert.Equal(t, received.SchemeManaged, role.SchemeManaged)
// Check a no-op patch succeeds.
_, resp = client.PatchRole(role.Id, patch)
CheckNoError(t, resp)
_, _, err = client.PatchRole(role.Id, patch)
require.NoError(t, err)
_, resp = client.PatchRole("junk", patch)
_, resp, err := client.PatchRole("junk", patch)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
})
_, resp := th.Client.PatchRole(model.NewId(), patch)
_, resp, err := th.Client.PatchRole(model.NewId(), patch)
require.Error(t, err)
CheckNotFoundStatus(t, resp)
_, resp = th.Client.PatchRole(role.Id, patch)
_, resp, err = th.Client.PatchRole(role.Id, patch)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
patch = &model.RolePatch{
@ -248,8 +261,8 @@ func TestPatchRole(t *testing.T) {
}
th.TestForSystemAdminAndLocal(t, func(t *testing.T, client *model.Client4) {
received, resp := client.PatchRole(role.Id, patch)
CheckNoError(t, resp)
received, _, err := client.PatchRole(role.Id, patch)
require.NoError(t, err)
assert.Equal(t, received.Id, role.Id)
assert.Equal(t, received.Name, role.Name)
@ -267,7 +280,8 @@ func TestPatchRole(t *testing.T) {
guestRole, err := th.App.Srv().Store.Role().GetByName(context.Background(), "system_guest")
require.NoError(t, err)
received, resp = client.PatchRole(guestRole.Id, patch)
received, resp, err = client.PatchRole(guestRole.Id, patch)
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
})
@ -277,8 +291,8 @@ func TestPatchRole(t *testing.T) {
th.App.Srv().SetLicense(license)
guestRole, err := th.App.Srv().Store.Role().GetByName(context.Background(), "system_guest")
require.NoError(t, err)
_, resp = client.PatchRole(guestRole.Id, patch)
CheckNoError(t, resp)
_, _, err = client.PatchRole(guestRole.Id, patch)
require.NoError(t, err)
})
})
}

View file

@ -16,9 +16,10 @@ import (
func TestGetSamlMetadata(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
client := th.Client
_, resp := Client.GetSamlMetadata()
_, resp, err := client.GetSamlMetadata()
require.Error(t, err)
CheckNotImplementedStatus(t, resp)
// Rest is tested by enterprise tests
@ -64,10 +65,12 @@ func TestSamlResetId(t *testing.T) {
})
require.Nil(t, appErr)
_, resp := th.Client.ResetSamlAuthDataToEmail(false, false, nil)
_, resp, err := th.Client.ResetSamlAuthDataToEmail(false, false, nil)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
numAffected, resp := th.SystemAdminClient.ResetSamlAuthDataToEmail(false, false, nil)
numAffected, resp, err := th.SystemAdminClient.ResetSamlAuthDataToEmail(false, false, nil)
require.NoError(t, err)
CheckOKStatus(t, resp)
require.Equal(t, int64(1), numAffected)
}

View file

@ -30,8 +30,8 @@ func TestCreateScheme(t *testing.T) {
Scope: model.SchemeScopeTeam,
}
s1, r1 := th.SystemAdminClient.CreateScheme(scheme1)
CheckNoError(t, r1)
s1, _, err := th.SystemAdminClient.CreateScheme(scheme1)
require.NoError(t, err)
assert.Equal(t, s1.DisplayName, scheme1.DisplayName)
assert.Equal(t, s1.Name, scheme1.Name)
@ -48,18 +48,21 @@ func TestCreateScheme(t *testing.T) {
assert.NotZero(t, len(s1.DefaultChannelGuestRole))
// Check the default roles have been created.
_, roleRes1 := th.SystemAdminClient.GetRoleByName(s1.DefaultTeamAdminRole)
CheckNoError(t, roleRes1)
_, roleRes2 := th.SystemAdminClient.GetRoleByName(s1.DefaultTeamUserRole)
CheckNoError(t, roleRes2)
_, roleRes3 := th.SystemAdminClient.GetRoleByName(s1.DefaultChannelAdminRole)
CheckNoError(t, roleRes3)
_, roleRes4 := th.SystemAdminClient.GetRoleByName(s1.DefaultChannelUserRole)
CheckNoError(t, roleRes4)
_, roleRes5 := th.SystemAdminClient.GetRoleByName(s1.DefaultTeamGuestRole)
CheckNoError(t, roleRes5)
_, roleRes6 := th.SystemAdminClient.GetRoleByName(s1.DefaultChannelGuestRole)
CheckNoError(t, roleRes6)
_, _, err = th.SystemAdminClient.GetRoleByName(s1.DefaultTeamAdminRole)
require.NoError(t, err)
_, _, err = th.SystemAdminClient.GetRoleByName(s1.DefaultTeamUserRole)
require.NoError(t, err)
_, _, err = th.SystemAdminClient.GetRoleByName(s1.DefaultChannelAdminRole)
require.NoError(t, err)
_, _, err = th.SystemAdminClient.GetRoleByName(s1.DefaultChannelUserRole)
require.NoError(t, err)
_, _, err = th.SystemAdminClient.GetRoleByName(s1.DefaultTeamGuestRole)
require.NoError(t, err)
_, _, err = th.SystemAdminClient.GetRoleByName(s1.DefaultTeamGuestRole)
require.NoError(t, err)
_, _, err = th.SystemAdminClient.GetRoleByName(s1.DefaultChannelGuestRole)
require.NoError(t, err)
// Basic Test of a Channel scheme.
scheme2 := &model.Scheme{
@ -69,8 +72,8 @@ func TestCreateScheme(t *testing.T) {
Scope: model.SchemeScopeChannel,
}
s2, r2 := th.SystemAdminClient.CreateScheme(scheme2)
CheckNoError(t, r2)
s2, _, err := th.SystemAdminClient.CreateScheme(scheme2)
require.NoError(t, err)
assert.Equal(t, s2.DisplayName, scheme2.DisplayName)
assert.Equal(t, s2.Name, scheme2.Name)
@ -87,12 +90,12 @@ func TestCreateScheme(t *testing.T) {
assert.NotZero(t, len(s2.DefaultChannelGuestRole))
// Check the default roles have been created.
_, roleRes7 := th.SystemAdminClient.GetRoleByName(s2.DefaultChannelAdminRole)
CheckNoError(t, roleRes7)
_, roleRes8 := th.SystemAdminClient.GetRoleByName(s2.DefaultChannelUserRole)
CheckNoError(t, roleRes8)
_, roleRes9 := th.SystemAdminClient.GetRoleByName(s2.DefaultChannelGuestRole)
CheckNoError(t, roleRes9)
_, _, err = th.SystemAdminClient.GetRoleByName(s2.DefaultChannelAdminRole)
require.NoError(t, err)
_, _, err = th.SystemAdminClient.GetRoleByName(s2.DefaultChannelUserRole)
require.NoError(t, err)
_, _, err = th.SystemAdminClient.GetRoleByName(s2.DefaultChannelGuestRole)
require.NoError(t, err)
// Try and create a scheme with an invalid scope.
scheme3 := &model.Scheme{
@ -102,7 +105,7 @@ func TestCreateScheme(t *testing.T) {
Scope: model.NewId(),
}
_, r3 := th.SystemAdminClient.CreateScheme(scheme3)
_, r3, _ := th.SystemAdminClient.CreateScheme(scheme3)
CheckBadRequestStatus(t, r3)
// Try and create a scheme with an invalid display name.
@ -112,7 +115,7 @@ func TestCreateScheme(t *testing.T) {
Description: model.NewId(),
Scope: model.NewId(),
}
_, r4 := th.SystemAdminClient.CreateScheme(scheme4)
_, r4, _ := th.SystemAdminClient.CreateScheme(scheme4)
CheckBadRequestStatus(t, r4)
// Try and create a scheme with an invalid name.
@ -122,7 +125,7 @@ func TestCreateScheme(t *testing.T) {
Description: model.NewId(),
Scope: model.NewId(),
}
_, r8 := th.SystemAdminClient.CreateScheme(scheme8)
_, r8, _ := th.SystemAdminClient.CreateScheme(scheme8)
CheckBadRequestStatus(t, r8)
// Try and create a scheme without the appropriate permissions.
@ -132,7 +135,8 @@ func TestCreateScheme(t *testing.T) {
Description: model.NewId(),
Scope: model.SchemeScopeTeam,
}
_, r5 := th.Client.CreateScheme(scheme5)
_, r5, err := th.Client.CreateScheme(scheme5)
require.Error(t, err)
CheckForbiddenStatus(t, r5)
// Try and create a scheme without a license.
@ -143,7 +147,7 @@ func TestCreateScheme(t *testing.T) {
Description: model.NewId(),
Scope: model.SchemeScopeTeam,
}
_, r6 := th.SystemAdminClient.CreateScheme(scheme6)
_, r6, _ := th.SystemAdminClient.CreateScheme(scheme6)
CheckNotImplementedStatus(t, r6)
th.App.SetPhase2PermissionsMigrationStatus(false)
@ -157,7 +161,7 @@ func TestCreateScheme(t *testing.T) {
Description: model.NewId(),
Scope: model.SchemeScopeTeam,
}
_, r7 := th.SystemAdminClient.CreateScheme(scheme7)
_, r7, _ := th.SystemAdminClient.CreateScheme(scheme7)
CheckNotImplementedStatus(t, r7)
}
@ -177,8 +181,8 @@ func TestGetScheme(t *testing.T) {
th.App.SetPhase2PermissionsMigrationStatus(true)
s1, r1 := th.SystemAdminClient.CreateScheme(scheme1)
CheckNoError(t, r1)
s1, _, err := th.SystemAdminClient.CreateScheme(scheme1)
require.NoError(t, err)
assert.Equal(t, s1.DisplayName, scheme1.DisplayName)
assert.Equal(t, s1.Name, scheme1.Name)
@ -194,32 +198,33 @@ func TestGetScheme(t *testing.T) {
assert.NotZero(t, len(s1.DefaultChannelUserRole))
assert.NotZero(t, len(s1.DefaultChannelGuestRole))
s2, r2 := th.SystemAdminClient.GetScheme(s1.Id)
CheckNoError(t, r2)
s2, _, err := th.SystemAdminClient.GetScheme(s1.Id)
require.NoError(t, err)
assert.Equal(t, s1, s2)
_, r3 := th.SystemAdminClient.GetScheme(model.NewId())
_, r3, _ := th.SystemAdminClient.GetScheme(model.NewId())
CheckNotFoundStatus(t, r3)
_, r4 := th.SystemAdminClient.GetScheme("12345")
_, r4, _ := th.SystemAdminClient.GetScheme("12345")
CheckBadRequestStatus(t, r4)
th.SystemAdminClient.Logout()
_, r5 := th.SystemAdminClient.GetScheme(s1.Id)
_, r5, _ := th.SystemAdminClient.GetScheme(s1.Id)
CheckUnauthorizedStatus(t, r5)
th.SystemAdminClient.Login(th.SystemAdminUser.Username, th.SystemAdminUser.Password)
th.App.Srv().SetLicense(nil)
_, r6 := th.SystemAdminClient.GetScheme(s1.Id)
CheckNoError(t, r6)
_, _, err = th.SystemAdminClient.GetScheme(s1.Id)
require.NoError(t, err)
_, r7 := th.Client.GetScheme(s1.Id)
_, r7, err := th.Client.GetScheme(s1.Id)
require.Error(t, err)
CheckForbiddenStatus(t, r7)
th.App.SetPhase2PermissionsMigrationStatus(false)
_, r8 := th.SystemAdminClient.GetScheme(s1.Id)
_, r8, _ := th.SystemAdminClient.GetScheme(s1.Id)
CheckNotImplementedStatus(t, r8)
}
@ -245,44 +250,45 @@ func TestGetSchemes(t *testing.T) {
th.App.SetPhase2PermissionsMigrationStatus(true)
_, r1 := th.SystemAdminClient.CreateScheme(scheme1)
CheckNoError(t, r1)
_, r2 := th.SystemAdminClient.CreateScheme(scheme2)
CheckNoError(t, r2)
_, _, err := th.SystemAdminClient.CreateScheme(scheme1)
require.NoError(t, err)
_, _, err = th.SystemAdminClient.CreateScheme(scheme2)
require.NoError(t, err)
l3, r3 := th.SystemAdminClient.GetSchemes("", 0, 100)
CheckNoError(t, r3)
l3, _, err := th.SystemAdminClient.GetSchemes("", 0, 100)
require.NoError(t, err)
assert.NotZero(t, len(l3))
l4, r4 := th.SystemAdminClient.GetSchemes("team", 0, 100)
CheckNoError(t, r4)
l4, _, err := th.SystemAdminClient.GetSchemes("team", 0, 100)
require.NoError(t, err)
for _, s := range l4 {
assert.Equal(t, "team", s.Scope)
}
l5, r5 := th.SystemAdminClient.GetSchemes("channel", 0, 100)
CheckNoError(t, r5)
l5, _, err := th.SystemAdminClient.GetSchemes("channel", 0, 100)
require.NoError(t, err)
for _, s := range l5 {
assert.Equal(t, "channel", s.Scope)
}
_, r6 := th.SystemAdminClient.GetSchemes("asdf", 0, 100)
_, r6, _ := th.SystemAdminClient.GetSchemes("asdf", 0, 100)
CheckBadRequestStatus(t, r6)
th.Client.Logout()
_, r7 := th.Client.GetSchemes("", 0, 100)
_, r7, _ := th.Client.GetSchemes("", 0, 100)
CheckUnauthorizedStatus(t, r7)
th.Client.Login(th.BasicUser.Username, th.BasicUser.Password)
_, r8 := th.Client.GetSchemes("", 0, 100)
_, r8, err := th.Client.GetSchemes("", 0, 100)
require.Error(t, err)
CheckForbiddenStatus(t, r8)
th.App.SetPhase2PermissionsMigrationStatus(false)
_, r9 := th.SystemAdminClient.GetSchemes("", 0, 100)
_, r9, _ := th.SystemAdminClient.GetSchemes("", 0, 100)
CheckNotImplementedStatus(t, r9)
}
@ -300,8 +306,8 @@ func TestGetTeamsForScheme(t *testing.T) {
Description: model.NewId(),
Scope: model.SchemeScopeTeam,
}
scheme1, r1 := th.SystemAdminClient.CreateScheme(scheme1)
CheckNoError(t, r1)
scheme1, _, err := th.SystemAdminClient.CreateScheme(scheme1)
require.NoError(t, err)
team1 := &model.Team{
Name: GenerateTestUsername(),
@ -309,19 +315,19 @@ func TestGetTeamsForScheme(t *testing.T) {
Type: model.TeamOpen,
}
team1, err := th.App.Srv().Store.Team().Save(team1)
team1, err = th.App.Srv().Store.Team().Save(team1)
require.NoError(t, err)
l2, r2 := th.SystemAdminClient.GetTeamsForScheme(scheme1.Id, 0, 100)
CheckNoError(t, r2)
l2, _, err := th.SystemAdminClient.GetTeamsForScheme(scheme1.Id, 0, 100)
require.NoError(t, err)
assert.Zero(t, len(l2))
team1.SchemeId = &scheme1.Id
team1, err = th.App.Srv().Store.Team().Update(team1)
assert.NoError(t, err)
l3, r3 := th.SystemAdminClient.GetTeamsForScheme(scheme1.Id, 0, 100)
CheckNoError(t, r3)
l3, _, err := th.SystemAdminClient.GetTeamsForScheme(scheme1.Id, 0, 100)
require.NoError(t, err)
assert.Len(t, l3, 1)
assert.Equal(t, team1.Id, l3[0].Id)
@ -334,30 +340,31 @@ func TestGetTeamsForScheme(t *testing.T) {
team2, err = th.App.Srv().Store.Team().Save(team2)
require.NoError(t, err)
l4, r4 := th.SystemAdminClient.GetTeamsForScheme(scheme1.Id, 0, 100)
CheckNoError(t, r4)
l4, _, err := th.SystemAdminClient.GetTeamsForScheme(scheme1.Id, 0, 100)
require.NoError(t, err)
assert.Len(t, l4, 2)
assert.Equal(t, team1.Id, l4[0].Id)
assert.Equal(t, team2.Id, l4[1].Id)
l5, r5 := th.SystemAdminClient.GetTeamsForScheme(scheme1.Id, 1, 1)
CheckNoError(t, r5)
l5, _, err := th.SystemAdminClient.GetTeamsForScheme(scheme1.Id, 1, 1)
require.NoError(t, err)
assert.Len(t, l5, 1)
assert.Equal(t, team2.Id, l5[0].Id)
// Check various error cases.
_, ri1 := th.SystemAdminClient.GetTeamsForScheme(model.NewId(), 0, 100)
_, ri1, _ := th.SystemAdminClient.GetTeamsForScheme(model.NewId(), 0, 100)
CheckNotFoundStatus(t, ri1)
_, ri2 := th.SystemAdminClient.GetTeamsForScheme("", 0, 100)
_, ri2, _ := th.SystemAdminClient.GetTeamsForScheme("", 0, 100)
CheckBadRequestStatus(t, ri2)
th.Client.Logout()
_, ri3 := th.Client.GetTeamsForScheme(model.NewId(), 0, 100)
_, ri3, _ := th.Client.GetTeamsForScheme(model.NewId(), 0, 100)
CheckUnauthorizedStatus(t, ri3)
th.Client.Login(th.BasicUser.Username, th.BasicUser.Password)
_, ri4 := th.Client.GetTeamsForScheme(model.NewId(), 0, 100)
_, ri4, err := th.Client.GetTeamsForScheme(model.NewId(), 0, 100)
require.Error(t, err)
CheckForbiddenStatus(t, ri4)
scheme2 := &model.Scheme{
@ -366,15 +373,15 @@ func TestGetTeamsForScheme(t *testing.T) {
Description: model.NewId(),
Scope: model.SchemeScopeChannel,
}
scheme2, rs2 := th.SystemAdminClient.CreateScheme(scheme2)
CheckNoError(t, rs2)
scheme2, _, err = th.SystemAdminClient.CreateScheme(scheme2)
require.NoError(t, err)
_, ri5 := th.SystemAdminClient.GetTeamsForScheme(scheme2.Id, 0, 100)
_, ri5, _ := th.SystemAdminClient.GetTeamsForScheme(scheme2.Id, 0, 100)
CheckBadRequestStatus(t, ri5)
th.App.SetPhase2PermissionsMigrationStatus(false)
_, ri6 := th.SystemAdminClient.GetTeamsForScheme(scheme1.Id, 0, 100)
_, ri6, _ := th.SystemAdminClient.GetTeamsForScheme(scheme1.Id, 0, 100)
CheckNotImplementedStatus(t, ri6)
}
@ -392,8 +399,8 @@ func TestGetChannelsForScheme(t *testing.T) {
Description: model.NewId(),
Scope: model.SchemeScopeChannel,
}
scheme1, r1 := th.SystemAdminClient.CreateScheme(scheme1)
CheckNoError(t, r1)
scheme1, _, err := th.SystemAdminClient.CreateScheme(scheme1)
require.NoError(t, err)
channel1 := &model.Channel{
TeamId: model.NewId(),
@ -405,16 +412,16 @@ func TestGetChannelsForScheme(t *testing.T) {
channel1, errCh := th.App.Srv().Store.Channel().Save(channel1, 1000000)
assert.NoError(t, errCh)
l2, r2 := th.SystemAdminClient.GetChannelsForScheme(scheme1.Id, 0, 100)
CheckNoError(t, r2)
l2, _, err := th.SystemAdminClient.GetChannelsForScheme(scheme1.Id, 0, 100)
require.NoError(t, err)
assert.Zero(t, len(l2))
channel1.SchemeId = &scheme1.Id
channel1, err := th.App.Srv().Store.Channel().Update(channel1)
channel1, err = th.App.Srv().Store.Channel().Update(channel1)
assert.NoError(t, err)
l3, r3 := th.SystemAdminClient.GetChannelsForScheme(scheme1.Id, 0, 100)
CheckNoError(t, r3)
l3, _, err := th.SystemAdminClient.GetChannelsForScheme(scheme1.Id, 0, 100)
require.NoError(t, err)
assert.Len(t, l3, 1)
assert.Equal(t, channel1.Id, l3[0].Id)
@ -425,33 +432,34 @@ func TestGetChannelsForScheme(t *testing.T) {
Type: model.ChannelTypeOpen,
SchemeId: &scheme1.Id,
}
channel2, nErr := th.App.Srv().Store.Channel().Save(channel2, 1000000)
assert.NoError(t, nErr)
channel2, err = th.App.Srv().Store.Channel().Save(channel2, 1000000)
assert.NoError(t, err)
l4, r4 := th.SystemAdminClient.GetChannelsForScheme(scheme1.Id, 0, 100)
CheckNoError(t, r4)
l4, _, err := th.SystemAdminClient.GetChannelsForScheme(scheme1.Id, 0, 100)
require.NoError(t, err)
assert.Len(t, l4, 2)
assert.Equal(t, channel1.Id, l4[0].Id)
assert.Equal(t, channel2.Id, l4[1].Id)
l5, r5 := th.SystemAdminClient.GetChannelsForScheme(scheme1.Id, 1, 1)
CheckNoError(t, r5)
l5, _, err := th.SystemAdminClient.GetChannelsForScheme(scheme1.Id, 1, 1)
require.NoError(t, err)
assert.Len(t, l5, 1)
assert.Equal(t, channel2.Id, l5[0].Id)
// Check various error cases.
_, ri1 := th.SystemAdminClient.GetChannelsForScheme(model.NewId(), 0, 100)
_, ri1, _ := th.SystemAdminClient.GetChannelsForScheme(model.NewId(), 0, 100)
CheckNotFoundStatus(t, ri1)
_, ri2 := th.SystemAdminClient.GetChannelsForScheme("", 0, 100)
_, ri2, _ := th.SystemAdminClient.GetChannelsForScheme("", 0, 100)
CheckBadRequestStatus(t, ri2)
th.Client.Logout()
_, ri3 := th.Client.GetChannelsForScheme(model.NewId(), 0, 100)
_, ri3, _ := th.Client.GetChannelsForScheme(model.NewId(), 0, 100)
CheckUnauthorizedStatus(t, ri3)
th.Client.Login(th.BasicUser.Username, th.BasicUser.Password)
_, ri4 := th.Client.GetChannelsForScheme(model.NewId(), 0, 100)
_, ri4, err := th.Client.GetChannelsForScheme(model.NewId(), 0, 100)
require.Error(t, err)
CheckForbiddenStatus(t, ri4)
scheme2 := &model.Scheme{
@ -460,15 +468,15 @@ func TestGetChannelsForScheme(t *testing.T) {
Description: model.NewId(),
Scope: model.SchemeScopeTeam,
}
scheme2, rs2 := th.SystemAdminClient.CreateScheme(scheme2)
CheckNoError(t, rs2)
scheme2, _, err = th.SystemAdminClient.CreateScheme(scheme2)
require.NoError(t, err)
_, ri5 := th.SystemAdminClient.GetChannelsForScheme(scheme2.Id, 0, 100)
_, ri5, _ := th.SystemAdminClient.GetChannelsForScheme(scheme2.Id, 0, 100)
CheckBadRequestStatus(t, ri5)
th.App.SetPhase2PermissionsMigrationStatus(false)
_, ri6 := th.SystemAdminClient.GetChannelsForScheme(scheme1.Id, 0, 100)
_, ri6, _ := th.SystemAdminClient.GetChannelsForScheme(scheme1.Id, 0, 100)
CheckNotImplementedStatus(t, ri6)
}
@ -488,8 +496,8 @@ func TestPatchScheme(t *testing.T) {
Scope: model.SchemeScopeTeam,
}
s1, r1 := th.SystemAdminClient.CreateScheme(scheme1)
CheckNoError(t, r1)
s1, _, err := th.SystemAdminClient.CreateScheme(scheme1)
require.NoError(t, err)
assert.Equal(t, s1.DisplayName, scheme1.DisplayName)
assert.Equal(t, s1.Name, scheme1.Name)
@ -505,8 +513,8 @@ func TestPatchScheme(t *testing.T) {
assert.NotZero(t, len(s1.DefaultChannelUserRole))
assert.NotZero(t, len(s1.DefaultChannelGuestRole))
s2, r2 := th.SystemAdminClient.GetScheme(s1.Id)
CheckNoError(t, r2)
s2, _, err := th.SystemAdminClient.GetScheme(s1.Id)
require.NoError(t, err)
assert.Equal(t, s1, s2)
@ -520,15 +528,15 @@ func TestPatchScheme(t *testing.T) {
*schemePatch.Name = model.NewId()
*schemePatch.Description = model.NewId()
s3, r3 := th.SystemAdminClient.PatchScheme(s2.Id, schemePatch)
CheckNoError(t, r3)
s3, _, err := th.SystemAdminClient.PatchScheme(s2.Id, schemePatch)
require.NoError(t, err)
assert.Equal(t, s3.Id, s2.Id)
assert.Equal(t, s3.DisplayName, *schemePatch.DisplayName)
assert.Equal(t, s3.Name, *schemePatch.Name)
assert.Equal(t, s3.Description, *schemePatch.Description)
s4, r4 := th.SystemAdminClient.GetScheme(s3.Id)
CheckNoError(t, r4)
s4, _, err := th.SystemAdminClient.GetScheme(s3.Id)
require.NoError(t, err)
assert.Equal(t, s3, s4)
// Test with a partial patch.
@ -536,38 +544,39 @@ func TestPatchScheme(t *testing.T) {
*schemePatch.DisplayName = model.NewId()
schemePatch.Description = nil
s5, r5 := th.SystemAdminClient.PatchScheme(s4.Id, schemePatch)
CheckNoError(t, r5)
s5, _, err := th.SystemAdminClient.PatchScheme(s4.Id, schemePatch)
require.NoError(t, err)
assert.Equal(t, s5.Id, s4.Id)
assert.Equal(t, s5.DisplayName, *schemePatch.DisplayName)
assert.Equal(t, s5.Name, *schemePatch.Name)
assert.Equal(t, s5.Description, s4.Description)
s6, r6 := th.SystemAdminClient.GetScheme(s5.Id)
CheckNoError(t, r6)
s6, _, err := th.SystemAdminClient.GetScheme(s5.Id)
require.NoError(t, err)
assert.Equal(t, s5, s6)
// Test with invalid patch.
*schemePatch.Name = strings.Repeat(model.NewId(), 20)
_, r7 := th.SystemAdminClient.PatchScheme(s6.Id, schemePatch)
_, r7, _ := th.SystemAdminClient.PatchScheme(s6.Id, schemePatch)
CheckBadRequestStatus(t, r7)
// Test with unknown ID.
*schemePatch.Name = model.NewId()
_, r8 := th.SystemAdminClient.PatchScheme(model.NewId(), schemePatch)
_, r8, _ := th.SystemAdminClient.PatchScheme(model.NewId(), schemePatch)
CheckNotFoundStatus(t, r8)
// Test with invalid ID.
_, r9 := th.SystemAdminClient.PatchScheme("12345", schemePatch)
_, r9, _ := th.SystemAdminClient.PatchScheme("12345", schemePatch)
CheckBadRequestStatus(t, r9)
// Test without required permissions.
_, r10 := th.Client.PatchScheme(s6.Id, schemePatch)
_, r10, err := th.Client.PatchScheme(s6.Id, schemePatch)
require.Error(t, err)
CheckForbiddenStatus(t, r10)
// Test without license.
th.App.Srv().SetLicense(nil)
_, r11 := th.SystemAdminClient.PatchScheme(s6.Id, schemePatch)
_, r11, _ := th.SystemAdminClient.PatchScheme(s6.Id, schemePatch)
CheckNotImplementedStatus(t, r11)
th.App.SetPhase2PermissionsMigrationStatus(false)
@ -575,7 +584,7 @@ func TestPatchScheme(t *testing.T) {
th.LoginSystemAdmin()
th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes"))
_, r12 := th.SystemAdminClient.PatchScheme(s6.Id, schemePatch)
_, r12, _ := th.SystemAdminClient.PatchScheme(s6.Id, schemePatch)
CheckNotImplementedStatus(t, r12)
}
@ -596,22 +605,22 @@ func TestDeleteScheme(t *testing.T) {
Scope: model.SchemeScopeTeam,
}
s1, r1 := th.SystemAdminClient.CreateScheme(scheme1)
CheckNoError(t, r1)
s1, _, err := th.SystemAdminClient.CreateScheme(scheme1)
require.NoError(t, err)
// Retrieve the roles and check they are not deleted.
role1, roleRes1 := th.SystemAdminClient.GetRoleByName(s1.DefaultTeamAdminRole)
CheckNoError(t, roleRes1)
role2, roleRes2 := th.SystemAdminClient.GetRoleByName(s1.DefaultTeamUserRole)
CheckNoError(t, roleRes2)
role3, roleRes3 := th.SystemAdminClient.GetRoleByName(s1.DefaultChannelAdminRole)
CheckNoError(t, roleRes3)
role4, roleRes4 := th.SystemAdminClient.GetRoleByName(s1.DefaultChannelUserRole)
CheckNoError(t, roleRes4)
role5, roleRes5 := th.SystemAdminClient.GetRoleByName(s1.DefaultTeamGuestRole)
CheckNoError(t, roleRes5)
role6, roleRes6 := th.SystemAdminClient.GetRoleByName(s1.DefaultChannelGuestRole)
CheckNoError(t, roleRes6)
role1, _, err := th.SystemAdminClient.GetRoleByName(s1.DefaultTeamAdminRole)
require.NoError(t, err)
role2, _, err := th.SystemAdminClient.GetRoleByName(s1.DefaultTeamUserRole)
require.NoError(t, err)
role3, _, err := th.SystemAdminClient.GetRoleByName(s1.DefaultChannelAdminRole)
require.NoError(t, err)
role4, _, err := th.SystemAdminClient.GetRoleByName(s1.DefaultChannelUserRole)
require.NoError(t, err)
role5, _, err := th.SystemAdminClient.GetRoleByName(s1.DefaultTeamGuestRole)
require.NoError(t, err)
role6, _, err := th.SystemAdminClient.GetRoleByName(s1.DefaultChannelGuestRole)
require.NoError(t, err)
assert.Zero(t, role1.DeleteAt)
assert.Zero(t, role2.DeleteAt)
@ -631,22 +640,22 @@ func TestDeleteScheme(t *testing.T) {
require.NoError(t, err)
// Delete the Scheme.
_, r3 := th.SystemAdminClient.DeleteScheme(s1.Id)
CheckNoError(t, r3)
_, err = th.SystemAdminClient.DeleteScheme(s1.Id)
require.NoError(t, err)
// Check the roles were deleted.
role1, roleRes1 = th.SystemAdminClient.GetRoleByName(s1.DefaultTeamAdminRole)
CheckNoError(t, roleRes1)
role2, roleRes2 = th.SystemAdminClient.GetRoleByName(s1.DefaultTeamUserRole)
CheckNoError(t, roleRes2)
role3, roleRes3 = th.SystemAdminClient.GetRoleByName(s1.DefaultChannelAdminRole)
CheckNoError(t, roleRes3)
role4, roleRes4 = th.SystemAdminClient.GetRoleByName(s1.DefaultChannelUserRole)
CheckNoError(t, roleRes4)
role5, roleRes5 = th.SystemAdminClient.GetRoleByName(s1.DefaultTeamGuestRole)
CheckNoError(t, roleRes5)
role6, roleRes6 = th.SystemAdminClient.GetRoleByName(s1.DefaultChannelGuestRole)
CheckNoError(t, roleRes6)
role1, _, err = th.SystemAdminClient.GetRoleByName(s1.DefaultTeamAdminRole)
require.NoError(t, err)
role2, _, err = th.SystemAdminClient.GetRoleByName(s1.DefaultTeamUserRole)
require.NoError(t, err)
role3, _, err = th.SystemAdminClient.GetRoleByName(s1.DefaultChannelAdminRole)
require.NoError(t, err)
role4, _, err = th.SystemAdminClient.GetRoleByName(s1.DefaultChannelUserRole)
require.NoError(t, err)
role5, _, err = th.SystemAdminClient.GetRoleByName(s1.DefaultTeamGuestRole)
require.NoError(t, err)
role6, _, err = th.SystemAdminClient.GetRoleByName(s1.DefaultChannelGuestRole)
require.NoError(t, err)
assert.NotZero(t, role1.DeleteAt)
assert.NotZero(t, role2.DeleteAt)
@ -656,8 +665,8 @@ func TestDeleteScheme(t *testing.T) {
assert.NotZero(t, role6.DeleteAt)
// Check the team now uses the default scheme
c2, resp := th.SystemAdminClient.GetTeam(team.Id, "")
CheckNoError(t, resp)
c2, _, err := th.SystemAdminClient.GetTeam(team.Id, "")
require.NoError(t, err)
assert.Equal(t, "", *c2.SchemeId)
})
@ -674,16 +683,16 @@ func TestDeleteScheme(t *testing.T) {
Scope: model.SchemeScopeChannel,
}
s1, r1 := th.SystemAdminClient.CreateScheme(scheme1)
CheckNoError(t, r1)
s1, _, err := th.SystemAdminClient.CreateScheme(scheme1)
require.NoError(t, err)
// Retrieve the roles and check they are not deleted.
role3, roleRes3 := th.SystemAdminClient.GetRoleByName(s1.DefaultChannelAdminRole)
CheckNoError(t, roleRes3)
role4, roleRes4 := th.SystemAdminClient.GetRoleByName(s1.DefaultChannelUserRole)
CheckNoError(t, roleRes4)
role6, roleRes6 := th.SystemAdminClient.GetRoleByName(s1.DefaultChannelGuestRole)
CheckNoError(t, roleRes6)
role3, _, err := th.SystemAdminClient.GetRoleByName(s1.DefaultChannelAdminRole)
require.NoError(t, err)
role4, _, err := th.SystemAdminClient.GetRoleByName(s1.DefaultChannelUserRole)
require.NoError(t, err)
role6, _, err := th.SystemAdminClient.GetRoleByName(s1.DefaultChannelGuestRole)
require.NoError(t, err)
assert.Zero(t, role3.DeleteAt)
assert.Zero(t, role4.DeleteAt)
@ -700,24 +709,24 @@ func TestDeleteScheme(t *testing.T) {
assert.NoError(t, err)
// Delete the Scheme.
_, r3 := th.SystemAdminClient.DeleteScheme(s1.Id)
CheckNoError(t, r3)
_, err = th.SystemAdminClient.DeleteScheme(s1.Id)
require.NoError(t, err)
// Check the roles were deleted.
role3, roleRes3 = th.SystemAdminClient.GetRoleByName(s1.DefaultChannelAdminRole)
CheckNoError(t, roleRes3)
role4, roleRes4 = th.SystemAdminClient.GetRoleByName(s1.DefaultChannelUserRole)
CheckNoError(t, roleRes4)
role6, roleRes6 = th.SystemAdminClient.GetRoleByName(s1.DefaultChannelGuestRole)
CheckNoError(t, roleRes6)
role3, _, err = th.SystemAdminClient.GetRoleByName(s1.DefaultChannelAdminRole)
require.NoError(t, err)
role4, _, err = th.SystemAdminClient.GetRoleByName(s1.DefaultChannelUserRole)
require.NoError(t, err)
role6, _, err = th.SystemAdminClient.GetRoleByName(s1.DefaultChannelGuestRole)
require.NoError(t, err)
assert.NotZero(t, role3.DeleteAt)
assert.NotZero(t, role4.DeleteAt)
assert.NotZero(t, role6.DeleteAt)
// Check the channel now uses the default scheme
c2, resp := th.SystemAdminClient.GetChannelByName(channel.Name, channel.TeamId, "")
CheckNoError(t, resp)
c2, _, err := th.SystemAdminClient.GetChannelByName(channel.Name, channel.TeamId, "")
require.NoError(t, err)
assert.Equal(t, "", *c2.SchemeId)
})
@ -733,31 +742,36 @@ func TestDeleteScheme(t *testing.T) {
Scope: model.SchemeScopeChannel,
}
s1, r1 := th.SystemAdminClient.CreateScheme(scheme1)
CheckNoError(t, r1)
s1, _, err := th.SystemAdminClient.CreateScheme(scheme1)
require.NoError(t, err)
// Test with unknown ID.
_, r2 := th.SystemAdminClient.DeleteScheme(model.NewId())
r2, err := th.SystemAdminClient.DeleteScheme(model.NewId())
require.Error(t, err)
CheckNotFoundStatus(t, r2)
// Test with invalid ID.
_, r3 := th.SystemAdminClient.DeleteScheme("12345")
r3, err := th.SystemAdminClient.DeleteScheme("12345")
require.Error(t, err)
CheckBadRequestStatus(t, r3)
// Test without required permissions.
_, r4 := th.Client.DeleteScheme(s1.Id)
r4, err := th.Client.DeleteScheme(s1.Id)
require.Error(t, err)
CheckForbiddenStatus(t, r4)
// Test without license.
th.App.Srv().SetLicense(nil)
_, r5 := th.SystemAdminClient.DeleteScheme(s1.Id)
r5, err := th.SystemAdminClient.DeleteScheme(s1.Id)
require.Error(t, err)
CheckNotImplementedStatus(t, r5)
th.App.SetPhase2PermissionsMigrationStatus(false)
th.App.Srv().SetLicense(model.NewTestLicense("custom_permissions_schemes"))
_, r6 := th.SystemAdminClient.DeleteScheme(s1.Id)
r6, err := th.SystemAdminClient.DeleteScheme(s1.Id)
require.Error(t, err)
CheckNotImplementedStatus(t, r6)
})
}
@ -770,27 +784,27 @@ func TestUpdateTeamSchemeWithTeamMembers(t *testing.T) {
th.App.SetPhase2PermissionsMigrationStatus(true)
team := th.CreateTeam()
_, _, err := th.App.AddUserToTeam(th.Context, team.Id, th.BasicUser.Id, th.SystemAdminUser.Id)
require.Nil(t, err)
_, _, appErr := th.App.AddUserToTeam(th.Context, team.Id, th.BasicUser.Id, th.SystemAdminUser.Id)
require.Nil(t, appErr)
teamScheme := th.SetupTeamScheme()
teamUserRole, err := th.App.GetRoleByName(context.Background(), teamScheme.DefaultTeamUserRole)
require.Nil(t, err)
teamUserRole, appErr := th.App.GetRoleByName(context.Background(), teamScheme.DefaultTeamUserRole)
require.Nil(t, appErr)
teamUserRole.Permissions = []string{}
_, err = th.App.UpdateRole(teamUserRole)
require.Nil(t, err)
_, appErr = th.App.UpdateRole(teamUserRole)
require.Nil(t, appErr)
th.LoginBasic()
_, resp := th.Client.CreateChannel(&model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.ChannelTypeOpen, TeamId: team.Id})
require.Nil(t, resp.Error)
_, _, err := th.Client.CreateChannel(&model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.ChannelTypeOpen, TeamId: team.Id})
require.NoError(t, err)
team.SchemeId = &teamScheme.Id
team, err = th.App.UpdateTeamScheme(team)
require.Nil(t, err)
team, appErr = th.App.UpdateTeamScheme(team)
require.Nil(t, appErr)
_, resp = th.Client.CreateChannel(&model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.ChannelTypeOpen, TeamId: team.Id})
require.NotNil(t, resp.Error)
_, _, err = th.Client.CreateChannel(&model.Channel{DisplayName: "Test API Name", Name: GenerateTestChannelName(), Type: model.ChannelTypeOpen, TeamId: team.Id})
require.Error(t, err)
})
}

View file

@ -53,8 +53,8 @@ func TestGetAllSharedChannels(t *testing.T) {
t.Run("get shared channels paginated", func(t *testing.T) {
channelIds := make([]string, 0, 21)
for i := 0; i < pages; i++ {
channels, resp := th.Client.GetAllSharedChannels(th.BasicTeam.Id, i, pageSize)
CheckNoError(t, resp)
channels, _, err := th.Client.GetAllSharedChannels(th.BasicTeam.Id, i, pageSize)
require.NoError(t, err)
channelIds = append(channelIds, getIds(channels)...)
}
sort.Strings(channelIds)
@ -64,8 +64,8 @@ func TestGetAllSharedChannels(t *testing.T) {
})
t.Run("get shared channels for invalid team", func(t *testing.T) {
channels, resp := th.Client.GetAllSharedChannels(model.NewId(), 0, 100)
CheckNoError(t, resp)
channels, _, err := th.Client.GetAllSharedChannels(model.NewId(), 0, 100)
require.NoError(t, err)
assert.Empty(t, channels)
})
}
@ -128,13 +128,14 @@ func TestGetRemoteClusterById(t *testing.T) {
require.NoError(t, err)
t.Run("valid remote, user is member", func(t *testing.T) {
rcInfo, resp := th.Client.GetRemoteClusterInfo(rc.RemoteId)
CheckNoError(t, resp)
rcInfo, _, err := th.Client.GetRemoteClusterInfo(rc.RemoteId)
require.NoError(t, err)
assert.Equal(t, rc.Name, rcInfo.Name)
})
t.Run("invalid remote", func(t *testing.T) {
_, resp := th.Client.GetRemoteClusterInfo(model.NewId())
_, resp, err := th.Client.GetRemoteClusterInfo(model.NewId())
require.Error(t, err)
CheckNotFoundStatus(t, resp)
})
@ -144,17 +145,17 @@ func TestCreateDirectChannelWithRemoteUser(t *testing.T) {
t.Run("creates a local DM channel that is shared", func(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
defer Client.Logout()
client := th.Client
defer client.Logout()
localUser := th.BasicUser
remoteUser := th.CreateUser()
remoteUser.RemoteId = model.NewString(model.NewId())
remoteUser, err := th.App.UpdateUser(remoteUser, false)
require.Nil(t, err)
remoteUser, appErr := th.App.UpdateUser(remoteUser, false)
require.Nil(t, appErr)
dm, resp := Client.CreateDirectChannel(localUser.Id, remoteUser.Id)
CheckNoError(t, resp)
dm, _, err := client.CreateDirectChannel(localUser.Id, remoteUser.Id)
require.NoError(t, err)
channelName := model.GetDMNameFromIds(localUser.Id, remoteUser.Id)
require.Equal(t, channelName, dm.Name, "dm name didn't match")
@ -164,8 +165,8 @@ func TestCreateDirectChannelWithRemoteUser(t *testing.T) {
t.Run("sends a shared channel invitation to the remote", func(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
defer Client.Logout()
client := th.Client
defer client.Logout()
mockService := app.NewMockSharedChannelService(nil, app.MockOptionSharedChannelServiceWithActive(true))
th.App.Srv().SetSharedChannelSyncService(mockService)
@ -177,15 +178,15 @@ func TestCreateDirectChannelWithRemoteUser(t *testing.T) {
Token: model.NewId(),
CreatorId: localUser.Id,
}
rc, err := th.App.AddRemoteCluster(rc)
require.Nil(t, err)
rc, appErr := th.App.AddRemoteCluster(rc)
require.Nil(t, appErr)
remoteUser.RemoteId = model.NewString(rc.RemoteId)
remoteUser, err = th.App.UpdateUser(remoteUser, false)
require.Nil(t, err)
remoteUser, appErr = th.App.UpdateUser(remoteUser, false)
require.Nil(t, appErr)
dm, resp := Client.CreateDirectChannel(localUser.Id, remoteUser.Id)
CheckNoError(t, resp)
dm, _, err := client.CreateDirectChannel(localUser.Id, remoteUser.Id)
require.NoError(t, err)
channelName := model.GetDMNameFromIds(localUser.Id, remoteUser.Id)
require.Equal(t, channelName, dm.Name, "dm name didn't match")
@ -197,8 +198,8 @@ func TestCreateDirectChannelWithRemoteUser(t *testing.T) {
t.Run("does not send a shared channel invitation to the remote when creator is remote", func(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
defer Client.Logout()
client := th.Client
defer client.Logout()
mockService := app.NewMockSharedChannelService(nil, app.MockOptionSharedChannelServiceWithActive(true))
th.App.Srv().SetSharedChannelSyncService(mockService)
@ -210,15 +211,15 @@ func TestCreateDirectChannelWithRemoteUser(t *testing.T) {
Token: model.NewId(),
CreatorId: localUser.Id,
}
rc, err := th.App.AddRemoteCluster(rc)
require.Nil(t, err)
rc, appErr := th.App.AddRemoteCluster(rc)
require.Nil(t, appErr)
remoteUser.RemoteId = model.NewString(rc.RemoteId)
remoteUser, err = th.App.UpdateUser(remoteUser, false)
require.Nil(t, err)
remoteUser, appErr = th.App.UpdateUser(remoteUser, false)
require.Nil(t, appErr)
dm, resp := Client.CreateDirectChannel(remoteUser.Id, localUser.Id)
CheckNoError(t, resp)
dm, _, err := client.CreateDirectChannel(remoteUser.Id, localUser.Id)
require.NoError(t, err)
channelName := model.GetDMNameFromIds(localUser.Id, remoteUser.Id)
require.Equal(t, channelName, dm.Name, "dm name didn't match")

View file

@ -8,6 +8,7 @@ import (
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/mattermost/mattermost-server/v6/model"
)
@ -15,39 +16,39 @@ import (
func TestGetUserStatus(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
t.Run("offline status", func(t *testing.T) {
userStatus, resp := Client.GetUserStatus(th.BasicUser.Id, "")
CheckNoError(t, resp)
userStatus, _, err := client.GetUserStatus(th.BasicUser.Id, "")
require.NoError(t, err)
assert.Equal(t, "offline", userStatus.Status)
})
t.Run("online status", func(t *testing.T) {
th.App.SetStatusOnline(th.BasicUser.Id, true)
userStatus, resp := Client.GetUserStatus(th.BasicUser.Id, "")
CheckNoError(t, resp)
userStatus, _, err := client.GetUserStatus(th.BasicUser.Id, "")
require.NoError(t, err)
assert.Equal(t, "online", userStatus.Status)
})
t.Run("away status", func(t *testing.T) {
th.App.SetStatusAwayIfNeeded(th.BasicUser.Id, true)
userStatus, resp := Client.GetUserStatus(th.BasicUser.Id, "")
CheckNoError(t, resp)
userStatus, _, err := client.GetUserStatus(th.BasicUser.Id, "")
require.NoError(t, err)
assert.Equal(t, "away", userStatus.Status)
})
t.Run("dnd status", func(t *testing.T) {
th.App.SetStatusDoNotDisturb(th.BasicUser.Id)
userStatus, resp := Client.GetUserStatus(th.BasicUser.Id, "")
CheckNoError(t, resp)
userStatus, _, err := client.GetUserStatus(th.BasicUser.Id, "")
require.NoError(t, err)
assert.Equal(t, "dnd", userStatus.Status)
})
t.Run("dnd status timed", func(t *testing.T) {
th.App.SetStatusDoNotDisturbTimed(th.BasicUser.Id, time.Now().Add(10*time.Minute).Unix())
userStatus, resp := Client.GetUserStatus(th.BasicUser.Id, "")
CheckNoError(t, resp)
userStatus, _, err := client.GetUserStatus(th.BasicUser.Id, "")
require.NoError(t, err)
assert.Equal(t, "dnd", userStatus.Status)
})
@ -55,43 +56,44 @@ func TestGetUserStatus(t *testing.T) {
task := model.CreateRecurringTaskFromNextIntervalTime("Unset DND Statuses From Test", th.App.UpdateDNDStatusOfUsers, 1*time.Second)
defer task.Cancel()
th.App.SetStatusOnline(th.BasicUser.Id, true)
userStatus, resp := Client.GetUserStatus(th.BasicUser.Id, "")
CheckNoError(t, resp)
userStatus, _, err := client.GetUserStatus(th.BasicUser.Id, "")
require.NoError(t, err)
assert.Equal(t, "online", userStatus.Status)
th.App.SetStatusDoNotDisturbTimed(th.BasicUser.Id, time.Now().Add(2*time.Second).Unix())
userStatus, resp = Client.GetUserStatus(th.BasicUser.Id, "")
CheckNoError(t, resp)
userStatus, _, err = client.GetUserStatus(th.BasicUser.Id, "")
require.NoError(t, err)
assert.Equal(t, "dnd", userStatus.Status)
time.Sleep(3 * time.Second)
userStatus, resp = Client.GetUserStatus(th.BasicUser.Id, "")
CheckNoError(t, resp)
userStatus, _, err = client.GetUserStatus(th.BasicUser.Id, "")
require.NoError(t, err)
assert.Equal(t, "online", userStatus.Status)
})
t.Run("back to offline status", func(t *testing.T) {
th.App.SetStatusOffline(th.BasicUser.Id, true)
userStatus, resp := Client.GetUserStatus(th.BasicUser.Id, "")
CheckNoError(t, resp)
userStatus, _, err := client.GetUserStatus(th.BasicUser.Id, "")
require.NoError(t, err)
assert.Equal(t, "offline", userStatus.Status)
})
t.Run("get other user status", func(t *testing.T) {
//Get user2 status logged as user1
userStatus, resp := Client.GetUserStatus(th.BasicUser2.Id, "")
CheckNoError(t, resp)
userStatus, _, err := client.GetUserStatus(th.BasicUser2.Id, "")
require.NoError(t, err)
assert.Equal(t, "offline", userStatus.Status)
})
t.Run("get status from logged out user", func(t *testing.T) {
Client.Logout()
_, resp := Client.GetUserStatus(th.BasicUser2.Id, "")
client.Logout()
_, resp, err := client.GetUserStatus(th.BasicUser2.Id, "")
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
})
t.Run("get status from other user", func(t *testing.T) {
th.LoginBasic2()
userStatus, resp := Client.GetUserStatus(th.BasicUser2.Id, "")
CheckNoError(t, resp)
userStatus, _, err := client.GetUserStatus(th.BasicUser2.Id, "")
require.NoError(t, err)
assert.Equal(t, "offline", userStatus.Status)
})
}
@ -99,28 +101,31 @@ func TestGetUserStatus(t *testing.T) {
func TestGetUsersStatusesByIds(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
usersIds := []string{th.BasicUser.Id, th.BasicUser2.Id}
t.Run("empty userIds list", func(t *testing.T) {
_, resp := Client.GetUsersStatusesByIds([]string{})
_, resp, err := client.GetUsersStatusesByIds([]string{})
require.Error(t, err)
CheckBadRequestStatus(t, resp)
})
t.Run("completely invalid userIds list", func(t *testing.T) {
_, resp := Client.GetUsersStatusesByIds([]string{"invalid_user_id", "invalid_user_id"})
_, resp, err := client.GetUsersStatusesByIds([]string{"invalid_user_id", "invalid_user_id"})
require.Error(t, err)
CheckBadRequestStatus(t, resp)
})
t.Run("partly invalid userIds list", func(t *testing.T) {
_, resp := Client.GetUsersStatusesByIds([]string{th.BasicUser.Id, "invalid_user_id"})
_, resp, err := client.GetUsersStatusesByIds([]string{th.BasicUser.Id, "invalid_user_id"})
require.Error(t, err)
CheckBadRequestStatus(t, resp)
})
t.Run("offline status", func(t *testing.T) {
usersStatuses, resp := Client.GetUsersStatusesByIds(usersIds)
CheckNoError(t, resp)
usersStatuses, _, err := client.GetUsersStatusesByIds(usersIds)
require.NoError(t, err)
for _, userStatus := range usersStatuses {
assert.Equal(t, "offline", userStatus.Status)
}
@ -129,8 +134,8 @@ func TestGetUsersStatusesByIds(t *testing.T) {
t.Run("online status", func(t *testing.T) {
th.App.SetStatusOnline(th.BasicUser.Id, true)
th.App.SetStatusOnline(th.BasicUser2.Id, true)
usersStatuses, resp := Client.GetUsersStatusesByIds(usersIds)
CheckNoError(t, resp)
usersStatuses, _, err := client.GetUsersStatusesByIds(usersIds)
require.NoError(t, err)
for _, userStatus := range usersStatuses {
assert.Equal(t, "online", userStatus.Status)
}
@ -139,8 +144,8 @@ func TestGetUsersStatusesByIds(t *testing.T) {
t.Run("away status", func(t *testing.T) {
th.App.SetStatusAwayIfNeeded(th.BasicUser.Id, true)
th.App.SetStatusAwayIfNeeded(th.BasicUser2.Id, true)
usersStatuses, resp := Client.GetUsersStatusesByIds(usersIds)
CheckNoError(t, resp)
usersStatuses, _, err := client.GetUsersStatusesByIds(usersIds)
require.NoError(t, err)
for _, userStatus := range usersStatuses {
assert.Equal(t, "away", userStatus.Status)
}
@ -149,8 +154,8 @@ func TestGetUsersStatusesByIds(t *testing.T) {
t.Run("dnd status", func(t *testing.T) {
th.App.SetStatusDoNotDisturb(th.BasicUser.Id)
th.App.SetStatusDoNotDisturb(th.BasicUser2.Id)
usersStatuses, resp := Client.GetUsersStatusesByIds(usersIds)
CheckNoError(t, resp)
usersStatuses, _, err := client.GetUsersStatusesByIds(usersIds)
require.NoError(t, err)
for _, userStatus := range usersStatuses {
assert.Equal(t, "dnd", userStatus.Status)
}
@ -159,17 +164,18 @@ func TestGetUsersStatusesByIds(t *testing.T) {
t.Run("dnd status", func(t *testing.T) {
th.App.SetStatusDoNotDisturbTimed(th.BasicUser.Id, time.Now().Add(10*time.Minute).Unix())
th.App.SetStatusDoNotDisturbTimed(th.BasicUser2.Id, time.Now().Add(15*time.Minute).Unix())
usersStatuses, resp := Client.GetUsersStatusesByIds(usersIds)
CheckNoError(t, resp)
usersStatuses, _, err := client.GetUsersStatusesByIds(usersIds)
require.NoError(t, err)
for _, userStatus := range usersStatuses {
assert.Equal(t, "dnd", userStatus.Status)
}
})
t.Run("get statuses from logged out user", func(t *testing.T) {
Client.Logout()
client.Logout()
_, resp := Client.GetUsersStatusesByIds(usersIds)
_, resp, err := client.GetUsersStatusesByIds(usersIds)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
})
}
@ -177,59 +183,62 @@ func TestGetUsersStatusesByIds(t *testing.T) {
func TestUpdateUserStatus(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
t.Run("set online status", func(t *testing.T) {
toUpdateUserStatus := &model.Status{Status: "online", UserId: th.BasicUser.Id}
updateUserStatus, resp := Client.UpdateUserStatus(th.BasicUser.Id, toUpdateUserStatus)
CheckNoError(t, resp)
updateUserStatus, _, err := client.UpdateUserStatus(th.BasicUser.Id, toUpdateUserStatus)
require.NoError(t, err)
assert.Equal(t, "online", updateUserStatus.Status)
})
t.Run("set away status", func(t *testing.T) {
toUpdateUserStatus := &model.Status{Status: "away", UserId: th.BasicUser.Id}
updateUserStatus, resp := Client.UpdateUserStatus(th.BasicUser.Id, toUpdateUserStatus)
CheckNoError(t, resp)
updateUserStatus, _, err := client.UpdateUserStatus(th.BasicUser.Id, toUpdateUserStatus)
require.NoError(t, err)
assert.Equal(t, "away", updateUserStatus.Status)
})
t.Run("set dnd status timed", func(t *testing.T) {
toUpdateUserStatus := &model.Status{Status: "dnd", UserId: th.BasicUser.Id, DNDEndTime: time.Now().Add(10 * time.Minute).Unix()}
updateUserStatus, resp := Client.UpdateUserStatus(th.BasicUser.Id, toUpdateUserStatus)
CheckNoError(t, resp)
updateUserStatus, _, err := client.UpdateUserStatus(th.BasicUser.Id, toUpdateUserStatus)
require.NoError(t, err)
assert.Equal(t, "dnd", updateUserStatus.Status)
})
t.Run("set offline status", func(t *testing.T) {
toUpdateUserStatus := &model.Status{Status: "offline", UserId: th.BasicUser.Id}
updateUserStatus, resp := Client.UpdateUserStatus(th.BasicUser.Id, toUpdateUserStatus)
CheckNoError(t, resp)
updateUserStatus, _, err := client.UpdateUserStatus(th.BasicUser.Id, toUpdateUserStatus)
require.NoError(t, err)
assert.Equal(t, "offline", updateUserStatus.Status)
})
t.Run("set status for other user as regular user", func(t *testing.T) {
toUpdateUserStatus := &model.Status{Status: "online", UserId: th.BasicUser2.Id}
_, resp := Client.UpdateUserStatus(th.BasicUser2.Id, toUpdateUserStatus)
_, resp, err := client.UpdateUserStatus(th.BasicUser2.Id, toUpdateUserStatus)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("set status for other user as admin user", func(t *testing.T) {
toUpdateUserStatus := &model.Status{Status: "online", UserId: th.BasicUser2.Id}
updateUserStatus, _ := th.SystemAdminClient.UpdateUserStatus(th.BasicUser2.Id, toUpdateUserStatus)
updateUserStatus, _, _ := th.SystemAdminClient.UpdateUserStatus(th.BasicUser2.Id, toUpdateUserStatus)
assert.Equal(t, "online", updateUserStatus.Status)
})
t.Run("not matching status user id and the user id passed in the function", func(t *testing.T) {
toUpdateUserStatus := &model.Status{Status: "online", UserId: th.BasicUser2.Id}
_, resp := Client.UpdateUserStatus(th.BasicUser.Id, toUpdateUserStatus)
_, resp, err := client.UpdateUserStatus(th.BasicUser.Id, toUpdateUserStatus)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
})
t.Run("get statuses from logged out user", func(t *testing.T) {
toUpdateUserStatus := &model.Status{Status: "online", UserId: th.BasicUser2.Id}
Client.Logout()
client.Logout()
_, resp := Client.UpdateUserStatus(th.BasicUser2.Id, toUpdateUserStatus)
_, resp, err := client.UpdateUserStatus(th.BasicUser2.Id, toUpdateUserStatus)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
})
}

View file

@ -28,8 +28,8 @@ func TestGetPing(t *testing.T) {
th.TestForAllClients(t, func(t *testing.T, client *model.Client4) {
t.Run("healthy", func(t *testing.T) {
status, resp := client.GetPing()
CheckNoError(t, resp)
status, _, err := client.GetPing()
require.NoError(t, err)
assert.Equal(t, model.StatusOk, status)
})
@ -40,7 +40,8 @@ func TestGetPing(t *testing.T) {
}()
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.GoroutineHealthThreshold = 10 })
status, resp := client.GetPing()
status, resp, err := client.GetPing()
require.Error(t, err)
CheckInternalErrorStatus(t, resp)
assert.Equal(t, model.StatusUnhealthy, status)
})
@ -48,9 +49,8 @@ func TestGetPing(t *testing.T) {
th.TestForAllClients(t, func(t *testing.T, client *model.Client4) {
t.Run("healthy", func(t *testing.T) {
status, resp := client.GetPingWithServerStatus()
CheckNoError(t, resp)
status, _, err := client.GetPingWithServerStatus()
require.NoError(t, err)
assert.Equal(t, model.StatusOk, status)
})
@ -62,7 +62,8 @@ func TestGetPing(t *testing.T) {
th.App.Config().FileSettings.DriverName = oldDriver
}()
status, resp := client.GetPingWithServerStatus()
status, resp, err := client.GetPingWithServerStatus()
require.Error(t, err)
CheckInternalErrorStatus(t, resp)
assert.Equal(t, model.StatusUnhealthy, status)
})
@ -70,8 +71,8 @@ func TestGetPing(t *testing.T) {
th.TestForAllClients(t, func(t *testing.T, client *model.Client4) {
th.App.ReloadConfig()
resp, appErr := client.DoApiGet(client.GetSystemRoute()+"/ping", "")
require.Nil(t, appErr)
resp, err := client.DoApiGet(client.GetSystemRoute()+"/ping", "")
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
respBytes, err := ioutil.ReadAll(resp.Body)
require.NoError(t, err)
@ -83,8 +84,8 @@ func TestGetPing(t *testing.T) {
defer os.Unsetenv("MM_FEATUREFLAGS_TESTFEATURE")
th.App.ReloadConfig()
resp, appErr = client.DoApiGet(client.GetSystemRoute()+"/ping", "")
require.Nil(t, appErr)
resp, err = client.DoApiGet(client.GetSystemRoute()+"/ping", "")
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
respBytes, err = ioutil.ReadAll(resp.Body)
require.NoError(t, err)
@ -96,35 +97,37 @@ func TestGetPing(t *testing.T) {
func TestGetAudits(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
client := th.Client
audits, resp := th.SystemAdminClient.GetAudits(0, 100, "")
CheckNoError(t, resp)
audits, _, err := th.SystemAdminClient.GetAudits(0, 100, "")
require.NoError(t, err)
require.NotEmpty(t, audits, "should not be empty")
audits, resp = th.SystemAdminClient.GetAudits(0, 1, "")
CheckNoError(t, resp)
audits, _, err = th.SystemAdminClient.GetAudits(0, 1, "")
require.NoError(t, err)
require.Len(t, audits, 1, "should only be 1")
audits, resp = th.SystemAdminClient.GetAudits(1, 1, "")
CheckNoError(t, resp)
audits, _, err = th.SystemAdminClient.GetAudits(1, 1, "")
require.NoError(t, err)
require.Len(t, audits, 1, "should only be 1")
_, resp = th.SystemAdminClient.GetAudits(-1, -1, "")
CheckNoError(t, resp)
_, _, err = th.SystemAdminClient.GetAudits(-1, -1, "")
require.NoError(t, err)
_, resp = Client.GetAudits(0, 100, "")
_, resp, err := client.GetAudits(0, 100, "")
require.Error(t, err)
CheckForbiddenStatus(t, resp)
Client.Logout()
_, resp = Client.GetAudits(0, 100, "")
client.Logout()
_, resp, err = client.GetAudits(0, 100, "")
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
}
func TestEmailTest(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
client := th.Client
dir, err := ioutil.TempDir("", "")
require.NoError(t, err)
@ -155,13 +158,14 @@ func TestEmailTest(t *testing.T) {
}
t.Run("as system user", func(t *testing.T) {
_, resp := Client.TestEmail(&config)
resp, err := client.TestEmail(&config)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("as system admin", func(t *testing.T) {
_, resp := th.SystemAdminClient.TestEmail(&config)
CheckErrorMessage(t, resp, "api.admin.test_email.missing_server")
resp, err := th.SystemAdminClient.TestEmail(&config)
CheckErrorID(t, err, "api.admin.test_email.missing_server")
CheckBadRequestStatus(t, resp)
inbucket_host := os.Getenv("CI_INBUCKET_HOST")
@ -176,14 +180,16 @@ func TestEmailTest(t *testing.T) {
*config.EmailSettings.SMTPServer = inbucket_host
*config.EmailSettings.SMTPPort = inbucket_port
_, resp = th.SystemAdminClient.TestEmail(&config)
resp, err = th.SystemAdminClient.TestEmail(&config)
require.NoError(t, err)
CheckOKStatus(t, resp)
})
t.Run("as restricted system admin", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
_, resp := th.SystemAdminClient.TestEmail(&config)
resp, err := th.SystemAdminClient.TestEmail(&config)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
}
@ -196,22 +202,23 @@ func TestGenerateSupportPacket(t *testing.T) {
l := model.NewTestLicense()
th.App.Srv().SetLicense(l)
file, resp := th.SystemAdminClient.GenerateSupportPacket()
require.Nil(t, resp.Error)
file, _, err := th.SystemAdminClient.GenerateSupportPacket()
require.NoError(t, err)
require.NotZero(t, len(file))
})
t.Run("As a Regular User", func(t *testing.T) {
_, resp := th.Client.GenerateSupportPacket()
_, resp, err := th.Client.GenerateSupportPacket()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("Server with no License", func(t *testing.T) {
ok, resp := th.SystemAdminClient.RemoveLicenseFile()
CheckNoError(t, resp)
require.True(t, ok)
_, err := th.SystemAdminClient.RemoveLicenseFile()
require.NoError(t, err)
_, resp = th.SystemAdminClient.GenerateSupportPacket()
_, resp, err := th.SystemAdminClient.GenerateSupportPacket()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
}
@ -219,7 +226,7 @@ func TestGenerateSupportPacket(t *testing.T) {
func TestSiteURLTest(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
client := th.Client
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/valid/api/v4/system/ping") {
@ -234,25 +241,30 @@ func TestSiteURLTest(t *testing.T) {
invalidSiteURL := ts.URL + "/invalid"
t.Run("as system admin", func(t *testing.T) {
_, resp := th.SystemAdminClient.TestSiteURL("")
resp, err := th.SystemAdminClient.TestSiteURL("")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = th.SystemAdminClient.TestSiteURL(invalidSiteURL)
resp, err = th.SystemAdminClient.TestSiteURL(invalidSiteURL)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = th.SystemAdminClient.TestSiteURL(validSiteURL)
resp, err = th.SystemAdminClient.TestSiteURL(validSiteURL)
require.NoError(t, err)
CheckOKStatus(t, resp)
})
t.Run("as system user", func(t *testing.T) {
_, resp := Client.TestSiteURL(validSiteURL)
resp, err := client.TestSiteURL(validSiteURL)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("as restricted system admin", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
_, resp := Client.TestSiteURL(validSiteURL)
resp, err := client.TestSiteURL(validSiteURL)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
}
@ -260,22 +272,24 @@ func TestSiteURLTest(t *testing.T) {
func TestDatabaseRecycle(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
client := th.Client
t.Run("as system user", func(t *testing.T) {
_, resp := Client.DatabaseRecycle()
resp, err := client.DatabaseRecycle()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("as system admin", func(t *testing.T) {
_, resp := th.SystemAdminClient.DatabaseRecycle()
CheckNoError(t, resp)
_, err := th.SystemAdminClient.DatabaseRecycle()
require.NoError(t, err)
})
t.Run("as restricted system admin", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
_, resp := th.SystemAdminClient.DatabaseRecycle()
resp, err := th.SystemAdminClient.DatabaseRecycle()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
}
@ -283,26 +297,25 @@ func TestDatabaseRecycle(t *testing.T) {
func TestInvalidateCaches(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
client := th.Client
t.Run("as system user", func(t *testing.T) {
ok, resp := Client.InvalidateCaches()
resp, err := client.InvalidateCaches()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
require.False(t, ok, "should not clean the cache due to no permission.")
})
t.Run("as system admin", func(t *testing.T) {
ok, resp := th.SystemAdminClient.InvalidateCaches()
CheckNoError(t, resp)
require.True(t, ok, "should clean the cache")
_, err := th.SystemAdminClient.InvalidateCaches()
require.NoError(t, err)
})
t.Run("as restricted system admin", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
ok, resp := th.SystemAdminClient.InvalidateCaches()
resp, err := th.SystemAdminClient.InvalidateCaches()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
require.False(t, ok, "should not clean the cache due to no permission.")
})
}
@ -315,41 +328,44 @@ func TestGetLogs(t *testing.T) {
}
th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) {
logs, resp := c.GetLogs(0, 10)
CheckNoError(t, resp)
logs, _, err := c.GetLogs(0, 10)
require.NoError(t, err)
require.Len(t, logs, 10)
for i := 10; i < 20; i++ {
assert.Containsf(t, logs[i-10], fmt.Sprintf(`"msg":"%d"`, i), "Log line doesn't contain correct message")
}
logs, resp = c.GetLogs(1, 10)
CheckNoError(t, resp)
logs, _, err = c.GetLogs(1, 10)
require.NoError(t, err)
require.Len(t, logs, 10)
logs, resp = c.GetLogs(-1, -1)
CheckNoError(t, resp)
logs, _, err = c.GetLogs(-1, -1)
require.NoError(t, err)
require.NotEmpty(t, logs, "should not be empty")
})
th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
_, resp := th.Client.GetLogs(0, 10)
_, resp, err := th.Client.GetLogs(0, 10)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
_, resp := th.Client.GetLogs(0, 10)
_, resp, err := th.Client.GetLogs(0, 10)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
th.Client.Logout()
_, resp = th.Client.GetLogs(0, 10)
_, resp, err = th.Client.GetLogs(0, 10)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
}
func TestPostLog(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
client := th.Client
enableDev := *th.App.Config().ServiceSettings.EnableDeveloper
defer func() {
@ -361,28 +377,29 @@ func TestPostLog(t *testing.T) {
message["level"] = "ERROR"
message["message"] = "this is a test"
_, resp := Client.PostLog(message)
CheckNoError(t, resp)
_, _, err := client.PostLog(message)
require.NoError(t, err)
*th.App.Config().ServiceSettings.EnableDeveloper = false
_, resp = Client.PostLog(message)
CheckNoError(t, resp)
_, _, err = client.PostLog(message)
require.NoError(t, err)
*th.App.Config().ServiceSettings.EnableDeveloper = true
Client.Logout()
client.Logout()
_, resp = Client.PostLog(message)
CheckNoError(t, resp)
_, _, err = client.PostLog(message)
require.NoError(t, err)
*th.App.Config().ServiceSettings.EnableDeveloper = false
_, resp = Client.PostLog(message)
_, resp, err := client.PostLog(message)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
logMessage, resp := th.SystemAdminClient.PostLog(message)
CheckNoError(t, resp)
logMessage, _, err := th.SystemAdminClient.PostLog(message)
require.NoError(t, err)
require.NotEmpty(t, logMessage, "should return the log message")
}
@ -390,13 +407,14 @@ func TestPostLog(t *testing.T) {
func TestGetAnalyticsOld(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
rows, resp := Client.GetAnalyticsOld("", "")
rows, resp, err := client.GetAnalyticsOld("", "")
require.Error(t, err)
CheckForbiddenStatus(t, resp)
require.Nil(t, rows, "should be nil")
rows, resp = th.SystemAdminClient.GetAnalyticsOld("", "")
CheckNoError(t, resp)
rows, _, err = th.SystemAdminClient.GetAnalyticsOld("", "")
require.NoError(t, err)
found := false
found2 := false
@ -412,17 +430,17 @@ func TestGetAnalyticsOld(t *testing.T) {
assert.True(t, found, "should return unique user count")
assert.True(t, found2, "should return inactive user count")
_, resp = th.SystemAdminClient.GetAnalyticsOld("post_counts_day", "")
CheckNoError(t, resp)
_, _, err = th.SystemAdminClient.GetAnalyticsOld("post_counts_day", "")
require.NoError(t, err)
_, resp = th.SystemAdminClient.GetAnalyticsOld("user_counts_with_posts_day", "")
CheckNoError(t, resp)
_, _, err = th.SystemAdminClient.GetAnalyticsOld("user_counts_with_posts_day", "")
require.NoError(t, err)
_, resp = th.SystemAdminClient.GetAnalyticsOld("extra_counts", "")
CheckNoError(t, resp)
_, _, err = th.SystemAdminClient.GetAnalyticsOld("extra_counts", "")
require.NoError(t, err)
rows, resp = th.SystemAdminClient.GetAnalyticsOld("", th.BasicTeam.Id)
CheckNoError(t, resp)
rows, _, err = th.SystemAdminClient.GetAnalyticsOld("", th.BasicTeam.Id)
require.NoError(t, err)
for _, row := range rows {
if row.Name == "inactive_user_count" {
@ -430,35 +448,36 @@ func TestGetAnalyticsOld(t *testing.T) {
}
}
rows2, resp2 := th.SystemAdminClient.GetAnalyticsOld("standard", "")
CheckNoError(t, resp2)
rows2, _, err := th.SystemAdminClient.GetAnalyticsOld("standard", "")
require.NoError(t, err)
assert.Equal(t, "total_websocket_connections", rows2[5].Name)
assert.Equal(t, float64(0), rows2[5].Value)
WebSocketClient, err := th.CreateWebSocketClient()
require.Nil(t, err)
require.NoError(t, err)
time.Sleep(100 * time.Millisecond)
rows2, resp2 = th.SystemAdminClient.GetAnalyticsOld("standard", "")
CheckNoError(t, resp2)
rows2, _, err = th.SystemAdminClient.GetAnalyticsOld("standard", "")
require.NoError(t, err)
assert.Equal(t, "total_websocket_connections", rows2[5].Name)
assert.Equal(t, float64(1), rows2[5].Value)
WebSocketClient.Close()
rows2, resp2 = th.SystemAdminClient.GetAnalyticsOld("standard", "")
CheckNoError(t, resp2)
rows2, _, err = th.SystemAdminClient.GetAnalyticsOld("standard", "")
require.NoError(t, err)
assert.Equal(t, "total_websocket_connections", rows2[5].Name)
assert.Equal(t, float64(0), rows2[5].Value)
Client.Logout()
_, resp = Client.GetAnalyticsOld("", th.BasicTeam.Id)
client.Logout()
_, resp, err = client.GetAnalyticsOld("", th.BasicTeam.Id)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
}
func TestS3TestConnection(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
client := th.Client
s3Host := os.Getenv("CI_MINIO_HOST")
if s3Host == "" {
@ -485,49 +504,53 @@ func TestS3TestConnection(t *testing.T) {
}
t.Run("as system user", func(t *testing.T) {
_, resp := Client.TestS3Connection(&config)
resp, err := client.TestS3Connection(&config)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
t.Run("as system admin", func(t *testing.T) {
_, resp := th.SystemAdminClient.TestS3Connection(&config)
resp, err := th.SystemAdminClient.TestS3Connection(&config)
CheckBadRequestStatus(t, resp)
require.Equal(t, resp.Error.Message, "S3 Bucket is required", "should return error - missing s3 bucket")
CheckErrorMessage(t, err, "S3 Bucket is required")
// If this fails, check the test configuration to ensure minio is setup with the
// `mattermost-test` bucket defined by model.MINIO_BUCKET.
*config.FileSettings.AmazonS3Bucket = model.MinioBucket
config.FileSettings.AmazonS3PathPrefix = model.NewString("")
*config.FileSettings.AmazonS3Region = "us-east-1"
_, resp = th.SystemAdminClient.TestS3Connection(&config)
resp, err = th.SystemAdminClient.TestS3Connection(&config)
require.NoError(t, err)
CheckOKStatus(t, resp)
config.FileSettings.AmazonS3Region = model.NewString("")
_, resp = th.SystemAdminClient.TestS3Connection(&config)
resp, err = th.SystemAdminClient.TestS3Connection(&config)
require.NoError(t, err)
CheckOKStatus(t, resp)
config.FileSettings.AmazonS3Bucket = model.NewString("Wrong_bucket")
_, resp = th.SystemAdminClient.TestS3Connection(&config)
resp, err = th.SystemAdminClient.TestS3Connection(&config)
CheckInternalErrorStatus(t, resp)
assert.Equal(t, "api.file.test_connection_s3_bucket_does_not_exist.app_error", resp.Error.Id)
CheckErrorID(t, err, "api.file.test_connection_s3_bucket_does_not_exist.app_error")
*config.FileSettings.AmazonS3Bucket = "shouldnotcreatenewbucket"
_, resp = th.SystemAdminClient.TestS3Connection(&config)
resp, err = th.SystemAdminClient.TestS3Connection(&config)
CheckInternalErrorStatus(t, resp)
assert.Equal(t, "api.file.test_connection_s3_bucket_does_not_exist.app_error", resp.Error.Id)
CheckErrorID(t, err, "api.file.test_connection_s3_bucket_does_not_exist.app_error")
})
t.Run("with incorrect credentials", func(t *testing.T) {
configCopy := config
*configCopy.FileSettings.AmazonS3AccessKeyId = "invalidaccesskey"
_, resp := th.SystemAdminClient.TestS3Connection(&configCopy)
resp, err := th.SystemAdminClient.TestS3Connection(&configCopy)
CheckInternalErrorStatus(t, resp)
assert.Equal(t, "api.file.test_connection_s3_auth.app_error", resp.Error.Id)
CheckErrorID(t, err, "api.file.test_connection_s3_auth.app_error")
})
t.Run("as restricted system admin", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ExperimentalSettings.RestrictSystemAdmin = true })
_, resp := th.SystemAdminClient.TestS3Connection(&config)
resp, err := th.SystemAdminClient.TestS3Connection(&config)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
}
@ -535,12 +558,12 @@ func TestS3TestConnection(t *testing.T) {
func TestSupportedTimezones(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
client := th.Client
supportedTimezonesFromConfig := th.App.Timezones().GetSupported()
supportedTimezones, resp := Client.GetSupportedTimezone()
supportedTimezones, _, err := client.GetSupportedTimezone()
CheckNoError(t, resp)
require.NoError(t, err)
assert.Equal(t, supportedTimezonesFromConfig, supportedTimezones)
}
@ -558,7 +581,7 @@ func TestRedirectLocation(t *testing.T) {
th := Setup(t)
defer th.TearDown()
Client := th.Client
client := th.Client
enableLinkPreviews := *th.App.Config().ServiceSettings.EnableLinkPreviews
defer func() {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableLinkPreviews = enableLinkPreviews })
@ -567,36 +590,38 @@ func TestRedirectLocation(t *testing.T) {
*th.App.Config().ServiceSettings.EnableLinkPreviews = true
*th.App.Config().ServiceSettings.AllowedUntrustedInternalConnections = "127.0.0.1"
_, resp := th.SystemAdminClient.GetRedirectLocation("https://mattermost.com/", "")
CheckNoError(t, resp)
_, _, err := th.SystemAdminClient.GetRedirectLocation("https://mattermost.com/", "")
require.NoError(t, err)
_, resp = th.SystemAdminClient.GetRedirectLocation("", "")
_, resp, err := th.SystemAdminClient.GetRedirectLocation("", "")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
actual, resp := th.SystemAdminClient.GetRedirectLocation(mockBitlyLink, "")
CheckNoError(t, resp)
actual, _, err := th.SystemAdminClient.GetRedirectLocation(mockBitlyLink, "")
require.NoError(t, err)
assert.Equal(t, expected, actual)
// Check cached value
actual, resp = th.SystemAdminClient.GetRedirectLocation(mockBitlyLink, "")
CheckNoError(t, resp)
actual, _, err = th.SystemAdminClient.GetRedirectLocation(mockBitlyLink, "")
require.NoError(t, err)
assert.Equal(t, expected, actual)
*th.App.Config().ServiceSettings.EnableLinkPreviews = false
actual, resp = th.SystemAdminClient.GetRedirectLocation("https://mattermost.com/", "")
CheckNoError(t, resp)
actual, _, err = th.SystemAdminClient.GetRedirectLocation("https://mattermost.com/", "")
require.NoError(t, err)
assert.Equal(t, actual, "")
actual, resp = th.SystemAdminClient.GetRedirectLocation("", "")
CheckNoError(t, resp)
actual, _, err = th.SystemAdminClient.GetRedirectLocation("", "")
require.NoError(t, err)
assert.Equal(t, actual, "")
actual, resp = th.SystemAdminClient.GetRedirectLocation(mockBitlyLink, "")
CheckNoError(t, resp)
actual, _, err = th.SystemAdminClient.GetRedirectLocation(mockBitlyLink, "")
require.NoError(t, err)
assert.Equal(t, actual, "")
Client.Logout()
_, resp = Client.GetRedirectLocation("", "")
client.Logout()
_, resp, err = client.GetRedirectLocation("", "")
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
}
@ -607,16 +632,15 @@ func TestSetServerBusy(t *testing.T) {
const secs = 30
t.Run("as system user", func(t *testing.T) {
ok, resp := th.Client.SetServerBusy(secs)
resp, err := th.Client.SetServerBusy(secs)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
require.False(t, ok, "should not set server busy due to no permission")
require.False(t, th.App.Srv().Busy.IsBusy(), "server should not be marked busy")
})
th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) {
ok, resp := c.SetServerBusy(secs)
CheckNoError(t, resp)
require.True(t, ok, "should set server busy successfully")
_, err := c.SetServerBusy(secs)
require.NoError(t, err)
require.True(t, th.App.Srv().Busy.IsBusy(), "server should be marked busy")
}, "as system admin")
}
@ -628,9 +652,9 @@ func TestSetServerBusyInvalidParam(t *testing.T) {
th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) {
params := []int{-1, 0, MaxServerBusySeconds + 1}
for _, p := range params {
ok, resp := c.SetServerBusy(p)
resp, err := c.SetServerBusy(p)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
require.False(t, ok, "should not set server busy due to invalid param ", p)
require.False(t, th.App.Srv().Busy.IsBusy(), "server should not be marked busy due to invalid param ", p)
}
}, "as system admin, invalid param")
@ -642,17 +666,16 @@ func TestClearServerBusy(t *testing.T) {
th.App.Srv().Busy.Set(time.Second * 30)
t.Run("as system user", func(t *testing.T) {
ok, resp := th.Client.ClearServerBusy()
resp, err := th.Client.ClearServerBusy()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
require.False(t, ok, "should not clear server busy flag due to no permission.")
require.True(t, th.App.Srv().Busy.IsBusy(), "server should be marked busy")
})
th.App.Srv().Busy.Set(time.Second * 30)
th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) {
ok, resp := c.ClearServerBusy()
CheckNoError(t, resp)
require.True(t, ok, "should clear server busy flag successfully")
_, err := c.ClearServerBusy()
require.NoError(t, err)
require.False(t, th.App.Srv().Busy.IsBusy(), "server should not be marked busy")
}, "as system admin")
}
@ -664,14 +687,15 @@ func TestGetServerBusy(t *testing.T) {
th.App.Srv().Busy.Set(time.Second * 30)
t.Run("as system user", func(t *testing.T) {
_, resp := th.Client.GetServerBusy()
_, resp, err := th.Client.GetServerBusy()
require.Error(t, err)
CheckForbiddenStatus(t, resp)
})
th.TestForSystemAdminAndLocal(t, func(t *testing.T, c *model.Client4) {
sbs, resp := c.GetServerBusy()
sbs, _, err := c.GetServerBusy()
expires := time.Unix(sbs.Expires, 0)
CheckNoError(t, resp)
require.NoError(t, err)
require.Greater(t, expires.Unix(), time.Now().Unix())
}, "as system admin")
}
@ -684,25 +708,29 @@ func TestServerBusy503(t *testing.T) {
t.Run("search users while busy", func(t *testing.T) {
us := &model.UserSearch{Term: "test"}
_, resp := th.SystemAdminClient.SearchUsers(us)
_, resp, err := th.SystemAdminClient.SearchUsers(us)
require.Error(t, err)
CheckServiceUnavailableStatus(t, resp)
})
t.Run("search teams while busy", func(t *testing.T) {
ts := &model.TeamSearch{}
_, resp := th.SystemAdminClient.SearchTeams(ts)
_, resp, err := th.SystemAdminClient.SearchTeams(ts)
require.Error(t, err)
CheckServiceUnavailableStatus(t, resp)
})
t.Run("search channels while busy", func(t *testing.T) {
cs := &model.ChannelSearch{}
_, resp := th.SystemAdminClient.SearchChannels("foo", cs)
_, resp, err := th.SystemAdminClient.SearchChannels("foo", cs)
require.Error(t, err)
CheckServiceUnavailableStatus(t, resp)
})
t.Run("search archived channels while busy", func(t *testing.T) {
cs := &model.ChannelSearch{}
_, resp := th.SystemAdminClient.SearchArchivedChannels("foo", cs)
_, resp, err := th.SystemAdminClient.SearchArchivedChannels("foo", cs)
require.Error(t, err)
CheckServiceUnavailableStatus(t, resp)
})
@ -710,8 +738,8 @@ func TestServerBusy503(t *testing.T) {
t.Run("search users while not busy", func(t *testing.T) {
us := &model.UserSearch{Term: "test"}
_, resp := th.SystemAdminClient.SearchUsers(us)
CheckNoError(t, resp)
_, _, err := th.SystemAdminClient.SearchUsers(us)
require.NoError(t, err)
})
}

File diff suppressed because it is too large Load diff

View file

@ -15,13 +15,13 @@ import (
func TestGetTermsOfService(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
_, err := th.App.CreateTermsOfService("abc", th.BasicUser.Id)
require.Nil(t, err)
_, appErr := th.App.CreateTermsOfService("abc", th.BasicUser.Id)
require.Nil(t, appErr)
termsOfService, resp := Client.GetTermsOfService("")
CheckNoError(t, resp)
termsOfService, _, err := client.GetTermsOfService("")
require.NoError(t, err)
assert.NotNil(t, termsOfService)
assert.Equal(t, "abc", termsOfService.Text)
@ -32,25 +32,25 @@ func TestGetTermsOfService(t *testing.T) {
func TestCreateTermsOfService(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
_, resp := Client.CreateTermsOfService("terms of service new", th.BasicUser.Id)
CheckErrorMessage(t, resp, "api.context.permissions.app_error")
_, _, err := client.CreateTermsOfService("terms of service new", th.BasicUser.Id)
CheckErrorID(t, err, "api.context.permissions.app_error")
}
func TestCreateTermsOfServiceAdminUser(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.SystemAdminClient
client := th.SystemAdminClient
termsOfService, resp := Client.CreateTermsOfService("terms of service new", th.SystemAdminUser.Id)
CheckErrorMessage(t, resp, "api.create_terms_of_service.custom_terms_of_service_disabled.app_error")
termsOfService, _, err := client.CreateTermsOfService("terms of service new", th.SystemAdminUser.Id)
CheckErrorID(t, err, "api.create_terms_of_service.custom_terms_of_service_disabled.app_error")
assert.Nil(t, termsOfService)
th.App.Srv().SetLicense(model.NewTestLicense("EnableCustomTermsOfService"))
termsOfService, resp = Client.CreateTermsOfService("terms of service new_2", th.SystemAdminUser.Id)
CheckNoError(t, resp)
termsOfService, _, err = client.CreateTermsOfService("terms of service new_2", th.SystemAdminUser.Id)
require.NoError(t, err)
assert.NotEmpty(t, termsOfService.Id)
assert.NotEmpty(t, termsOfService.CreateAt)
assert.Equal(t, "terms of service new_2", termsOfService.Text)

View file

@ -30,26 +30,24 @@ func TestCreateUpload(t *testing.T) {
t.Run("file attachments disabled", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.EnableFileAttachments = false })
defer th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.EnableFileAttachments = true })
u, resp := th.Client.CreateUpload(us)
u, resp, err := th.Client.CreateUpload(us)
require.Nil(t, u)
require.NotNil(t, resp.Error)
require.Equal(t, "api.file.attachments.disabled.app_error", resp.Error.Id)
CheckErrorID(t, err, "api.file.attachments.disabled.app_error")
require.Equal(t, http.StatusNotImplemented, resp.StatusCode)
})
t.Run("no permissions", func(t *testing.T) {
us.ChannelId = th.BasicPrivateChannel2.Id
u, resp := th.Client.CreateUpload(us)
u, resp, err := th.Client.CreateUpload(us)
require.Nil(t, u)
require.NotNil(t, resp.Error)
require.Equal(t, "api.context.permissions.app_error", resp.Error.Id)
CheckErrorID(t, err, "api.context.permissions.app_error")
require.Equal(t, http.StatusForbidden, resp.StatusCode)
})
t.Run("valid", func(t *testing.T) {
us.ChannelId = th.BasicChannel.Id
u, resp := th.Client.CreateUpload(us)
require.Nil(t, resp.Error)
u, resp, err := th.Client.CreateUpload(us)
require.NoError(t, err)
require.NotEmpty(t, u)
require.Equal(t, http.StatusCreated, resp.StatusCode)
})
@ -70,10 +68,9 @@ func TestCreateUpload(t *testing.T) {
FileSize: info.Size(),
Type: model.UploadTypeImport,
}
u, resp := th.Client.CreateUpload(us)
u, resp, err := th.Client.CreateUpload(us)
require.Nil(t, u)
require.NotNil(t, resp.Error)
require.Equal(t, "api.context.permissions.app_error", resp.Error.Id)
CheckErrorID(t, err, "api.context.permissions.app_error")
require.Equal(t, http.StatusForbidden, resp.StatusCode)
})
@ -83,8 +80,8 @@ func TestCreateUpload(t *testing.T) {
FileSize: info.Size(),
Type: model.UploadTypeImport,
}
u, resp := th.SystemAdminClient.CreateUpload(us)
require.Nil(t, resp.Error)
u, _, err := th.SystemAdminClient.CreateUpload(us)
require.NoError(t, err)
require.NotEmpty(t, u)
})
})
@ -109,28 +106,26 @@ func TestGetUpload(t *testing.T) {
require.NotEmpty(t, us)
t.Run("upload not found", func(t *testing.T) {
u, resp := th.Client.GetUpload(model.NewId())
u, resp, err := th.Client.GetUpload(model.NewId())
require.Nil(t, u)
require.NotNil(t, resp.Error)
require.Equal(t, "app.upload.get.app_error", resp.Error.Id)
CheckErrorID(t, err, "app.upload.get.app_error")
require.Equal(t, http.StatusNotFound, resp.StatusCode)
})
t.Run("no permissions", func(t *testing.T) {
u, resp := th.Client.GetUpload(us.Id)
u, _, err := th.Client.GetUpload(us.Id)
require.Nil(t, u)
require.NotNil(t, resp.Error)
require.Equal(t, "api.upload.get_upload.forbidden.app_error", resp.Error.Id)
CheckErrorID(t, err, "api.upload.get_upload.forbidden.app_error")
})
t.Run("success", func(t *testing.T) {
expected, resp := th.Client.CreateUpload(us)
require.Nil(t, resp.Error)
expected, resp, err := th.Client.CreateUpload(us)
require.NoError(t, err)
require.NotEmpty(t, expected)
require.Equal(t, http.StatusCreated, resp.StatusCode)
u, resp := th.Client.GetUpload(expected.Id)
require.Nil(t, resp.Error)
u, _, err := th.Client.GetUpload(expected.Id)
require.NoError(t, err)
require.NotEmpty(t, u)
require.Equal(t, expected, u)
})
@ -141,15 +136,15 @@ func TestGetUploadsForUser(t *testing.T) {
defer th.TearDown()
t.Run("no permissions", func(t *testing.T) {
uss, resp := th.Client.GetUploadsForUser(th.BasicUser2.Id)
require.NotNil(t, resp.Error)
require.Equal(t, "api.user.get_uploads_for_user.forbidden.app_error", resp.Error.Id)
uss, _, err := th.Client.GetUploadsForUser(th.BasicUser2.Id)
require.Error(t, err)
CheckErrorID(t, err, "api.user.get_uploads_for_user.forbidden.app_error")
require.Nil(t, uss)
})
t.Run("empty", func(t *testing.T) {
uss, resp := th.Client.GetUploadsForUser(th.BasicUser.Id)
require.Nil(t, resp.Error)
uss, _, err := th.Client.GetUploadsForUser(th.BasicUser.Id)
require.NoError(t, err)
require.Empty(t, uss)
})
@ -173,8 +168,8 @@ func TestGetUploadsForUser(t *testing.T) {
uploads[i] = us
}
uss, resp := th.Client.GetUploadsForUser(th.BasicUser.Id)
require.Nil(t, resp.Error)
uss, _, err := th.Client.GetUploadsForUser(th.BasicUser.Id)
require.NoError(t, err)
require.NotEmpty(t, uss)
require.Len(t, uss, len(uploads))
for i := range uploads {
@ -209,58 +204,54 @@ func TestUploadData(t *testing.T) {
t.Run("file attachments disabled", func(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.EnableFileAttachments = false })
defer th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.EnableFileAttachments = true })
info, resp := th.Client.UploadData(model.NewId(), bytes.NewReader(data))
info, _, err := th.Client.UploadData(model.NewId(), bytes.NewReader(data))
require.Nil(t, info)
require.NotNil(t, resp.Error)
require.Equal(t, "api.file.attachments.disabled.app_error", resp.Error.Id)
CheckErrorID(t, err, "api.file.attachments.disabled.app_error")
})
t.Run("upload not found", func(t *testing.T) {
info, resp := th.Client.UploadData(model.NewId(), bytes.NewReader(data))
info, resp, err := th.Client.UploadData(model.NewId(), bytes.NewReader(data))
require.Nil(t, info)
require.NotNil(t, resp.Error)
require.Equal(t, "app.upload.get.app_error", resp.Error.Id)
CheckErrorID(t, err, "app.upload.get.app_error")
require.Equal(t, http.StatusNotFound, resp.StatusCode)
})
t.Run("no permissions", func(t *testing.T) {
info, resp := th.Client.UploadData(us.Id, bytes.NewReader(data))
info, _, err := th.Client.UploadData(us.Id, bytes.NewReader(data))
require.Nil(t, info)
require.NotNil(t, resp.Error)
require.Equal(t, "api.context.permissions.app_error", resp.Error.Id)
CheckErrorID(t, err, "api.context.permissions.app_error")
})
t.Run("bad content-length", func(t *testing.T) {
u, resp := th.Client.CreateUpload(us)
require.Nil(t, resp.Error)
u, resp, err := th.Client.CreateUpload(us)
require.NoError(t, err)
require.NotEmpty(t, u)
require.Equal(t, http.StatusCreated, resp.StatusCode)
info, resp := th.Client.UploadData(u.Id, bytes.NewReader(append(data, 0x00)))
info, _, err := th.Client.UploadData(u.Id, bytes.NewReader(append(data, 0x00)))
require.Nil(t, info)
require.NotNil(t, resp.Error)
require.Equal(t, "api.upload.upload_data.invalid_content_length", resp.Error.Id)
CheckErrorID(t, err, "api.upload.upload_data.invalid_content_length")
})
t.Run("success", func(t *testing.T) {
u, resp := th.Client.CreateUpload(us)
require.Nil(t, resp.Error)
u, resp, err := th.Client.CreateUpload(us)
require.NoError(t, err)
require.NotEmpty(t, u)
require.Equal(t, http.StatusCreated, resp.StatusCode)
info, resp := th.Client.UploadData(u.Id, bytes.NewReader(data))
require.Nil(t, resp.Error)
info, _, err := th.Client.UploadData(u.Id, bytes.NewReader(data))
require.NoError(t, err)
require.NotEmpty(t, info)
require.Equal(t, u.Filename, info.Name)
file, resp := th.Client.GetFile(info.Id)
require.Nil(t, resp.Error)
file, _, err := th.Client.GetFile(info.Id)
require.NoError(t, err)
require.Equal(t, file, data)
})
t.Run("resume success", func(t *testing.T) {
u, resp := th.Client.CreateUpload(us)
require.Nil(t, resp.Error)
u, resp, err := th.Client.CreateUpload(us)
require.NoError(t, err)
require.NotEmpty(t, u)
require.Equal(t, http.StatusCreated, resp.StatusCode)
@ -268,18 +259,18 @@ func TestUploadData(t *testing.T) {
R: bytes.NewReader(data),
N: 5 * 1024 * 1024,
}
info, resp := th.Client.UploadData(u.Id, rd)
require.Nil(t, resp.Error)
info, resp, err := th.Client.UploadData(u.Id, rd)
require.NoError(t, err)
require.Nil(t, info)
require.Equal(t, http.StatusNoContent, resp.StatusCode)
info, resp = th.Client.UploadData(u.Id, bytes.NewReader(data[5*1024*1024:]))
require.Nil(t, resp.Error)
info, _, err = th.Client.UploadData(u.Id, bytes.NewReader(data[5*1024*1024:]))
require.NoError(t, err)
require.NotEmpty(t, info)
require.Equal(t, u.Filename, info.Name)
file, resp := th.Client.GetFile(info.Id)
require.Nil(t, resp.Error)
file, _, err := th.Client.GetFile(info.Id)
require.NoError(t, err)
require.Equal(t, file, data)
})
}
@ -300,8 +291,8 @@ func TestUploadDataMultipart(t *testing.T) {
Filename: "upload",
FileSize: 8 * 1024 * 1024,
}
us, resp := th.Client.CreateUpload(us)
require.Nil(t, resp.Error)
us, _, err := th.Client.CreateUpload(us)
require.NoError(t, err)
require.NotNil(t, us)
require.NotEmpty(t, us)
@ -321,10 +312,9 @@ func TestUploadDataMultipart(t *testing.T) {
}
t.Run("bad content-type", func(t *testing.T) {
info, resp := th.Client.DoUploadFile("/uploads/"+us.Id, data, "multipart/form-data;")
info, _, err := th.Client.DoUploadFile("/uploads/"+us.Id, data, "multipart/form-data;")
require.Nil(t, info)
require.NotNil(t, resp.Error)
require.Equal(t, "api.upload.upload_data.invalid_content_type", resp.Error.Id)
CheckErrorID(t, err, "api.upload.upload_data.invalid_content_type")
})
t.Run("success", func(t *testing.T) {
@ -341,16 +331,16 @@ func TestUploadDataMultipart(t *testing.T) {
require.NotEmpty(t, info)
require.Equal(t, us.Filename, info.Name)
file, resp := th.Client.GetFile(info.Id)
require.Nil(t, resp.Error)
file, _, err := th.Client.GetFile(info.Id)
require.NoError(t, err)
require.Equal(t, file, data)
})
t.Run("resume success", func(t *testing.T) {
mpData, contentType := genMultipartData(t, data[:5*1024*1024])
u, resp := th.Client.CreateUpload(us)
require.Nil(t, resp.Error)
u, _, err := th.Client.CreateUpload(us)
require.NoError(t, err)
require.NotNil(t, u)
require.NotEmpty(t, u)
@ -376,8 +366,8 @@ func TestUploadDataMultipart(t *testing.T) {
require.NotEmpty(t, info)
require.Equal(t, u.Filename, info.Name)
file, resp := th.Client.GetFile(info.Id)
require.Nil(t, resp.Error)
file, _, err := th.Client.GetFile(info.Id)
require.NoError(t, err)
require.Equal(t, file, data)
})
}

File diff suppressed because it is too large Load diff

View file

@ -16,31 +16,31 @@ func TestApiResctrictedViewMembers(t *testing.T) {
defer th.TearDown()
// Create first account for system admin
_, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user0", Password: "test-password-0", Username: "test-user-0", Roles: model.SystemUserRoleId})
require.Nil(t, err)
_, appErr := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user0", Password: "test-password-0", Username: "test-user-0", Roles: model.SystemUserRoleId})
require.Nil(t, appErr)
user1, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user1", Password: "test-password-1", Username: "test-user-1", Roles: model.SystemUserRoleId})
require.Nil(t, err)
user2, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user2", Password: "test-password-2", Username: "test-user-2", Roles: model.SystemUserRoleId})
require.Nil(t, err)
user3, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user3", Password: "test-password-3", Username: "test-user-3", Roles: model.SystemUserRoleId})
require.Nil(t, err)
user4, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user4", Password: "test-password-4", Username: "test-user-4", Roles: model.SystemUserRoleId})
require.Nil(t, err)
user5, err := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user5", Password: "test-password-5", Username: "test-user-5", Roles: model.SystemUserRoleId})
require.Nil(t, err)
user1, appErr := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user1", Password: "test-password-1", Username: "test-user-1", Roles: model.SystemUserRoleId})
require.Nil(t, appErr)
user2, appErr := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user2", Password: "test-password-2", Username: "test-user-2", Roles: model.SystemUserRoleId})
require.Nil(t, appErr)
user3, appErr := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user3", Password: "test-password-3", Username: "test-user-3", Roles: model.SystemUserRoleId})
require.Nil(t, appErr)
user4, appErr := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user4", Password: "test-password-4", Username: "test-user-4", Roles: model.SystemUserRoleId})
require.Nil(t, appErr)
user5, appErr := th.App.CreateUser(th.Context, &model.User{Email: th.GenerateTestEmail(), Nickname: "test user5", Password: "test-password-5", Username: "test-user-5", Roles: model.SystemUserRoleId})
require.Nil(t, appErr)
team1, err := th.App.CreateTeam(th.Context, &model.Team{DisplayName: "dn_" + model.NewId(), Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TeamOpen})
require.Nil(t, err)
team2, err := th.App.CreateTeam(th.Context, &model.Team{DisplayName: "dn_" + model.NewId(), Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TeamOpen})
require.Nil(t, err)
team1, appErr := th.App.CreateTeam(th.Context, &model.Team{DisplayName: "dn_" + model.NewId(), Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TeamOpen})
require.Nil(t, appErr)
team2, appErr := th.App.CreateTeam(th.Context, &model.Team{DisplayName: "dn_" + model.NewId(), Name: GenerateTestTeamName(), Email: th.GenerateTestEmail(), Type: model.TeamOpen})
require.Nil(t, appErr)
channel1, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.ChannelTypeOpen, TeamId: team1.Id, CreatorId: model.NewId()}, false)
require.Nil(t, err)
channel2, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.ChannelTypeOpen, TeamId: team1.Id, CreatorId: model.NewId()}, false)
require.Nil(t, err)
channel3, err := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.ChannelTypeOpen, TeamId: team2.Id, CreatorId: model.NewId()}, false)
require.Nil(t, err)
channel1, appErr := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.ChannelTypeOpen, TeamId: team1.Id, CreatorId: model.NewId()}, false)
require.Nil(t, appErr)
channel2, appErr := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.ChannelTypeOpen, TeamId: team1.Id, CreatorId: model.NewId()}, false)
require.Nil(t, appErr)
channel3, appErr := th.App.CreateChannel(th.Context, &model.Channel{DisplayName: "dn_" + model.NewId(), Name: "name_" + model.NewId(), Type: model.ChannelTypeOpen, TeamId: team2.Id, CreatorId: model.NewId()}, false)
require.Nil(t, appErr)
th.LinkUserToTeam(user1, team1)
th.LinkUserToTeam(user2, team1)
@ -60,8 +60,8 @@ func TestApiResctrictedViewMembers(t *testing.T) {
th.App.SetStatusOnline(user4.Id, true)
th.App.SetStatusOnline(user5.Id, true)
_, resp := th.Client.Login(user1.Username, "test-password-1")
CheckNoError(t, resp)
_, _, err := th.Client.Login(user1.Username, "test-password-1")
require.NoError(t, err)
t.Run("getUser", func(t *testing.T) {
testCases := []struct {
@ -134,12 +134,11 @@ func TestApiResctrictedViewMembers(t *testing.T) {
th.AddPermissionToRole(model.PermissionViewMembers.Id, model.SystemUserRoleId)
}
_, resp := th.Client.GetUser(tc.UserId, "")
require.Nil(t, err)
_, _, err := th.Client.GetUser(tc.UserId, "")
if tc.ExpectedError != "" {
CheckErrorMessage(t, resp, tc.ExpectedError)
CheckErrorID(t, err, tc.ExpectedError)
} else {
CheckNoError(t, resp)
require.NoError(t, err)
}
})
}
@ -216,12 +215,11 @@ func TestApiResctrictedViewMembers(t *testing.T) {
th.AddPermissionToRole(model.PermissionViewMembers.Id, model.SystemUserRoleId)
}
_, resp := th.Client.GetUserByUsername(tc.Username, "")
require.Nil(t, err)
_, _, err := th.Client.GetUserByUsername(tc.Username, "")
if tc.ExpectedError != "" {
CheckErrorMessage(t, resp, tc.ExpectedError)
CheckErrorID(t, err, tc.ExpectedError)
} else {
CheckNoError(t, resp)
require.NoError(t, err)
}
})
}
@ -298,12 +296,11 @@ func TestApiResctrictedViewMembers(t *testing.T) {
th.AddPermissionToRole(model.PermissionViewMembers.Id, model.SystemUserRoleId)
}
_, resp := th.Client.GetUserByEmail(tc.Email, "")
require.Nil(t, err)
_, _, err := th.Client.GetUserByEmail(tc.Email, "")
if tc.ExpectedError != "" {
CheckErrorMessage(t, resp, tc.ExpectedError)
CheckErrorID(t, err, tc.ExpectedError)
} else {
CheckNoError(t, resp)
require.NoError(t, err)
}
})
}
@ -380,12 +377,11 @@ func TestApiResctrictedViewMembers(t *testing.T) {
th.AddPermissionToRole(model.PermissionViewMembers.Id, model.SystemUserRoleId)
}
_, resp := th.Client.GetDefaultProfileImage(tc.UserId)
require.Nil(t, err)
_, _, err := th.Client.GetDefaultProfileImage(tc.UserId)
if tc.ExpectedError != "" {
CheckErrorMessage(t, resp, tc.ExpectedError)
CheckErrorID(t, err, tc.ExpectedError)
} else {
CheckNoError(t, resp)
require.NoError(t, err)
}
})
}
@ -462,12 +458,11 @@ func TestApiResctrictedViewMembers(t *testing.T) {
th.AddPermissionToRole(model.PermissionViewMembers.Id, model.SystemUserRoleId)
}
_, resp := th.Client.GetProfileImage(tc.UserId, "")
require.Nil(t, err)
_, _, err := th.Client.GetProfileImage(tc.UserId, "")
if tc.ExpectedError != "" {
CheckErrorMessage(t, resp, tc.ExpectedError)
CheckErrorID(t, err, tc.ExpectedError)
} else {
CheckNoError(t, resp)
require.NoError(t, err)
}
})
}

File diff suppressed because it is too large Load diff

View file

@ -21,15 +21,15 @@ func TestWebSocket(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
WebSocketClient, err := th.CreateWebSocketClient()
require.Nil(t, err)
require.NoError(t, err)
defer WebSocketClient.Close()
time.Sleep(300 * time.Millisecond)
// Test closing and reconnecting
WebSocketClient.Close()
err = WebSocketClient.Connect()
require.Nil(t, err)
appErr := WebSocketClient.Connect()
require.Nil(t, appErr)
WebSocketClient.Listen()

View file

@ -30,7 +30,7 @@ func TestWebSocketEvent(t *testing.T) {
defer th.TearDown()
WebSocketClient, err := th.CreateWebSocketClient()
require.Nil(t, err)
require.NoError(t, err)
defer WebSocketClient.Close()
WebSocketClient.Listen()
@ -98,7 +98,7 @@ func TestCreateDirectChannelWithSocket(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
user2 := th.BasicUser2
users := make([]*model.User, 0)
@ -109,7 +109,7 @@ func TestCreateDirectChannelWithSocket(t *testing.T) {
}
WebSocketClient, err := th.CreateWebSocketClient()
require.Nil(t, err)
require.NoError(t, err)
defer WebSocketClient.Close()
WebSocketClient.Listen()
@ -138,8 +138,8 @@ func TestCreateDirectChannelWithSocket(t *testing.T) {
for _, user := range users {
time.Sleep(100 * time.Millisecond)
_, resp := Client.CreateDirectChannel(th.BasicUser.Id, user.Id)
require.Nil(t, resp.Error, "failed to create DM channel")
_, _, err := client.CreateDirectChannel(th.BasicUser.Id, user.Id)
require.NoError(t, err, "failed to create DM channel")
}
time.Sleep(5000 * time.Millisecond)
@ -203,9 +203,9 @@ func TestWebSocketStatuses(t *testing.T) {
th := Setup(t).InitBasic()
defer th.TearDown()
Client := th.Client
client := th.Client
WebSocketClient, err := th.CreateWebSocketClient()
require.Nil(t, err, err)
require.NoError(t, err)
defer WebSocketClient.Close()
WebSocketClient.Listen()
@ -213,26 +213,28 @@ func TestWebSocketStatuses(t *testing.T) {
require.Equal(t, resp.Status, model.StatusOk, "should have responded OK to authentication challenge")
team := model.Team{DisplayName: "Name", Name: "z-z-" + model.NewRandomTeamName() + "a", Email: "test@nowhere.com", Type: model.TeamOpen}
rteam, _ := Client.CreateTeam(&team)
rteam, _, _ := client.CreateTeam(&team)
user := model.User{Email: strings.ToLower(model.NewId()) + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1"}
ruser := Client.Must(Client.CreateUser(&user)).(*model.User)
ruser, _, err := client.CreateUser(&user)
require.NoError(t, err)
th.LinkUserToTeam(ruser, rteam)
_, nErr := th.App.Srv().Store.User().VerifyEmail(ruser.Id, ruser.Email)
require.NoError(t, nErr)
_, err = th.App.Srv().Store.User().VerifyEmail(ruser.Id, ruser.Email)
require.NoError(t, err)
user2 := model.User{Email: strings.ToLower(model.NewId()) + "success+test@simulator.amazonses.com", Nickname: "Corey Hulen", Password: "passwd1"}
ruser2 := Client.Must(Client.CreateUser(&user2)).(*model.User)
ruser2, _, err := client.CreateUser(&user2)
require.NoError(t, err)
th.LinkUserToTeam(ruser2, rteam)
_, nErr = th.App.Srv().Store.User().VerifyEmail(ruser2.Id, ruser2.Email)
require.NoError(t, nErr)
_, err = th.App.Srv().Store.User().VerifyEmail(ruser2.Id, ruser2.Email)
require.NoError(t, err)
Client.Login(user.Email, user.Password)
client.Login(user.Email, user.Password)
th.LoginBasic2()
WebSocketClient2, err2 := th.CreateWebSocketClient()
require.Nil(t, err2, err2)
WebSocketClient2, err := th.CreateWebSocketClient()
require.NoError(t, err)
time.Sleep(1000 * time.Millisecond)

View file

@ -1709,8 +1709,8 @@ func TestPluginHTTPUpgradeWebSocket(t *testing.T) {
require.NotEmpty(t, pluginID)
reqURL := fmt.Sprintf("ws://localhost:%d/plugins/%s", th.Server.ListenAddr.Port, pluginID)
wsc, appErr := model.NewWebSocketClient(reqURL, "")
require.Nil(t, appErr)
wsc, err := model.NewWebSocketClient(reqURL, "")
require.NoError(t, err)
require.NotNil(t, wsc)
wsc.Listen()

View file

@ -77,14 +77,14 @@ func CreateTestEnvironmentInTeam(a *app.App, c *request.Context, client *model.C
// Have every user join every channel
for _, user := range users {
for _, channel := range channels {
_, resp := client.LoginById(user.Id, UserPassword)
if resp.Error != nil {
return TeamEnvironment{}, resp.Error
_, _, err := client.LoginById(user.Id, UserPassword)
if err != nil {
return TeamEnvironment{}, err
}
_, resp = client.AddChannelMember(channel.Id, user.Id)
if resp.Error != nil {
return TeamEnvironment{}, resp.Error
_, _, err = client.AddChannelMember(channel.Id, user.Id)
if err != nil {
return TeamEnvironment{}, err
}
}
}
@ -93,9 +93,9 @@ func CreateTestEnvironmentInTeam(a *app.App, c *request.Context, client *model.C
numImages := utils.RandIntFromRange(rangePosts) / 4
for j := 0; j < numPosts; j++ {
user := users[utils.RandIntFromRange(utils.Range{Begin: 0, End: len(users) - 1})]
_, resp := client.LoginById(user.Id, UserPassword)
if resp.Error != nil {
return TeamEnvironment{}, resp.Error
_, _, err := client.LoginById(user.Id, UserPassword)
if err != nil {
return TeamEnvironment{}, err
}
for i, channel := range channels {

View file

@ -57,9 +57,9 @@ func (cfg *AutoTeamCreator) createRandomTeam() (*model.Team, error) {
Type: model.TeamOpen,
}
createdTeam, resp := cfg.client.CreateTeam(team)
if resp.Error != nil {
return nil, resp.Error
createdTeam, _, err := cfg.client.CreateTeam(team)
if err != nil {
return nil, err
}
return createdTeam, nil
}

View file

@ -39,23 +39,23 @@ func NewAutoUserCreator(a *app.App, client *model.Client4, team *model.Team) *Au
}
// Basic test team and user so you always know one
func CreateBasicUser(a *app.App, client *model.Client4) *model.AppError {
found, _ := client.TeamExists(BTestTeamName, "")
func CreateBasicUser(a *app.App, client *model.Client4) error {
found, _, _ := client.TeamExists(BTestTeamName, "")
if found {
return nil
}
newteam := &model.Team{DisplayName: BTestTeamDisplayName, Name: BTestTeamName, Email: BTestTeamEmail, Type: BTestTeamType}
basicteam, resp := client.CreateTeam(newteam)
if resp.Error != nil {
return resp.Error
basicteam, _, err := client.CreateTeam(newteam)
if err != nil {
return err
}
newuser := &model.User{Email: BTestUserEmail, Nickname: BTestUserName, Password: BTestUserPassword}
ruser, resp := client.CreateUser(newuser)
if resp.Error != nil {
return resp.Error
ruser, _, err := client.CreateUser(newuser)
if err != nil {
return err
}
_, err := a.Srv().Store.User().VerifyEmail(ruser.Id, ruser.Email)
_, err = a.Srv().Store.User().VerifyEmail(ruser.Id, ruser.Email)
if err != nil {
return model.NewAppError("CreateBasicUser", "app.user.verify_email.app_error", nil, err.Error(), http.StatusInternalServerError)
}

View file

@ -215,9 +215,9 @@ func (*LoadTestProvider) SetupCommand(a *app.App, c *request.Context, args *mode
if err := CreateBasicUser(a, client); err != nil {
return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.CommandResponseTypeEphemeral}, err
}
_, resp := client.Login(BTestUserEmail, BTestUserPassword)
if resp.Error != nil {
return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.CommandResponseTypeEphemeral}, resp.Error
_, _, err := client.Login(BTestUserEmail, BTestUserPassword)
if err != nil {
return &model.CommandResponse{Text: "Failed to create testing environment", ResponseType: model.CommandResponseTypeEphemeral}, err
}
environment, err := CreateTestEnvironmentWithTeams(
a,
@ -443,18 +443,18 @@ func (*LoadTestProvider) PostCommand(a *app.App, args *model.CommandArgs, messag
}
client := model.NewAPIv4Client(args.SiteURL)
_, resp := client.LoginById(user.Id, passwd)
if resp.Error != nil {
return &model.CommandResponse{Text: "Failed to login a user", ResponseType: model.CommandResponseTypeEphemeral}, resp.Error
_, _, nErr := client.LoginById(user.Id, passwd)
if nErr != nil {
return &model.CommandResponse{Text: "Failed to login a user", ResponseType: model.CommandResponseTypeEphemeral}, nErr
}
post := &model.Post{
ChannelId: channel.Id,
Message: textMessage,
}
_, resp = client.CreatePost(post)
if resp.Error != nil {
return &model.CommandResponse{Text: "Failed to create a post", ResponseType: model.CommandResponseTypeEphemeral}, resp.Error
_, _, nErr = client.CreatePost(post)
if nErr != nil {
return &model.CommandResponse{Text: "Failed to create a post", ResponseType: model.CommandResponseTypeEphemeral}, nErr
}
return &model.CommandResponse{Text: "Added a post to " + channel.DisplayName, ResponseType: model.CommandResponseTypeEphemeral}, nil

View file

@ -113,7 +113,8 @@ func TestListChannels(t *testing.T) {
defer th.TearDown()
channel := th.CreatePublicChannel()
th.Client.Must(th.Client.DeleteChannel(channel.Id))
_, err := th.Client.DeleteChannel(channel.Id)
require.NoError(t, err)
privateChannel := th.CreatePrivateChannel()
output := th.CheckCommand(t, "channel", "list", th.BasicTeam.Name)
@ -124,7 +125,8 @@ func TestListChannels(t *testing.T) {
require.True(t, strings.Contains(output, privateChannel.Name+" (private)"), "should have private channel")
th.Client.Must(th.Client.DeleteChannel(privateChannel.Id))
_, err = th.Client.DeleteChannel(privateChannel.Id)
require.NoError(t, err)
output = th.CheckCommand(t, "channel", "list", th.BasicTeam.Name)
@ -136,7 +138,8 @@ func TestRestoreChannel(t *testing.T) {
defer th.TearDown()
channel := th.CreatePublicChannel()
th.Client.Must(th.Client.DeleteChannel(channel.Id))
_, err := th.Client.DeleteChannel(channel.Id)
require.NoError(t, err)
th.CheckCommand(t, "channel", "restore", th.BasicTeam.Name+":"+channel.Name)

View file

@ -115,9 +115,8 @@ func TestCreateCommand(t *testing.T) {
t.Run(testCase.Description, func(t *testing.T) {
actual, _ := th.RunCommandWithOutput(t, testCase.Args...)
cmds, response := th.SystemAdminClient.ListCommands(team.Id, true)
require.Nil(t, response.Error, "Failed to list commands")
cmds, _, err := th.SystemAdminClient.ListCommands(team.Id, true)
require.NoError(t, err, "Failed to list commands")
if testCase.ExpectedErr == "" {
assert.NotZero(t, len(cmds), "Failed to create command")

View file

@ -22,7 +22,8 @@ func TestCreateTeam(t *testing.T) {
th.CheckCommand(t, "team", "create", "--name", name, "--display_name", displayName)
found := th.SystemAdminClient.Must(th.SystemAdminClient.TeamExists(name, "")).(bool)
found, _, err := th.SystemAdminClient.TeamExists(name, "")
require.NoError(t, err)
require.True(t, found, "Failed to create Team")
}
@ -33,7 +34,8 @@ func TestJoinTeam(t *testing.T) {
th.CheckCommand(t, "team", "add", th.BasicTeam.Name, th.BasicUser.Email)
profiles := th.SystemAdminClient.Must(th.SystemAdminClient.GetUsersInTeam(th.BasicTeam.Id, 0, 1000, "")).([]*model.User)
profiles, _, err := th.SystemAdminClient.GetUsersInTeam(th.BasicTeam.Id, 0, 1000, "")
require.NoError(t, err)
found := false
@ -53,7 +55,8 @@ func TestLeaveTeam(t *testing.T) {
th.CheckCommand(t, "team", "remove", th.BasicTeam.Name, th.BasicUser.Email)
profiles := th.Client.Must(th.Client.GetUsersInTeam(th.BasicTeam.Id, 0, 1000, "")).([]*model.User)
profiles, _, err := th.Client.GetUsersInTeam(th.BasicTeam.Id, 0, 1000, "")
require.NoError(t, err)
found := false
@ -181,8 +184,8 @@ func TestRestoreTeams(t *testing.T) {
th.CheckCommand(t, "team", "restore", name)
found := th.SystemAdminClient.Must(th.SystemAdminClient.TeamExists(name, "")).(bool)
found, _, err := th.SystemAdminClient.TeamExists(name, "")
require.NoError(t, err)
require.True(t, found)
}

View file

@ -24,7 +24,8 @@ func TestCreateUserWithTeam(t *testing.T) {
th.CheckCommand(t, "team", "add", th.BasicTeam.Id, email)
profiles := th.SystemAdminClient.Must(th.SystemAdminClient.GetUsersInTeam(th.BasicTeam.Id, 0, 1000, "")).([]*model.User)
profiles, _, err := th.SystemAdminClient.GetUsersInTeam(th.BasicTeam.Id, 0, 1000, "")
require.NoError(t, err)
found := false

View file

@ -11,7 +11,6 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/mattermost/mattermost-server/v6/api4"
"github.com/mattermost/mattermost-server/v6/model"
)
@ -44,13 +43,13 @@ func TestListWebhooks(t *testing.T) {
dispName := "myhookinc"
hook := &model.IncomingWebhook{DisplayName: dispName, ChannelId: th.BasicChannel.Id, TeamId: th.BasicChannel.TeamId}
_, resp := adminClient.CreateIncomingWebhook(hook)
api4.CheckNoError(t, resp)
_, _, err := adminClient.CreateIncomingWebhook(hook)
require.NoError(t, err)
dispName2 := "myhookout"
outHook := &model.OutgoingWebhook{DisplayName: dispName2, ChannelId: th.BasicChannel.Id, TeamId: th.BasicChannel.TeamId, CallbackURLs: []string{"http://nowhere.com"}, Username: "some-user-name", IconURL: "http://some-icon-url/"}
_, resp = adminClient.CreateOutgoingWebhook(outHook)
api4.CheckNoError(t, resp)
_, _, err = adminClient.CreateOutgoingWebhook(outHook)
require.NoError(t, err)
output := th.CheckCommand(t, "webhook", "list", th.BasicTeam.Name)
@ -91,8 +90,8 @@ func TestShowWebhook(t *testing.T) {
ChannelId: th.BasicChannel.Id,
TeamId: th.BasicChannel.TeamId,
}
incomingWebhook, resp := adminClient.CreateIncomingWebhook(hook)
api4.CheckNoError(t, resp)
incomingWebhook, _, err := adminClient.CreateIncomingWebhook(hook)
require.NoError(t, err)
// should return an error when no webhookid is provided
require.Error(t, th.RunCommand(t, "webhook", "show"))
@ -114,8 +113,8 @@ func TestShowWebhook(t *testing.T) {
Username: "some-user-name",
IconURL: "http://some-icon-url/",
}
outgoingWebhook, resp := adminClient.CreateOutgoingWebhook(outgoingHook)
api4.CheckNoError(t, resp)
outgoingWebhook, _, err := adminClient.CreateOutgoingWebhook(outgoingHook)
require.NoError(t, err)
// valid outgoing webhook should return webhook data
output = th.CheckCommand(t, "webhook", "show", outgoingWebhook.Id)
@ -424,13 +423,13 @@ func TestDeleteWebhooks(t *testing.T) {
dispName := "myhookinc"
inHookStruct := &model.IncomingWebhook{DisplayName: dispName, ChannelId: th.BasicChannel.Id, TeamId: th.BasicChannel.TeamId}
incomingHook, resp := adminClient.CreateIncomingWebhook(inHookStruct)
api4.CheckNoError(t, resp)
incomingHook, _, err := adminClient.CreateIncomingWebhook(inHookStruct)
require.NoError(t, err)
dispName2 := "myhookout"
outHookStruct := &model.OutgoingWebhook{DisplayName: dispName2, ChannelId: th.BasicChannel.Id, TeamId: th.BasicChannel.TeamId, CallbackURLs: []string{"http://nowhere.com"}, Username: "some-user-name", IconURL: "http://some-icon-url/"}
outgoingHook, resp := adminClient.CreateOutgoingWebhook(outHookStruct)
api4.CheckNoError(t, resp)
outgoingHook, _, err := adminClient.CreateOutgoingWebhook(outHookStruct)
require.NoError(t, err)
hooksBeforeDeletion := th.CheckCommand(t, "webhook", "list", th.BasicTeam.Name)

View file

@ -107,9 +107,16 @@ func manualTest(c *web.Context, w http.ResponseWriter, r *http.Request) {
Nickname: username[0],
Password: slashcommands.UserPassword}
user, resp := client.CreateUser(user)
if resp.Error != nil {
c.Err = resp.Error
user, _, err = client.CreateUser(user)
if err != nil {
var appErr *model.AppError
ok = errors.As(err, &appErr)
if ok {
c.Err = appErr
} else {
c.Err = model.NewAppError("manualTest", "app.user.save.app_error", nil, err.Error(), http.StatusInternalServerError)
}
return
}
@ -119,9 +126,15 @@ func manualTest(c *web.Context, w http.ResponseWriter, r *http.Request) {
userID = user.Id
// Login as user to generate auth token
_, resp = client.LoginById(user.Id, slashcommands.UserPassword)
if resp.Error != nil {
c.Err = resp.Error
_, _, err = client.LoginById(user.Id, slashcommands.UserPassword)
if err != nil {
var appErr *model.AppError
ok = errors.As(err, &appErr)
if ok {
c.Err = appErr
} else {
c.Err = model.NewAppError("manualTest", "api.user.login.bot_login_forbidden.app_error", nil, err.Error(), http.StatusInternalServerError)
}
return
}

View file

@ -4,6 +4,7 @@
package manualtesting
import (
"errors"
"net/http"
"github.com/mattermost/mattermost-server/v6/model"
@ -23,14 +24,20 @@ https://medium.com/@slackhq/11-useful-tips-for-getting-the-most-of-slack-5dfb3d1
func testAutoLink(env TestEnvironment) *model.AppError {
mlog.Info("Manual Auto Link Test")
channelID, err := getChannelID(env.Context.App, model.DefaultChannelName, env.CreatedTeamID, env.CreatedUserID)
if !err {
channelID, ok := getChannelID(env.Context.App, model.DefaultChannelName, env.CreatedTeamID, env.CreatedUserID)
if !ok {
return model.NewAppError("/manualtest", "manaultesting.test_autolink.unable.app_error", nil, "", http.StatusInternalServerError)
}
post := &model.Post{
ChannelId: channelID,
Message: linkPostText}
_, resp := env.Client.CreatePost(post)
return resp.Error
_, _, err := env.Client.CreatePost(post)
var appErr *model.AppError
if ok = errors.As(err, &appErr); !ok {
appErr = model.NewAppError("/manualtest", "manaultesting.test_autolink.unable.app_error", nil, "", http.StatusInternalServerError)
}
return appErr
}

File diff suppressed because it is too large Load diff

View file

@ -67,7 +67,8 @@ func TestClient4CreatePost(t *testing.T) {
}))
client := NewAPIv4Client(server.URL)
_, resp := client.CreatePost(post)
_, resp, err := client.CreatePost(post)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
}
@ -89,7 +90,8 @@ func TestClient4SetToken(t *testing.T) {
client := NewAPIv4Client(server.URL)
client.SetToken(expected)
_, resp := client.GetMe("")
_, resp, err := client.GetMe("")
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
}
@ -111,6 +113,7 @@ func TestClient4MockSession(t *testing.T) {
client := NewAPIv4Client(server.URL)
client.MockSession(expected)
_, resp := client.GetMe("")
_, resp, err := client.GetMe("")
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
}

View file

@ -59,13 +59,13 @@ type WebSocketClient struct {
// NewWebSocketClient constructs a new WebSocket client with convenience
// methods for talking to the server.
func NewWebSocketClient(url, authToken string) (*WebSocketClient, *AppError) {
func NewWebSocketClient(url, authToken string) (*WebSocketClient, error) {
return NewWebSocketClientWithDialer(websocket.DefaultDialer, url, authToken)
}
// NewWebSocketClientWithDialer constructs a new WebSocket client with convenience
// methods for talking to the server using a custom dialer.
func NewWebSocketClientWithDialer(dialer *websocket.Dialer, url, authToken string) (*WebSocketClient, *AppError) {
func NewWebSocketClientWithDialer(dialer *websocket.Dialer, url, authToken string) (*WebSocketClient, error) {
conn, _, err := dialer.Dial(url+ApiUrlSuffix+"/websocket", nil)
if err != nil {
return nil, NewAppError("NewWebSocketClient", "model.websocket_client.connect_fail.app_error", nil, err.Error(), http.StatusInternalServerError)
@ -97,13 +97,13 @@ func NewWebSocketClientWithDialer(dialer *websocket.Dialer, url, authToken strin
// NewWebSocketClient4 constructs a new WebSocket client with convenience
// methods for talking to the server. Uses the v4 endpoint.
func NewWebSocketClient4(url, authToken string) (*WebSocketClient, *AppError) {
func NewWebSocketClient4(url, authToken string) (*WebSocketClient, error) {
return NewWebSocketClient4WithDialer(websocket.DefaultDialer, url, authToken)
}
// NewWebSocketClient4WithDialer constructs a new WebSocket client with convenience
// methods for talking to the server using a custom dialer. Uses the v4 endpoint.
func NewWebSocketClient4WithDialer(dialer *websocket.Dialer, url, authToken string) (*WebSocketClient, *AppError) {
func NewWebSocketClient4WithDialer(dialer *websocket.Dialer, url, authToken string) (*WebSocketClient, error) {
return NewWebSocketClientWithDialer(dialer, url, authToken)
}

View file

@ -46,7 +46,7 @@ func TestWebSocketRace(t *testing.T) {
url := strings.Replace(s.URL, "http://", "ws://", 1)
cli, err := NewWebSocketClient4(url, "authToken")
require.Nil(t, err)
require.NoError(t, err)
cli.Listen()
@ -110,7 +110,7 @@ func TestWebSocketClose(t *testing.T) {
t.Run("SuddenClose", func(t *testing.T) {
cli, err := NewWebSocketClient4(url, "authToken")
require.Nil(t, err)
require.NoError(t, err)
cli.Listen()
@ -132,7 +132,7 @@ func TestWebSocketClose(t *testing.T) {
t.Run("ExplicitClose", func(t *testing.T) {
cli, err := NewWebSocketClient4(url, "authToken")
require.Nil(t, err)
require.NoError(t, err)
cli.Listen()

View file

@ -82,8 +82,8 @@ func TestAuthorizeOAuthApp(t *testing.T) {
}
// Test auth code flow
ruri, resp := ApiClient.AuthorizeOAuthApp(authRequest)
require.Nil(t, resp.Error)
ruri, _, err := ApiClient.AuthorizeOAuthApp(authRequest)
require.NoError(t, err)
require.NotEmpty(t, ruri, "redirect url should be set")
@ -94,8 +94,8 @@ func TestAuthorizeOAuthApp(t *testing.T) {
// Test implicit flow
authRequest.ResponseType = model.ImplicitResponseType
ruri, resp = ApiClient.AuthorizeOAuthApp(authRequest)
require.Nil(t, resp.Error)
ruri, _, err = ApiClient.AuthorizeOAuthApp(authRequest)
require.NoError(t, err)
require.False(t, ruri == "", "redirect url should be set")
ru, _ = url.Parse(ruri)
@ -107,44 +107,40 @@ func TestAuthorizeOAuthApp(t *testing.T) {
oldToken := ApiClient.AuthToken
ApiClient.AuthToken = values.Get("access_token")
_, resp = ApiClient.AuthorizeOAuthApp(authRequest)
_, resp, err := ApiClient.AuthorizeOAuthApp(authRequest)
require.Error(t, err)
CheckForbiddenStatus(t, resp)
ApiClient.AuthToken = oldToken
authRequest.RedirectUri = ""
_, resp = ApiClient.AuthorizeOAuthApp(authRequest)
_, resp, err = ApiClient.AuthorizeOAuthApp(authRequest)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
authRequest.RedirectUri = "http://somewhereelse.com"
_, resp = ApiClient.AuthorizeOAuthApp(authRequest)
_, resp, err = ApiClient.AuthorizeOAuthApp(authRequest)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
authRequest.RedirectUri = rapp.CallbackUrls[0]
authRequest.ResponseType = ""
_, resp = ApiClient.AuthorizeOAuthApp(authRequest)
_, resp, err = ApiClient.AuthorizeOAuthApp(authRequest)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
authRequest.ResponseType = model.AuthCodeResponseType
authRequest.ClientId = ""
_, resp = ApiClient.AuthorizeOAuthApp(authRequest)
_, resp, err = ApiClient.AuthorizeOAuthApp(authRequest)
require.Error(t, err)
CheckBadRequestStatus(t, resp)
authRequest.ClientId = model.NewId()
_, resp = ApiClient.AuthorizeOAuthApp(authRequest)
_, resp, err = ApiClient.AuthorizeOAuthApp(authRequest)
require.Error(t, err)
CheckNotFoundStatus(t, resp)
}
func TestNilAuthorizeOAuthApp(t *testing.T) {
th := Setup(t).InitBasic()
th.Login(ApiClient, th.SystemAdminUser)
defer th.TearDown()
_, resp := ApiClient.AuthorizeOAuthApp(nil)
require.NotNil(t, resp.Error)
assert.Equal(t, "api.context.invalid_body_param.app_error", resp.Error.Id)
}
func TestDeauthorizeOAuthApp(t *testing.T) {
th := Setup(t).InitBasic()
th.Login(ApiClient, th.SystemAdminUser)
@ -175,22 +171,22 @@ func TestDeauthorizeOAuthApp(t *testing.T) {
State: "123",
}
_, resp := ApiClient.AuthorizeOAuthApp(authRequest)
require.Nil(t, resp.Error)
_, _, err := ApiClient.AuthorizeOAuthApp(authRequest)
require.NoError(t, err)
pass, resp := ApiClient.DeauthorizeOAuthApp(rapp.Id)
require.Nil(t, resp.Error)
_, err = ApiClient.DeauthorizeOAuthApp(rapp.Id)
require.NoError(t, err)
require.True(t, pass, "should have passed")
_, resp = ApiClient.DeauthorizeOAuthApp("junk")
resp, err := ApiClient.DeauthorizeOAuthApp("junk")
require.Error(t, err)
CheckBadRequestStatus(t, resp)
_, resp = ApiClient.DeauthorizeOAuthApp(model.NewId())
require.Nil(t, resp.Error)
_, err = ApiClient.DeauthorizeOAuthApp(model.NewId())
require.NoError(t, err)
th.Logout(ApiClient)
_, resp = ApiClient.DeauthorizeOAuthApp(rapp.Id)
resp, err = ApiClient.DeauthorizeOAuthApp(rapp.Id)
require.Error(t, err)
CheckUnauthorizedStatus(t, resp)
}
@ -229,8 +225,8 @@ func TestOAuthAccessToken(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = false })
data := url.Values{"grant_type": []string{"junk"}, "client_id": []string{"12345678901234567890123456"}, "client_secret": []string{"12345678901234567890123456"}, "code": []string{"junk"}, "redirect_uri": []string{oauthApp.CallbackUrls[0]}}
_, resp := ApiClient.GetOAuthAccessToken(data)
require.NotNil(t, resp.Error, "should have failed - oauth providing turned off - response status code: %v", resp.StatusCode)
_, _, err := ApiClient.GetOAuthAccessToken(data)
require.Error(t, err, "should have failed - oauth providing turned off")
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableOAuthServiceProvider = true })
authRequest := &model.AuthorizeRequest{
@ -241,48 +237,48 @@ func TestOAuthAccessToken(t *testing.T) {
State: "123",
}
redirect, resp := ApiClient.AuthorizeOAuthApp(authRequest)
require.Nil(t, resp.Error)
redirect, _, err := ApiClient.AuthorizeOAuthApp(authRequest)
require.NoError(t, err)
rurl, _ := url.Parse(redirect)
ApiClient.Logout()
data = url.Values{"grant_type": []string{"junk"}, "client_id": []string{oauthApp.Id}, "client_secret": []string{oauthApp.ClientSecret}, "code": []string{rurl.Query().Get("code")}, "redirect_uri": []string{oauthApp.CallbackUrls[0]}}
_, resp = ApiClient.GetOAuthAccessToken(data)
require.NotNil(t, resp.Error, "should have failed - bad grant type")
_, _, err = ApiClient.GetOAuthAccessToken(data)
require.Error(t, err, "should have failed - bad grant type")
data.Set("grant_type", model.AccessTokenGrantType)
data.Set("client_id", "")
_, resp = ApiClient.GetOAuthAccessToken(data)
require.NotNil(t, resp.Error, "should have failed - missing client id")
_, _, err = ApiClient.GetOAuthAccessToken(data)
require.Error(t, err, "should have failed - missing client id")
data.Set("client_id", "junk")
_, resp = ApiClient.GetOAuthAccessToken(data)
require.NotNil(t, resp.Error, "should have failed - bad client id")
_, _, err = ApiClient.GetOAuthAccessToken(data)
require.Error(t, err, "should have failed - bad client id")
data.Set("client_id", oauthApp.Id)
data.Set("client_secret", "")
_, resp = ApiClient.GetOAuthAccessToken(data)
require.NotNil(t, resp.Error, "should have failed - missing client secret")
_, _, err = ApiClient.GetOAuthAccessToken(data)
require.Error(t, err, "should have failed - missing client secret")
data.Set("client_secret", "junk")
_, resp = ApiClient.GetOAuthAccessToken(data)
require.NotNil(t, resp.Error, "should have failed - bad client secret")
_, _, err = ApiClient.GetOAuthAccessToken(data)
require.Error(t, err, "should have failed - bad client secret")
data.Set("client_secret", oauthApp.ClientSecret)
data.Set("code", "")
_, resp = ApiClient.GetOAuthAccessToken(data)
require.NotNil(t, resp.Error, "should have failed - missing code")
_, _, err = ApiClient.GetOAuthAccessToken(data)
require.Error(t, err, "should have failed - missing code")
data.Set("code", "junk")
_, resp = ApiClient.GetOAuthAccessToken(data)
require.NotNil(t, resp.Error, "should have failed - bad code")
_, _, err = ApiClient.GetOAuthAccessToken(data)
require.Error(t, err, "should have failed - bad code")
data.Set("code", rurl.Query().Get("code"))
data.Set("redirect_uri", "junk")
_, resp = ApiClient.GetOAuthAccessToken(data)
require.NotNil(t, resp.Error, "should have failed - non-matching redirect uri")
_, _, err = ApiClient.GetOAuthAccessToken(data)
require.Error(t, err, "should have failed - non-matching redirect uri")
// reset data for successful request
data.Set("grant_type", model.AccessTokenGrantType)
@ -293,30 +289,30 @@ func TestOAuthAccessToken(t *testing.T) {
token := ""
refreshToken := ""
rsp, resp := ApiClient.GetOAuthAccessToken(data)
require.Nil(t, resp.Error)
rsp, _, err := ApiClient.GetOAuthAccessToken(data)
require.NoError(t, err)
require.NotEmpty(t, rsp.AccessToken, "access token not returned")
require.NotEmpty(t, rsp.RefreshToken, "refresh token not returned")
token, refreshToken = rsp.AccessToken, rsp.RefreshToken
require.Equal(t, rsp.TokenType, model.AccessTokenType, "access token type incorrect")
_, err := ApiClient.DoApiGet("/oauth_test", "")
require.Nil(t, err)
_, err = ApiClient.DoApiGet("/oauth_test", "")
require.NoError(t, err)
ApiClient.SetOAuthToken("")
_, err = ApiClient.DoApiGet("/oauth_test", "")
require.NotNil(t, err, "should have failed - no access token provided")
require.Error(t, err, "should have failed - no access token provided")
ApiClient.SetOAuthToken("badtoken")
_, err = ApiClient.DoApiGet("/oauth_test", "")
require.NotNil(t, err, "should have failed - bad token provided")
require.Error(t, err, "should have failed - bad token provided")
ApiClient.SetOAuthToken(token)
_, err = ApiClient.DoApiGet("/oauth_test", "")
require.Nil(t, err)
require.NoError(t, err)
_, resp = ApiClient.GetOAuthAccessToken(data)
require.NotNil(t, resp.Error, "should have failed - tried to reuse auth code")
_, _, err = ApiClient.GetOAuthAccessToken(data)
require.Error(t, err, "should have failed - tried to reuse auth code")
data.Set("grant_type", model.RefreshTokenGrantType)
data.Set("client_id", oauthApp.Id)
@ -324,12 +320,12 @@ func TestOAuthAccessToken(t *testing.T) {
data.Set("refresh_token", "")
data.Set("redirect_uri", oauthApp.CallbackUrls[0])
data.Del("code")
_, resp = ApiClient.GetOAuthAccessToken(data)
require.NotNil(t, resp.Error, "Should have failed - refresh token empty")
_, _, err = ApiClient.GetOAuthAccessToken(data)
require.Error(t, err, "Should have failed - refresh token empty")
data.Set("refresh_token", refreshToken)
rsp, resp = ApiClient.GetOAuthAccessToken(data)
require.Nil(t, resp.Error)
rsp, _, err = ApiClient.GetOAuthAccessToken(data)
require.NoError(t, err)
require.NotEmpty(t, rsp.AccessToken, "access token not returned")
require.NotEmpty(t, rsp.RefreshToken, "refresh token not returned")
require.NotEqual(t, rsp.RefreshToken, refreshToken, "refresh token did not update")
@ -337,11 +333,11 @@ func TestOAuthAccessToken(t *testing.T) {
ApiClient.SetOAuthToken(rsp.AccessToken)
_, err = ApiClient.DoApiGet("/oauth_test", "")
require.Nil(t, err)
require.NoError(t, err)
data.Set("refresh_token", rsp.RefreshToken)
rsp, resp = ApiClient.GetOAuthAccessToken(data)
require.Nil(t, resp.Error)
rsp, _, err = ApiClient.GetOAuthAccessToken(data)
require.NoError(t, err)
require.NotEmpty(t, rsp.AccessToken, "access token not returned")
require.NotEmpty(t, rsp.RefreshToken, "refresh token not returned")
require.NotEqual(t, rsp.RefreshToken, refreshToken, "refresh token did not update")
@ -349,11 +345,11 @@ func TestOAuthAccessToken(t *testing.T) {
ApiClient.SetOAuthToken(rsp.AccessToken)
_, err = ApiClient.DoApiGet("/oauth_test", "")
require.Nil(t, err)
require.NoError(t, err)
authData := &model.AuthData{ClientId: oauthApp.Id, RedirectUri: oauthApp.CallbackUrls[0], UserId: th.BasicUser.Id, Code: model.NewId(), ExpiresIn: -1}
_, nErr := th.App.Srv().Store.OAuth().SaveAuthData(authData)
require.NoError(t, nErr)
_, err = th.App.Srv().Store.OAuth().SaveAuthData(authData)
require.NoError(t, err)
data.Set("grant_type", model.AccessTokenGrantType)
data.Set("client_id", oauthApp.Id)
@ -361,8 +357,8 @@ func TestOAuthAccessToken(t *testing.T) {
data.Set("redirect_uri", oauthApp.CallbackUrls[0])
data.Set("code", authData.Code)
data.Del("refresh_token")
_, resp = ApiClient.GetOAuthAccessToken(data)
require.NotNil(t, resp.Error, "Should have failed - code is expired")
_, _, err = ApiClient.GetOAuthAccessToken(data)
require.Error(t, err, "Should have failed - code is expired")
ApiClient.ClearOAuthToken()
}
@ -440,12 +436,12 @@ func TestOAuthComplete(t *testing.T) {
}()
r, err := HTTPGet(ApiClient.Url+"/login/gitlab/complete?code=123", ApiClient.HTTPClient, "", true)
assert.NotNil(t, err)
assert.Error(t, err)
closeBody(r)
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.Enable = true })
r, err = HTTPGet(ApiClient.Url+"/login/gitlab/complete?code=123&state=!#$#F@#Yˆ&~ñ", ApiClient.HTTPClient, "", true)
assert.NotNil(t, err)
assert.Error(t, err)
closeBody(r)
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.GitLabSettings.AuthEndpoint = ApiClient.Url + "/oauth/authorize" })
@ -458,13 +454,13 @@ func TestOAuthComplete(t *testing.T) {
state := base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps)))
r, err = HTTPGet(ApiClient.Url+"/login/gitlab/complete?code=123&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", true)
assert.NotNil(t, err)
assert.Error(t, err)
closeBody(r)
stateProps["hash"] = utils.HashSha256(*th.App.Config().GitLabSettings.Id)
state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps)))
r, err = HTTPGet(ApiClient.Url+"/login/gitlab/complete?code=123&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", true)
assert.NotNil(t, err)
assert.Error(t, err)
closeBody(r)
// We are going to use mattermost as the provider emulating gitlab
@ -507,8 +503,8 @@ func TestOAuthComplete(t *testing.T) {
State: "123",
}
redirect, resp := ApiClient.AuthorizeOAuthApp(authRequest)
require.Nil(t, resp.Error)
redirect, _, err := ApiClient.AuthorizeOAuthApp(authRequest)
require.NoError(t, err)
rurl, _ := url.Parse(redirect)
code := rurl.Query().Get("code")
@ -525,8 +521,8 @@ func TestOAuthComplete(t *testing.T) {
einterfaces.RegisterOAuthProvider(model.ServiceGitlab, provider)
redirect, resp = ApiClient.AuthorizeOAuthApp(authRequest)
require.Nil(t, resp.Error)
redirect, _, err = ApiClient.AuthorizeOAuthApp(authRequest)
require.NoError(t, err)
rurl, _ = url.Parse(redirect)
code = rurl.Query().Get("code")
@ -539,30 +535,30 @@ func TestOAuthComplete(t *testing.T) {
th.BasicUser.Id, model.ServiceGitlab, &th.BasicUser.Email, th.BasicUser.Email, true)
require.NoError(t, nErr)
redirect, resp = ApiClient.AuthorizeOAuthApp(authRequest)
require.Nil(t, resp.Error)
redirect, _, err = ApiClient.AuthorizeOAuthApp(authRequest)
require.NoError(t, err)
rurl, _ = url.Parse(redirect)
code = rurl.Query().Get("code")
stateProps["action"] = model.OAuthActionLogin
state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps)))
if r, err := HTTPGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", false); err == nil {
if r, err = HTTPGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", false); err == nil {
closeBody(r)
}
redirect, resp = ApiClient.AuthorizeOAuthApp(authRequest)
require.Nil(t, resp.Error)
redirect, _, err = ApiClient.AuthorizeOAuthApp(authRequest)
require.NoError(t, err)
rurl, _ = url.Parse(redirect)
code = rurl.Query().Get("code")
delete(stateProps, "action")
state = base64.StdEncoding.EncodeToString([]byte(model.MapToJson(stateProps)))
if r, err := HTTPGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", false); err == nil {
if r, err = HTTPGet(ApiClient.Url+"/login/"+model.ServiceGitlab+"/complete?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(state), ApiClient.HTTPClient, "", false); err == nil {
closeBody(r)
}
redirect, resp = ApiClient.AuthorizeOAuthApp(authRequest)
require.Nil(t, resp.Error)
redirect, _, err = ApiClient.AuthorizeOAuthApp(authRequest)
require.NoError(t, err)
rurl, _ = url.Parse(redirect)
code = rurl.Query().Get("code")
@ -612,7 +608,7 @@ func TestOAuthComplete_ErrorMessages(t *testing.T) {
assert.Contains(t, responseWriter.Body.String(), "<!-- mobile app message -->")
}
func HTTPGet(url string, httpClient *http.Client, authToken string, followRedirect bool) (*http.Response, *model.AppError) {
func HTTPGet(url string, httpClient *http.Client, authToken string, followRedirect bool) (*http.Response, error) {
rq, _ := http.NewRequest("GET", url, nil)
rq.Close = true
@ -627,7 +623,7 @@ func HTTPGet(url string, httpClient *http.Client, authToken string, followRedire
}
if rp, err := httpClient.Do(rq); err != nil {
return nil, model.NewAppError(url, "model.client.connecting.app_error", nil, err.Error(), 0)
return nil, err
} else if rp.StatusCode == 304 {
return rp, nil
} else if rp.StatusCode == 307 {
@ -675,11 +671,9 @@ func GenerateTestAppName() string {
func checkHTTPStatus(t *testing.T, resp *model.Response, expectedStatus int) {
t.Helper()
require.NotNil(t, resp, "Unexpected nil response, expected http:%v, expectError:%v)", expectedStatus, true)
require.NotNilf(t, resp, "Unexpected nil response, expected http status:%v", expectedStatus)
require.NotNil(t, resp.Error, "Expected a non-nil error and http status:%v, got nil, %v", expectedStatus, resp.StatusCode)
require.Equal(t, resp.StatusCode, expectedStatus, "Expected http status:%v, got %v (err: %q)", expectedStatus, resp.StatusCode, resp.Error)
require.Equalf(t, expectedStatus, resp.StatusCode, "Expected http status:%v, got %v", expectedStatus, resp.StatusCode)
}
func CheckForbiddenStatus(t *testing.T, resp *model.Response) {