Merge branch 'master' into mark-as-unread

Этот коммит содержится в:
Harrison Healey
2019-10-29 10:11:41 -04:00
родитель 9b1ba32dc6 38c0bde7f8
Коммит eb36329e8d
112 изменённых файлов: 1569 добавлений и 1479 удалений

Просмотреть файл

@@ -9,8 +9,6 @@ import (
"net"
"net/http"
"os"
"reflect"
"strconv"
"strings"
"testing"
"time"
@@ -26,6 +24,7 @@ import (
s3 "github.com/minio/minio-go/v6"
"github.com/minio/minio-go/v6/pkg/credentials"
"github.com/stretchr/testify/require"
)
type TestHelper struct {
@@ -560,57 +559,34 @@ func GenerateTestId() string {
func CheckUserSanitization(t *testing.T, user *model.User) {
t.Helper()
if user.Password != "" {
t.Fatal("password wasn't blank")
}
if user.AuthData != nil && *user.AuthData != "" {
t.Fatal("auth data wasn't blank")
}
if user.MfaSecret != "" {
t.Fatal("mfa secret wasn't blank")
}
require.Equal(t, "", user.Password, "password wasn't blank")
require.Empty(t, user.AuthData, "auth data wasn't blank")
require.Equal(t, "", user.MfaSecret, "mfa secret wasn't blank")
}
func CheckEtag(t *testing.T, data interface{}, resp *model.Response) {
t.Helper()
if !reflect.ValueOf(data).IsNil() {
t.Fatal("etag data was not nil")
}
if resp.StatusCode != http.StatusNotModified {
t.Log("actual: " + strconv.Itoa(resp.StatusCode))
t.Log("expected: " + strconv.Itoa(http.StatusNotModified))
t.Fatal("wrong status code for etag")
}
require.Empty(t, data)
require.Equal(t, resp.StatusCode, http.StatusNotModified, "wrong status code for etag")
}
func CheckNoError(t *testing.T, resp *model.Response) {
t.Helper()
if resp.Error != nil {
t.Fatalf("Expected no error, got %q", resp.Error.Error())
}
require.Nil(t, resp.Error)
}
func checkHTTPStatus(t *testing.T, resp *model.Response, expectedStatus int, expectError bool) {
t.Helper()
switch {
case resp == nil:
t.Fatalf("Unexpected nil response, expected http:%v, expectError:%v)", expectedStatus, expectError)
case expectError && resp.Error == nil:
t.Fatalf("Expected a non-nil error and http status:%v, got nil, %v", expectedStatus, resp.StatusCode)
case !expectError && resp.Error != nil:
t.Fatalf("Expected no error and http status:%v, got %q, http:%v", expectedStatus, resp.Error, resp.StatusCode)
case resp.StatusCode != expectedStatus:
t.Fatalf("Expected http status:%v, got %v (err: %q)", expectedStatus, resp.StatusCode, resp.Error)
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)
}
func CheckOKStatus(t *testing.T, resp *model.Response) {
@@ -661,16 +637,12 @@ func CheckInternalErrorStatus(t *testing.T, resp *model.Response) {
func CheckErrorMessage(t *testing.T, resp *model.Response, errorId string) {
t.Helper()
if resp.Error == nil {
t.Fatal("should have errored with message:" + errorId)
return
}
require.NotNil(t, resp.Error)
require.Equal(t, resp.Error.Id, errorId, "incorrect error message")
}
if resp.Error.Id != errorId {
t.Log("actual: " + resp.Error.Id)
t.Log("expected: " + errorId)
t.Fatal("incorrect error message")
}
func CheckStartsWith(t *testing.T, value, prefix, message string) {
require.True(t, strings.HasPrefix(value, prefix), message, value)
}
// Similar to s3.New() but allows initialization of signature v2 or signature v4 client.

Просмотреть файл

@@ -10,6 +10,7 @@ import (
"sort"
"strconv"
"strings"
"sync"
"testing"
"time"
@@ -2502,15 +2503,80 @@ func TestRemoveChannelMember(t *testing.T) {
_, resp = Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser.Id)
CheckForbiddenStatus(t, resp)
th.App.AddUserToChannel(th.BasicUser2, th.BasicChannel)
_, resp = Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser2.Id)
CheckNoError(t, resp)
t.Run("success", func(t *testing.T) {
// Setup the system administrator to listen for websocket events from the channels.
th.LinkUserToTeam(th.SystemAdminUser, th.BasicTeam)
_, err := th.App.AddUserToChannel(th.SystemAdminUser, th.BasicChannel)
require.Nil(t, err)
_, err = th.App.AddUserToChannel(th.SystemAdminUser, th.BasicChannel2)
require.Nil(t, err)
props := map[string]string{}
props[model.DESKTOP_NOTIFY_PROP] = model.CHANNEL_NOTIFY_ALL
_, resp = th.SystemAdminClient.UpdateChannelNotifyProps(th.BasicChannel.Id, th.SystemAdminUser.Id, props)
_, resp = th.SystemAdminClient.UpdateChannelNotifyProps(th.BasicChannel2.Id, th.SystemAdminUser.Id, props)
CheckNoError(t, resp)
_, resp = Client.RemoveUserFromChannel(th.BasicChannel2.Id, th.BasicUser.Id)
CheckNoError(t, resp)
wsClient, err := th.CreateWebSocketSystemAdminClient()
require.Nil(t, err)
wsClient.Listen()
var closeWsClient sync.Once
defer closeWsClient.Do(func() {
wsClient.Close()
})
_, resp = th.SystemAdminClient.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser.Id)
CheckNoError(t, resp)
wsr := <-wsClient.EventChannel
require.Equal(t, wsr.Event, model.WEBSOCKET_EVENT_HELLO)
// requirePost listens for websocket events and tries to find the post matching
// the expected post's channel and message.
requirePost := func(expectedPost *model.Post) {
t.Helper()
for {
select {
case event := <-wsClient.EventChannel:
postData, ok := event.Data["post"]
if !ok {
continue
}
post := model.PostFromJson(strings.NewReader(postData.(string)))
if post.ChannelId == expectedPost.ChannelId && post.Message == expectedPost.Message {
return
}
case <-time.After(5 * time.Second):
t.Fatal("failed to find expected post after 5 seconds")
return
}
}
}
th.App.AddUserToChannel(th.BasicUser2, th.BasicChannel)
_, resp = Client.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser2.Id)
CheckNoError(t, resp)
requirePost(&model.Post{
Message: fmt.Sprintf("@%s left the channel.", th.BasicUser2.Username),
ChannelId: th.BasicChannel.Id,
})
_, resp = Client.RemoveUserFromChannel(th.BasicChannel2.Id, th.BasicUser.Id)
CheckNoError(t, resp)
requirePost(&model.Post{
Message: fmt.Sprintf("@%s removed from the channel.", th.BasicUser.Username),
ChannelId: th.BasicChannel2.Id,
})
_, resp = th.SystemAdminClient.RemoveUserFromChannel(th.BasicChannel.Id, th.BasicUser.Id)
CheckNoError(t, resp)
requirePost(&model.Post{
Message: fmt.Sprintf("@%s removed from the channel.", th.BasicUser.Username),
ChannelId: th.BasicChannel.Id,
})
closeWsClient.Do(func() {
wsClient.Close()
})
})
// Leave deleted channel
th.LoginBasic()

Просмотреть файл

@@ -7,6 +7,7 @@ import (
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/stretchr/testify/assert"
)
func TestHelpCommand(t *testing.T) {
@@ -23,15 +24,11 @@ func TestHelpCommand(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.SupportSettings.HelpLink = "" })
rs1, _ := Client.ExecuteCommand(channel.Id, "/help ")
if rs1.GotoLocation != model.SUPPORT_SETTINGS_DEFAULT_HELP_LINK {
t.Fatal("failed to default help link")
}
assert.Equal(t, rs1.GotoLocation, model.SUPPORT_SETTINGS_DEFAULT_HELP_LINK, "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 ")
if rs2.GotoLocation != "https://docs.mattermost.com/guides/user.html" {
t.Fatal("failed to help link")
}
assert.Equal(t, rs2.GotoLocation, "https://docs.mattermost.com/guides/user.html", "failed to help link")
}

Просмотреть файл

@@ -39,12 +39,8 @@ func TestCreateCommand(t *testing.T) {
createdCmd, resp := th.SystemAdminClient.CreateCommand(newCmd)
CheckNoError(t, resp)
CheckCreatedStatus(t, resp)
if createdCmd.CreatorId != th.SystemAdminUser.Id {
t.Fatal("user ids didn't match")
}
if createdCmd.TeamId != th.BasicTeam.Id {
t.Fatal("team ids didn't match")
}
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)
CheckBadRequestStatus(t, resp)
@@ -100,34 +96,22 @@ func TestUpdateCommand(t *testing.T) {
rcmd, resp := Client.UpdateCommand(cmd2)
CheckNoError(t, resp)
if rcmd.Trigger != cmd2.Trigger {
t.Fatal("Trigger should have updated")
}
require.Equal(t, cmd2.Trigger, rcmd.Trigger, "Trigger should have updated")
if rcmd.Method != cmd2.Method {
t.Fatal("Method should have updated")
}
require.Equal(t, cmd2.Method, rcmd.Method, "Method should have updated")
if rcmd.URL != cmd2.URL {
t.Fatal("URL should have updated")
}
require.Equal(t, cmd2.URL, rcmd.URL, "URL should have updated")
if rcmd.CreatorId != cmd1.CreatorId {
t.Fatal("CreatorId should have not updated")
}
require.Equal(t, cmd1.CreatorId, rcmd.CreatorId, "CreatorId should have not updated")
if rcmd.Token != cmd1.Token {
t.Fatal("Token should have not updated")
}
require.Equal(t, cmd1.Token, rcmd.Token, "Token should have not updated")
cmd2.Id = GenerateTestId()
rcmd, resp = Client.UpdateCommand(cmd2)
CheckNotFoundStatus(t, resp)
if rcmd != nil {
t.Fatal("should be empty")
}
require.Nil(t, rcmd, "should be empty")
cmd2.Id = "junk"
@@ -176,21 +160,15 @@ func TestDeleteCommand(t *testing.T) {
ok, resp := Client.DeleteCommand(rcmd1.Id)
CheckNoError(t, resp)
if !ok {
t.Fatal("should have returned true")
}
require.True(t, ok)
rcmd1, _ = th.App.GetCommand(rcmd1.Id)
if rcmd1 != nil {
t.Fatal("should be nil")
}
require.Nil(t, rcmd1)
ok, resp = Client.DeleteCommand("junk")
CheckBadRequestStatus(t, resp)
if ok {
t.Fatal("should have returned false")
}
require.False(t, ok)
_, resp = Client.DeleteCommand(GenerateTestId())
CheckNotFoundStatus(t, resp)
@@ -248,24 +226,16 @@ func TestListCommands(t *testing.T) {
foundCustom = true
}
}
if !foundEcho {
t.Fatal("Couldn't find echo command")
}
if !foundCustom {
t.Fatal("Should list the custom command")
}
require.True(t, foundEcho, "Couldn't find echo command")
require.True(t, foundCustom, "Should list the custom command")
})
t.Run("ListCustomOnlyCommands", func(t *testing.T) {
listCommands, resp := th.SystemAdminClient.ListCommands(th.BasicTeam.Id, true)
CheckNoError(t, resp)
if len(listCommands) > 1 {
t.Fatal("Should list just one custom command")
}
if listCommands[0].Trigger != "custom_command" {
t.Fatal("Wrong custom command trigger")
}
require.Len(t, listCommands, 1, "Should list just one custom command")
require.Equal(t, listCommands[0].Trigger, "custom_command", "Wrong custom command trigger")
})
t.Run("UserWithNoPermissionForCustomCommands", func(t *testing.T) {
@@ -287,12 +257,8 @@ func TestListCommands(t *testing.T) {
foundCustom = true
}
}
if !foundEcho {
t.Fatal("Couldn't find echo command")
}
if foundCustom {
t.Fatal("Should not list the custom command")
}
require.True(t, foundEcho, "Couldn't find echo command")
require.False(t, foundCustom, "Should not list the custom command")
})
t.Run("NoMember", func(t *testing.T) {
@@ -344,12 +310,8 @@ func TestListAutocompleteCommands(t *testing.T) {
foundCustom = true
}
}
if !foundEcho {
t.Fatal("Couldn't find echo command")
}
if foundCustom {
t.Fatal("Should not list the custom command")
}
require.True(t, foundEcho, "Couldn't find echo command")
require.False(t, foundCustom, "Should not list the custom command")
})
t.Run("RegularUserCanListOnlySystemCommands", func(t *testing.T) {
@@ -366,12 +328,8 @@ func TestListAutocompleteCommands(t *testing.T) {
foundCustom = true
}
}
if !foundEcho {
t.Fatal("Couldn't find echo command")
}
if foundCustom {
t.Fatal("Should not list the custom command")
}
require.True(t, foundEcho, "Couldn't find echo command")
require.False(t, foundCustom, "Should not list the custom command")
})
t.Run("NoMember", func(t *testing.T) {
@@ -414,15 +372,11 @@ func TestRegenToken(t *testing.T) {
token, resp := th.SystemAdminClient.RegenCommandToken(createdCmd.Id)
CheckNoError(t, resp)
if token == createdCmd.Token {
t.Fatal("should update the token")
}
require.NotEqual(t, createdCmd.Token, token, "should update the token")
token, resp = Client.RegenCommandToken(createdCmd.Id)
CheckForbiddenStatus(t, resp)
if token != "" {
t.Fatal("should not return the token")
}
require.Empty(t, token, "should not return the token")
}
func TestExecuteInvalidCommand(t *testing.T) {
@@ -457,9 +411,8 @@ func TestExecuteInvalidCommand(t *testing.T) {
Trigger: "getcommand",
}
if _, err := th.App.CreateCommand(getCmd); err != nil {
t.Fatal("failed to create get command")
}
_, err := th.App.CreateCommand(getCmd)
require.Nil(t, err, "failed to create get command")
_, resp := Client.ExecuteCommand(channel.Id, "")
CheckBadRequestStatus(t, resp)
@@ -537,9 +490,8 @@ func TestExecuteGetCommand(t *testing.T) {
Token: token,
}
if _, err := th.App.CreateCommand(getCmd); err != nil {
t.Fatal("failed to create get command")
}
_, err := th.App.CreateCommand(getCmd)
require.Nil(t, err, "failed to create get command")
commandResponse, resp := Client.ExecuteCommand(channel.Id, "/getcommand")
CheckNoError(t, resp)
@@ -597,9 +549,8 @@ func TestExecutePostCommand(t *testing.T) {
Token: token,
}
if _, err := th.App.CreateCommand(postCmd); err != nil {
t.Fatal("failed to create get command")
}
_, err := th.App.CreateCommand(postCmd)
require.Nil(t, err, "failed to create get command")
commandResponse, resp := Client.ExecuteCommand(channel.Id, "/postcommand")
CheckNoError(t, resp)
@@ -652,9 +603,8 @@ func TestExecuteCommandAgainstChannelOnAnotherTeam(t *testing.T) {
Method: model.COMMAND_METHOD_POST,
Trigger: "postcommand",
}
if _, err := th.App.CreateCommand(postCmd); err != nil {
t.Fatal("failed to create post command")
}
_, err := th.App.CreateCommand(postCmd)
require.Nil(t, err, "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
@@ -702,15 +652,13 @@ func TestExecuteCommandAgainstChannelUserIsNotIn(t *testing.T) {
Method: model.COMMAND_METHOD_POST,
Trigger: "postcommand",
}
if _, err := th.App.CreateCommand(postCmd); err != nil {
t.Fatal("failed to create post command")
}
_, err := th.App.CreateCommand(postCmd)
require.Nil(t, err, "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.CHANNEL_OPEN, team2.Id)
if success, _ := client.RemoveUserFromChannel(channel2.Id, th.BasicUser.Id); !success {
t.Fatal("Failed to remove user from channel")
}
success, _ := client.RemoveUserFromChannel(channel2.Id, th.BasicUser.Id)
require.True(t, success, "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")
@@ -760,9 +708,8 @@ func TestExecuteCommandInDirectMessageChannel(t *testing.T) {
Method: model.COMMAND_METHOD_POST,
Trigger: "postcommand",
}
if _, err := th.App.CreateCommand(postCmd); err != nil {
t.Fatal("failed to create post command")
}
_, err := th.App.CreateCommand(postCmd)
require.Nil(t, err, "failed to create post command")
// make a direct message channel
dmChannel, response := client.CreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id)
@@ -823,9 +770,8 @@ func TestExecuteCommandInTeamUserIsNotOn(t *testing.T) {
Method: model.COMMAND_METHOD_POST,
Trigger: "postcommand",
}
if _, err := th.App.CreateCommand(postCmd); err != nil {
t.Fatal("failed to create post command")
}
_, err := th.App.CreateCommand(postCmd)
require.Nil(t, err, "failed to create post command")
// make a direct message channel
dmChannel, response := client.CreateDirectChannel(th.BasicUser.Id, th.BasicUser2.Id)
@@ -836,9 +782,9 @@ func TestExecuteCommandInTeamUserIsNotOn(t *testing.T) {
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
if success, _ := client.RemoveTeamMember(team2.Id, th.BasicUser.Id); !success {
t.Fatal("Failed to remove user from team")
}
success, _ := client.RemoveTeamMember(team2.Id, th.BasicUser.Id)
require.True(t, success, "Failed to remove user from team")
_, resp = client.ExecuteCommandWithTeam(dmChannel.Id, team2.Id, "/postcommand")
CheckForbiddenStatus(t, resp)

Просмотреть файл

@@ -7,6 +7,7 @@ import (
"github.com/mattermost/mattermost-server/model"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
@@ -127,16 +128,12 @@ func TestCORSRequestHandling(t *testing.T) {
url := fmt.Sprintf("%v/api/v4/system/ping", host)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
testcase.ModifyRequest(req)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, testcase.ExpectedAllowOrigin, resp.Header.Get(acAllowOrigin))
assert.Equal(t, testcase.ExpectedExposeHeaders, resp.Header.Get(acExposeHeaders))
@@ -146,5 +143,4 @@ func TestCORSRequestHandling(t *testing.T) {
assert.Equal(t, "", resp.Header.Get(acAllowHeaders))
})
}
}

Просмотреть файл

@@ -65,92 +65,6 @@ func (api *API) InitFile() {
}
func uploadFile(c *Context, w http.ResponseWriter, r *http.Request) {
defer io.Copy(ioutil.Discard, r.Body)
if !*c.App.Config().FileSettings.EnableFileAttachments {
c.Err = model.NewAppError("uploadFile", "api.file.attachments.disabled.app_error", nil, "", http.StatusNotImplemented)
return
}
if r.ContentLength > *c.App.Config().FileSettings.MaxFileSize {
c.Err = model.NewAppError("uploadFile", "api.file.upload_file.too_large.app_error", nil, "", http.StatusRequestEntityTooLarge)
return
}
now := time.Now()
var resStruct *model.FileUploadResponse
var appErr *model.AppError
if err := r.ParseMultipartForm(*c.App.Config().FileSettings.MaxFileSize); err != nil && err != http.ErrNotMultipart {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
} else if err == http.ErrNotMultipart {
defer r.Body.Close()
c.RequireChannelId()
c.RequireFilename()
if c.Err != nil {
return
}
channelId := c.Params.ChannelId
filename := c.Params.Filename
if !c.App.SessionHasPermissionToChannel(c.App.Session, channelId, model.PERMISSION_UPLOAD_FILE) {
c.SetPermissionError(model.PERMISSION_UPLOAD_FILE)
return
}
resStruct, appErr = c.App.UploadFiles(
FILE_TEAM_ID,
channelId,
c.App.Session.UserId,
[]io.ReadCloser{r.Body},
[]string{filename},
[]string{},
now,
)
} else {
m := r.MultipartForm
props := m.Value
if len(props["channel_id"]) == 0 {
c.SetInvalidParam("channel_id")
return
}
channelId := props["channel_id"][0]
c.Params.ChannelId = channelId
c.RequireChannelId()
if c.Err != nil {
return
}
if !c.App.SessionHasPermissionToChannel(c.App.Session, channelId, model.PERMISSION_UPLOAD_FILE) {
c.SetPermissionError(model.PERMISSION_UPLOAD_FILE)
return
}
resStruct, appErr = c.App.UploadMultipartFiles(
FILE_TEAM_ID,
channelId,
c.App.Session.UserId,
m.File["files"],
m.Value["client_ids"],
now,
)
}
if appErr != nil {
c.Err = appErr
return
}
w.WriteHeader(http.StatusCreated)
w.Write([]byte(resStruct.ToJson()))
}
func parseMultipartRequestHeader(req *http.Request) (boundary string, err error) {
v := req.Header.Get("Content-Type")
if v == "" {

Просмотреть файл

@@ -40,26 +40,20 @@ func escapeQuotes(s string) string {
return quoteEscaper.Replace(s)
}
func randomBytes(n int) []byte {
func randomBytes(t *testing.T, n int) []byte {
bb := make([]byte, n)
_, err := rand.Read(bb)
if err != nil {
panic(err.Error())
}
require.NoError(t, err)
return bb
}
func fileBytes(path string) []byte {
func fileBytes(t *testing.T, path string) []byte {
path = filepath.Join(testDir, path)
f, err := os.Open(path)
if err != nil {
panic(err.Error())
}
require.NoError(t, err)
defer f.Close()
bb, err := ioutil.ReadAll(f)
if err != nil {
panic(err.Error())
}
require.NoError(t, err)
return bb
}
@@ -183,7 +177,7 @@ func testUploadFilesMultipart(
require.Nil(t, err)
}
mw.Close()
require.NoError(t, mw.Close())
return testDoUploadFileRequest(t, c, "", mwBody.Bytes(), mw.FormDataContentType(), -1)
}
@@ -251,7 +245,7 @@ func TestUploadFiles(t *testing.T) {
{
title: "Happy invalid image",
names: []string{"testgif.gif"},
blobs: [][]byte{fileBytes("test-search.md")},
blobs: [][]byte{fileBytes(t, "test-search.md")},
skipPayloadValidation: true,
expectedCreatorId: th.BasicUser.Id,
},
@@ -382,7 +376,7 @@ func TestUploadFiles(t *testing.T) {
useChunkedInSimplePost: true,
skipPayloadValidation: true,
names: []string{"1Mb-stream"},
blobs: [][]byte{randomBytes(1024 * 1024)},
blobs: [][]byte{randomBytes(t, 1024*1024)},
setupConfig: func(a *app.App) func(a *app.App) {
maxFileSize := *a.Config().FileSettings.MaxFileSize
a.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.MaxFileSize = 1024 * 1024 })
@@ -480,7 +474,7 @@ func TestUploadFiles(t *testing.T) {
title: "Error stream too large",
skipPayloadValidation: true,
names: []string{"1Mb-stream"},
blobs: [][]byte{randomBytes(1024 * 1024)},
blobs: [][]byte{randomBytes(t, 1024*1024)},
skipSuccessValidation: true,
checkResponse: CheckRequestEntityTooLargeStatus,
setupConfig: func(a *app.App) func(a *app.App) {
@@ -532,7 +526,7 @@ func TestUploadFiles(t *testing.T) {
blobs := tc.blobs
if len(blobs) == 0 {
for _, name := range tc.names {
blobs = append(blobs, fileBytes(name))
blobs = append(blobs, fileBytes(t, name))
}
}
@@ -555,9 +549,9 @@ func TestUploadFiles(t *testing.T) {
return
}
if fileResp == nil || len(fileResp.FileInfos) == 0 || len(fileResp.FileInfos) != len(tc.names) {
t.Fatal("Empty or mismatched actual or expected FileInfos")
}
require.NotNil(t, fileResp, "Nil fileResp")
require.NotEqual(t, 0, len(fileResp.FileInfos), "Empty FileInfos")
require.Equal(t, len(tc.names), len(fileResp.FileInfos), "Mismatched actual or expected FileInfos")
for i, ri := range fileResp.FileInfos {
// The returned file info from the upload call will be missing some fields that will be stored in the database
@@ -613,8 +607,7 @@ func TestUploadFiles(t *testing.T) {
expected, err := ioutil.ReadFile(filepath.Join(testDir, name))
require.Nil(t, err)
if bytes.Compare(data, expected) != 0 {
if !bytes.Equal(data, expected) {
tf, err := ioutil.TempFile("", fmt.Sprintf("test_%v_*_%s", i, name))
require.Nil(t, err)
_, _ = io.Copy(tf, bytes.NewReader(data))
@@ -653,29 +646,20 @@ func TestGetFile(t *testing.T) {
t.Skip("skipping because no file driver is enabled")
}
fileId := ""
var sent []byte
var err error
if sent, err = testutils.ReadTestFile("test.png"); err != nil {
t.Fatal(err)
} else {
fileResp, resp := Client.UploadFile(sent, channel.Id, "test.png")
CheckNoError(t, resp)
sent, err := testutils.ReadTestFile("test.png")
require.NoError(t, err)
fileId = fileResp.FileInfos[0].Id
}
fileResp, resp := Client.UploadFile(sent, channel.Id, "test.png")
CheckNoError(t, resp)
fileId := fileResp.FileInfos[0].Id
data, resp := Client.GetFile(fileId)
CheckNoError(t, resp)
if len(data) == 0 {
t.Fatal("should not be empty")
}
require.NotEqual(t, 0, len(data), "should not be empty")
for i := range data {
if data[i] != sent[i] {
t.Fatal("received file didn't match sent one")
}
require.Equal(t, sent[i], data[i], "received file didn't match sent one")
}
_, resp = Client.GetFile("junk")
@@ -713,30 +697,19 @@ func TestGetFileHeaders(t *testing.T) {
_, resp = Client.GetFile(fileId)
CheckNoError(t, resp)
if contentType := resp.Header.Get("Content-Type"); !strings.HasPrefix(contentType, expectedContentType) {
t.Fatal("returned incorrect Content-Type", contentType)
}
CheckStartsWith(t, resp.Header.Get("Content-Type"), expectedContentType, "returned incorrect Content-Type")
if getInline {
if contentDisposition := resp.Header.Get("Content-Disposition"); !strings.HasPrefix(contentDisposition, "inline") {
t.Fatal("returned incorrect Content-Disposition", contentDisposition)
}
CheckStartsWith(t, resp.Header.Get("Content-Disposition"), "inline", "returned incorrect Content-Disposition")
} else {
if contentDisposition := resp.Header.Get("Content-Disposition"); !strings.HasPrefix(contentDisposition, "attachment") {
t.Fatal("returned incorrect Content-Disposition", contentDisposition)
}
CheckStartsWith(t, resp.Header.Get("Content-Disposition"), "attachment", "returned incorrect Content-Disposition")
}
_, resp = Client.DownloadFile(fileId, true)
CheckNoError(t, resp)
if contentType := resp.Header.Get("Content-Type"); !strings.HasPrefix(contentType, expectedContentType) {
t.Fatal("returned incorrect Content-Type", contentType)
}
if contentDisposition := resp.Header.Get("Content-Disposition"); !strings.HasPrefix(contentDisposition, "attachment") {
t.Fatal("returned incorrect Content-Disposition", contentDisposition)
}
CheckStartsWith(t, resp.Header.Get("Content-Type"), expectedContentType, "returned incorrect Content-Type")
CheckStartsWith(t, resp.Header.Get("Content-Disposition"), "attachment", "returned incorrect Content-Disposition")
}
}
@@ -768,27 +741,20 @@ func TestGetFileThumbnail(t *testing.T) {
t.Skip("skipping because no file driver is enabled")
}
fileId := ""
var sent []byte
var err error
if sent, err = testutils.ReadTestFile("test.png"); err != nil {
t.Fatal(err)
} else {
fileResp, resp := Client.UploadFile(sent, channel.Id, "test.png")
CheckNoError(t, resp)
sent, err := testutils.ReadTestFile("test.png")
require.NoError(t, err)
fileId = fileResp.FileInfos[0].Id
}
fileResp, resp := Client.UploadFile(sent, channel.Id, "test.png")
CheckNoError(t, resp)
fileId := fileResp.FileInfos[0].Id
// Wait a bit for files to ready
time.Sleep(2 * time.Second)
data, resp := Client.GetFileThumbnail(fileId)
CheckNoError(t, resp)
if len(data) == 0 {
t.Fatal("should not be empty")
}
require.NotEqual(t, 0, len(data), "should not be empty")
_, resp = Client.GetFileThumbnail("junk")
CheckBadRequestStatus(t, resp)
@@ -823,21 +789,19 @@ func TestGetFileLink(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.EnablePublicLink = true })
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.PublicLinkSalt = model.NewRandomString(32) })
fileId := ""
if data, err := testutils.ReadTestFile("test.png"); err != nil {
t.Fatal(err)
} else {
fileResp, resp := Client.UploadFile(data, channel.Id, "test.png")
CheckNoError(t, resp)
data, err := testutils.ReadTestFile("test.png")
require.NoError(t, err)
fileId = fileResp.FileInfos[0].Id
}
fileResp, uploadResp := Client.UploadFile(data, channel.Id, "test.png")
CheckNoError(t, uploadResp)
fileId := fileResp.FileInfos[0].Id
_, resp := Client.GetFileLink(fileId)
CheckBadRequestStatus(t, resp)
// Hacky way to assign file to a post (usually would be done by CreatePost call)
err := th.App.Srv.Store.FileInfo().AttachToPost(fileId, th.BasicPost.Id, th.BasicUser.Id)
err = th.App.Srv.Store.FileInfo().AttachToPost(fileId, th.BasicPost.Id, th.BasicUser.Id)
require.Nil(t, err)
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.EnablePublicLink = false })
@@ -850,10 +814,7 @@ func TestGetFileLink(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.EnablePublicLink = true })
link, resp := Client.GetFileLink(fileId)
CheckNoError(t, resp)
if link == "" {
t.Fatal("should've received public link")
}
require.NotEqual(t, "", link, "should've received public link")
_, resp = Client.GetFileLink("junk")
CheckBadRequestStatus(t, resp)
@@ -889,27 +850,19 @@ func TestGetFilePreview(t *testing.T) {
t.Skip("skipping because no file driver is enabled")
}
fileId := ""
var sent []byte
var err error
if sent, err = testutils.ReadTestFile("test.png"); err != nil {
t.Fatal(err)
} else {
fileResp, resp := Client.UploadFile(sent, channel.Id, "test.png")
CheckNoError(t, resp)
sent, err := testutils.ReadTestFile("test.png")
require.NoError(t, err)
fileId = fileResp.FileInfos[0].Id
}
fileResp, resp := Client.UploadFile(sent, channel.Id, "test.png")
CheckNoError(t, resp)
fileId := fileResp.FileInfos[0].Id
// Wait a bit for files to ready
time.Sleep(2 * time.Second)
data, resp := Client.GetFilePreview(fileId)
CheckNoError(t, resp)
if len(data) == 0 {
t.Fatal("should not be empty")
}
require.NotEqual(t, 0, len(data), "should not be empty")
_, resp = Client.GetFilePreview("junk")
CheckBadRequestStatus(t, resp)
@@ -942,17 +895,12 @@ func TestGetFileInfo(t *testing.T) {
t.Skip("skipping because no file driver is enabled")
}
fileId := ""
var sent []byte
var err error
if sent, err = testutils.ReadTestFile("test.png"); err != nil {
t.Fatal(err)
} else {
fileResp, resp := Client.UploadFile(sent, channel.Id, "test.png")
CheckNoError(t, resp)
sent, err := testutils.ReadTestFile("test.png")
require.NoError(t, err)
fileId = fileResp.FileInfos[0].Id
}
fileResp, resp := Client.UploadFile(sent, channel.Id, "test.png")
CheckNoError(t, resp)
fileId := fileResp.FileInfos[0].Id
// Wait a bit for files to ready
time.Sleep(2 * time.Second)
@@ -960,23 +908,14 @@ func TestGetFileInfo(t *testing.T) {
info, resp := Client.GetFileInfo(fileId)
CheckNoError(t, resp)
if err != nil {
t.Fatal(err)
} else if info.Id != fileId {
t.Fatal("got incorrect file")
} else if info.CreatorId != user.Id {
t.Fatal("file should be assigned to user")
} else if info.PostId != "" {
t.Fatal("file shouldn't have a post")
} else if info.Path != "" {
t.Fatal("file path shouldn't have been returned to client")
} else if info.ThumbnailPath != "" {
t.Fatal("file thumbnail path shouldn't have been returned to client")
} else if info.PreviewPath != "" {
t.Fatal("file preview path shouldn't have been returned to client")
} else if info.MimeType != "image/png" {
t.Fatal("mime type should've been image/png")
}
require.NoError(t, err)
require.Equal(t, fileId, info.Id, "got incorrect file")
require.Equal(t, user.Id, info.CreatorId, "file should be assigned to user")
require.Equal(t, "", info.PostId, "file shouldn't have a post")
require.Equal(t, "", info.Path, "file path shouldn't have been returned to client")
require.Equal(t, "", info.ThumbnailPath, "file thumbnail path shouldn't have been returned to client")
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")
CheckBadRequestStatus(t, resp)
@@ -1007,18 +946,16 @@ func TestGetPublicFile(t *testing.T) {
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.EnablePublicLink = true })
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.PublicLinkSalt = model.NewRandomString(32) })
fileId := ""
if data, err := testutils.ReadTestFile("test.png"); err != nil {
t.Fatal(err)
} else {
fileResp, resp := Client.UploadFile(data, channel.Id, "test.png")
CheckNoError(t, resp)
data, err := testutils.ReadTestFile("test.png")
require.NoError(t, err)
fileId = fileResp.FileInfos[0].Id
}
fileResp, httpResp := Client.UploadFile(data, channel.Id, "test.png")
CheckNoError(t, httpResp)
fileId := fileResp.FileInfos[0].Id
// Hacky way to assign file to a post (usually would be done by CreatePost call)
err := th.App.Srv.Store.FileInfo().AttachToPost(fileId, th.BasicPost.Id, th.BasicUser.Id)
err = th.App.Srv.Store.FileInfo().AttachToPost(fileId, th.BasicPost.Id, th.BasicUser.Id)
require.Nil(t, err)
info, err := th.App.Srv.Store.FileInfo().Get(fileId)
@@ -1028,31 +965,31 @@ func TestGetPublicFile(t *testing.T) {
// Wait a bit for files to ready
time.Sleep(2 * time.Second)
if resp, err := http.Get(link); err != nil || resp.StatusCode != http.StatusOK {
t.Log(link)
t.Fatal("failed to get image with public link", err)
}
resp, err := http.Get(link)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode, "failed to get image with public link")
if resp, err := http.Get(link[:strings.LastIndex(link, "?")]); err == nil && resp.StatusCode != http.StatusBadRequest {
t.Fatal("should've failed to get image with public link without hash", resp.Status)
}
resp, err = http.Get(link[:strings.LastIndex(link, "?")])
require.NoError(t, err)
require.Equal(t, http.StatusBadRequest, resp.StatusCode, "should've failed to get image with public link without hash", resp.Status)
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.EnablePublicLink = false })
if resp, err := http.Get(link); err == nil && resp.StatusCode != http.StatusNotImplemented {
t.Fatal("should've failed to get image with disabled public link")
}
resp, err = http.Get(link)
require.NoError(t, err)
require.Equal(t, http.StatusNotImplemented, resp.StatusCode, "should've failed to get image with disabled public link")
// test after the salt has changed
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.EnablePublicLink = true })
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.FileSettings.PublicLinkSalt = model.NewRandomString(32) })
if resp, err := http.Get(link); err == nil && resp.StatusCode != http.StatusBadRequest {
t.Fatal("should've failed to get image with public link after salt changed")
}
resp, err = http.Get(link)
require.NoError(t, err)
require.Equal(t, http.StatusBadRequest, resp.StatusCode, "should've failed to get image with public link after salt changed")
if resp, err := http.Get(link); err == nil && resp.StatusCode != http.StatusBadRequest {
t.Fatal("should've failed to get image with public link after salt changed")
}
resp, err = http.Get(link)
require.NoError(t, err)
require.Equal(t, http.StatusBadRequest, resp.StatusCode, "should've failed to get image with public link after salt changed")
fileInfo, err := th.App.Srv.Store.FileInfo().Get(fileId)
require.Nil(t, err)

Просмотреть файл

@@ -13,11 +13,6 @@ import (
"github.com/mattermost/mattermost-server/model"
)
const (
groupMemberActionCreate = iota
groupMemberActionDelete
)
func (api *API) InitGroup() {
// GET /api/v4/groups
api.BaseRoutes.Groups.Handle("", api.ApiSessionRequired(getGroups)).Methods("GET")

Просмотреть файл

@@ -112,7 +112,7 @@ func TestOpenDialog(t *testing.T) {
CallbackId: "callbackid",
Title: "Some Title",
Elements: []model.DialogElement{
model.DialogElement{
{
DisplayName: "Element Name",
Name: "element_name",
Type: "text",

Просмотреть файл

@@ -23,7 +23,7 @@ func TestCreateJob(t *testing.T) {
}
received, resp := th.SystemAdminClient.CreateJob(job)
CheckNoError(t, resp)
require.Nil(t, resp.Error)
defer th.App.Srv.Store.Job().Delete(received.Id)
@@ -52,11 +52,10 @@ func TestGetJob(t *testing.T) {
defer th.App.Srv.Store.Job().Delete(job.Id)
received, resp := th.SystemAdminClient.GetJob(job.Id)
CheckNoError(t, resp)
require.Nil(t, resp.Error)
if received.Id != job.Id || received.Status != job.Status {
t.Fatal("incorrect job received")
}
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")
CheckBadRequestStatus(t, resp)
@@ -100,22 +99,16 @@ func TestGetJobs(t *testing.T) {
}
received, resp := th.SystemAdminClient.GetJobs(0, 2)
CheckNoError(t, resp)
require.Nil(t, resp.Error)
if len(received) != 2 {
t.Fatal("received wrong number of jobs")
} else if received[0].Id != jobs[2].Id {
t.Fatal("should've received newest job first")
} else if received[1].Id != jobs[0].Id {
t.Fatal("should've received second newest job second")
}
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)
CheckNoError(t, resp)
require.Nil(t, resp.Error)
if received[0].Id != jobs[1].Id {
t.Fatal("should've received oldest job last")
}
require.Equal(t,jobs[1].Id, received[0].Id, "should've received oldest job last")
_, resp = th.Client.GetJobs(0, 60)
CheckForbiddenStatus(t, resp)
@@ -157,24 +150,17 @@ func TestGetJobsByType(t *testing.T) {
}
received, resp := th.SystemAdminClient.GetJobsByType(jobType, 0, 2)
CheckNoError(t, resp)
require.Nil(t, resp.Error)
if len(received) != 2 {
t.Fatal("received wrong number of jobs")
} else if received[0].Id != jobs[2].Id {
t.Fatal("should've received newest job first")
} else if received[1].Id != jobs[0].Id {
t.Fatal("should've received second newest job second")
}
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)
CheckNoError(t, resp)
require.Nil(t, resp.Error)
if len(received) != 1 {
t.Fatal("received wrong number of jobs")
} else if received[0].Id != jobs[1].Id {
t.Fatal("should've received oldest job last")
}
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)
CheckNotFoundStatus(t, resp)
@@ -218,10 +204,10 @@ func TestCancelJob(t *testing.T) {
CheckForbiddenStatus(t, resp)
_, resp = th.SystemAdminClient.CancelJob(jobs[0].Id)
CheckNoError(t, resp)
require.Nil(t, resp.Error)
_, resp = th.SystemAdminClient.CancelJob(jobs[1].Id)
CheckNoError(t, resp)
require.Nil(t, resp.Error)
_, resp = th.SystemAdminClient.CancelJob(jobs[2].Id)
CheckInternalErrorStatus(t, resp)

Просмотреть файл

@@ -387,7 +387,7 @@ func TestDisableOnRemove(t *testing.T) {
pluginsResp, resp := th.SystemAdminClient.GetPlugins()
CheckNoError(t, resp)
require.Len(t, pluginsResp.Active, 0)
require.Equal(t, pluginsResp.Inactive, []*model.PluginInfo{&model.PluginInfo{
require.Equal(t, pluginsResp.Inactive, []*model.PluginInfo{{
Manifest: *manifest,
}})
@@ -400,7 +400,7 @@ func TestDisableOnRemove(t *testing.T) {
pluginsResp, resp = th.SystemAdminClient.GetPlugins()
CheckNoError(t, resp)
require.Len(t, pluginsResp.Inactive, 0)
require.Equal(t, pluginsResp.Active, []*model.PluginInfo{&model.PluginInfo{
require.Equal(t, pluginsResp.Active, []*model.PluginInfo{{
Manifest: *manifest,
}})
@@ -414,7 +414,7 @@ func TestDisableOnRemove(t *testing.T) {
pluginsResp, resp = th.SystemAdminClient.GetPlugins()
CheckNoError(t, resp)
require.Len(t, pluginsResp.Inactive, 0)
require.Equal(t, pluginsResp.Active, []*model.PluginInfo{&model.PluginInfo{
require.Equal(t, pluginsResp.Active, []*model.PluginInfo{{
Manifest: *manifest,
}})
}
@@ -439,7 +439,7 @@ func TestDisableOnRemove(t *testing.T) {
pluginsResp, resp = th.SystemAdminClient.GetPlugins()
CheckNoError(t, resp)
require.Len(t, pluginsResp.Active, 0)
require.Equal(t, pluginsResp.Inactive, []*model.PluginInfo{&model.PluginInfo{
require.Equal(t, pluginsResp.Inactive, []*model.PluginInfo{{
Manifest: *manifest,
}})

Просмотреть файл

@@ -476,7 +476,7 @@ func searchPosts(c *Context, w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
results, err := c.App.SearchPostsInTeamForUser(terms, c.App.Session.UserId, c.Params.TeamId, isOrSearch, includeDeletedChannels, int(timeZoneOffset), page, perPage)
results, err := c.App.SearchPostsInTeamForUser(terms, c.App.Session.UserId, c.Params.TeamId, isOrSearch, includeDeletedChannels, timeZoneOffset, page, perPage)
elapsedTime := float64(time.Since(startTime)) / float64(time.Second)
metrics := c.App.Metrics

Просмотреть файл

@@ -8,6 +8,8 @@ import (
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/mattermost/mattermost-server/model"
)
@@ -42,14 +44,10 @@ func TestGetPreferences(t *testing.T) {
prefs, resp := Client.GetPreferences(user1.Id)
CheckNoError(t, resp)
if len(prefs) != 4 {
t.Fatal("received the wrong number of preferences")
}
require.Equal(t, len(prefs), 4, "received the wrong number of preferences")
for _, preference := range prefs {
if preference.UserId != th.BasicUser.Id {
t.Fatal("user id does not match")
}
require.Equal(t, preference.UserId, th.BasicUser.Id, "user id does not match")
}
th.LoginBasic2()
@@ -57,9 +55,7 @@ func TestGetPreferences(t *testing.T) {
prefs, resp = Client.GetPreferences(th.BasicUser2.Id)
CheckNoError(t, resp)
if len(prefs) == 0 {
t.Fatal("received the wrong number of preferences")
}
require.Greater(t, len(prefs), 0, "received the wrong number of preferences")
_, resp = Client.GetPreferences(th.BasicUser.Id)
CheckForbiddenStatus(t, resp)
@@ -101,9 +97,7 @@ func TestGetPreferencesByCategory(t *testing.T) {
prefs, resp := Client.GetPreferencesByCategory(user1.Id, category)
CheckNoError(t, resp)
if len(prefs) != 2 {
t.Fatalf("received the wrong number of preferences %v:%v", len(prefs), 2)
}
require.Equal(t, len(prefs), 2, "received the wrong number of preferences")
_, resp = Client.GetPreferencesByCategory(user1.Id, "junk")
CheckNotFoundStatus(t, resp)
@@ -119,9 +113,7 @@ func TestGetPreferencesByCategory(t *testing.T) {
prefs, resp = Client.GetPreferencesByCategory(th.BasicUser2.Id, "junk")
CheckNotFoundStatus(t, resp)
if len(prefs) != 0 {
t.Fatal("received the wrong number of preferences")
}
require.Equal(t, len(prefs), 0, "received the wrong number of preferences")
Client.Logout()
_, resp = Client.GetPreferencesByCategory(th.BasicUser2.Id, category)
@@ -158,9 +150,9 @@ func TestGetPreferenceByCategoryAndName(t *testing.T) {
pref, resp := Client.GetPreferenceByCategoryAndName(user.Id, model.PREFERENCE_CATEGORY_DIRECT_CHANNEL_SHOW, name)
CheckNoError(t, resp)
if (pref.UserId != preferences[0].UserId) && (pref.Category != preferences[0].Category) && (pref.Name != preferences[0].Name) {
t.Fatal("preference saved incorrectly")
}
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)
@@ -247,15 +239,12 @@ func TestUpdatePreferencesWebsocket(t *testing.T) {
defer th.TearDown()
WebSocketClient, err := th.CreateWebSocketClient()
if err != nil {
t.Fatal(err)
}
require.Nil(t, err)
WebSocketClient.Listen()
time.Sleep(300 * time.Millisecond)
if resp := <-WebSocketClient.ResponseChannel; resp.Status != model.STATUS_OK {
t.Fatal("should have responded OK to authentication challenge")
}
wsResp := <-WebSocketClient.ResponseChannel
require.Equal(t, wsResp.Status, model.STATUS_OK, "expected OK from auth challenge")
userId := th.BasicUser.Id
preferences := &model.Preferences{
@@ -285,19 +274,17 @@ func TestUpdatePreferencesWebsocket(t *testing.T) {
}
received, err := model.PreferencesFromJson(strings.NewReader(event.Data["preferences"].(string)))
if err != nil {
t.Fatal(err)
}
require.NoError(t, err)
for i, preference := range *preferences {
if preference.UserId != received[i].UserId || preference.Category != received[i].Category || preference.Name != received[i].Name {
t.Fatal("received incorrect preference")
}
for i, p := range *preferences {
require.Equal(t, received[i].UserId, p.UserId, "received incorrect UserId")
require.Equal(t, received[i].Category, p.Category, "received incorrect Category")
require.Equal(t, received[i].Name, p.Name, "received incorrect Name")
}
waiting = false
case <-timeout:
t.Fatal("timed out waiting for preference update event")
require.Fail(t, "timed timed out waiting for preference update event")
}
}
}

Просмотреть файл

@@ -4,6 +4,7 @@ import (
"testing"
"github.com/mattermost/mattermost-server/model"
"github.com/stretchr/testify/assert"
)
func TestGetUserStatus(t *testing.T) {
@@ -13,44 +14,32 @@ func TestGetUserStatus(t *testing.T) {
userStatus, resp := Client.GetUserStatus(th.BasicUser.Id, "")
CheckNoError(t, resp)
if userStatus.Status != "offline" {
t.Fatal("Should return offline status")
}
assert.Equal(t, "offline", userStatus.Status)
th.App.SetStatusOnline(th.BasicUser.Id, true)
userStatus, resp = Client.GetUserStatus(th.BasicUser.Id, "")
CheckNoError(t, resp)
if userStatus.Status != "online" {
t.Fatal("Should return online status")
}
assert.Equal(t, "online", userStatus.Status)
th.App.SetStatusAwayIfNeeded(th.BasicUser.Id, true)
userStatus, resp = Client.GetUserStatus(th.BasicUser.Id, "")
CheckNoError(t, resp)
if userStatus.Status != "away" {
t.Fatal("Should return away status")
}
assert.Equal(t, "away", userStatus.Status)
th.App.SetStatusDoNotDisturb(th.BasicUser.Id)
userStatus, resp = Client.GetUserStatus(th.BasicUser.Id, "")
CheckNoError(t, resp)
if userStatus.Status != "dnd" {
t.Fatal("Should return dnd status")
}
assert.Equal(t, "dnd", userStatus.Status)
th.App.SetStatusOffline(th.BasicUser.Id, true)
userStatus, resp = Client.GetUserStatus(th.BasicUser.Id, "")
CheckNoError(t, resp)
if userStatus.Status != "offline" {
t.Fatal("Should return offline status")
}
assert.Equal(t, "offline", userStatus.Status)
//Get user2 status logged as user1
userStatus, resp = Client.GetUserStatus(th.BasicUser2.Id, "")
CheckNoError(t, resp)
if userStatus.Status != "offline" {
t.Fatal("Should return offline status")
}
assert.Equal(t, "offline", userStatus.Status)
Client.Logout()
@@ -60,9 +49,7 @@ func TestGetUserStatus(t *testing.T) {
th.LoginBasic2()
userStatus, resp = Client.GetUserStatus(th.BasicUser2.Id, "")
CheckNoError(t, resp)
if userStatus.Status != "offline" {
t.Fatal("Should return offline status")
}
assert.Equal(t, "offline", userStatus.Status)
}
func TestGetUsersStatusesByIds(t *testing.T) {
@@ -75,9 +62,7 @@ func TestGetUsersStatusesByIds(t *testing.T) {
usersStatuses, resp := Client.GetUsersStatusesByIds(usersIds)
CheckNoError(t, resp)
for _, userStatus := range usersStatuses {
if userStatus.Status != "offline" {
t.Fatal("Status should be offline")
}
assert.Equal(t, "offline", userStatus.Status)
}
th.App.SetStatusOnline(th.BasicUser.Id, true)
@@ -85,9 +70,7 @@ func TestGetUsersStatusesByIds(t *testing.T) {
usersStatuses, resp = Client.GetUsersStatusesByIds(usersIds)
CheckNoError(t, resp)
for _, userStatus := range usersStatuses {
if userStatus.Status != "online" {
t.Fatal("Status should be offline")
}
assert.Equal(t, "online", userStatus.Status)
}
th.App.SetStatusAwayIfNeeded(th.BasicUser.Id, true)
@@ -95,9 +78,7 @@ func TestGetUsersStatusesByIds(t *testing.T) {
usersStatuses, resp = Client.GetUsersStatusesByIds(usersIds)
CheckNoError(t, resp)
for _, userStatus := range usersStatuses {
if userStatus.Status != "away" {
t.Fatal("Status should be offline")
}
assert.Equal(t, "away", userStatus.Status)
}
th.App.SetStatusDoNotDisturb(th.BasicUser.Id)
@@ -105,9 +86,7 @@ func TestGetUsersStatusesByIds(t *testing.T) {
usersStatuses, resp = Client.GetUsersStatusesByIds(usersIds)
CheckNoError(t, resp)
for _, userStatus := range usersStatuses {
if userStatus.Status != "dnd" {
t.Fatal("Status should be offline")
}
assert.Equal(t, "dnd", userStatus.Status)
}
Client.Logout()
@@ -124,30 +103,22 @@ func TestUpdateUserStatus(t *testing.T) {
toUpdateUserStatus := &model.Status{Status: "online", UserId: th.BasicUser.Id}
updateUserStatus, resp := Client.UpdateUserStatus(th.BasicUser.Id, toUpdateUserStatus)
CheckNoError(t, resp)
if updateUserStatus.Status != "online" {
t.Fatal("Should return online status")
}
assert.Equal(t, "online", updateUserStatus.Status)
toUpdateUserStatus.Status = "away"
updateUserStatus, resp = Client.UpdateUserStatus(th.BasicUser.Id, toUpdateUserStatus)
CheckNoError(t, resp)
if updateUserStatus.Status != "away" {
t.Fatal("Should return away status")
}
assert.Equal(t, "away", updateUserStatus.Status)
toUpdateUserStatus.Status = "dnd"
updateUserStatus, resp = Client.UpdateUserStatus(th.BasicUser.Id, toUpdateUserStatus)
CheckNoError(t, resp)
if updateUserStatus.Status != "dnd" {
t.Fatal("Should return dnd status")
}
assert.Equal(t, "dnd", updateUserStatus.Status)
toUpdateUserStatus.Status = "offline"
updateUserStatus, resp = Client.UpdateUserStatus(th.BasicUser.Id, toUpdateUserStatus)
CheckNoError(t, resp)
if updateUserStatus.Status != "offline" {
t.Fatal("Should return offline status")
}
assert.Equal(t, "offline", updateUserStatus.Status)
toUpdateUserStatus.Status = "online"
toUpdateUserStatus.UserId = th.BasicUser2.Id
@@ -156,9 +127,7 @@ func TestUpdateUserStatus(t *testing.T) {
toUpdateUserStatus.Status = "online"
updateUserStatus, _ = th.SystemAdminClient.UpdateUserStatus(th.BasicUser2.Id, toUpdateUserStatus)
if updateUserStatus.Status != "online" {
t.Fatal("Should return online status")
}
assert.Equal(t, "online", updateUserStatus.Status)
_, resp = Client.UpdateUserStatus(th.BasicUser.Id, toUpdateUserStatus)
CheckBadRequestStatus(t, resp)

Просмотреть файл

@@ -397,7 +397,6 @@ func getRedirectLocation(c *Context, w http.ResponseWriter, r *http.Request) {
m["location"] = location
w.Write([]byte(model.MapToJson(m)))
return
}
func pushNotificationAck(c *Context, w http.ResponseWriter, r *http.Request) {
@@ -415,5 +414,4 @@ func pushNotificationAck(c *Context, w http.ResponseWriter, r *http.Request) {
}
ReturnStatusOK(w)
return
}

Просмотреть файл

@@ -911,7 +911,7 @@ func importTeam(c *Context, w http.ResponseWriter, r *http.Request) {
}
data := map[string]string{}
data["results"] = base64.StdEncoding.EncodeToString([]byte(log.Bytes()))
data["results"] = base64.StdEncoding.EncodeToString(log.Bytes())
if c.Err != nil {
w.WriteHeader(c.Err.StatusCode)
}

Просмотреть файл

@@ -1422,8 +1422,6 @@ func login(c *Context, w http.ResponseWriter, r *http.Request) {
user.TermsOfServiceCreateAt = userTermsOfService.CreateAt
}
c.App.Session = *session
user.Sanitize(map[string]bool{})
w.Write([]byte(user.ToJson()))

Просмотреть файл

@@ -1369,7 +1369,8 @@ func TestGetUsersByGroupChannelIds(t *testing.T) {
usersByChannelId, resp := th.Client.GetUsersByGroupChannelIds([]string{gc1.Id})
CheckNoError(t, resp)
users, _ := usersByChannelId[gc1.Id]
users, ok := usersByChannelId[gc1.Id]
assert.True(t, ok)
userIds := []string{}
for _, user := range users {
userIds = append(userIds, user.Id)
@@ -1381,7 +1382,7 @@ func TestGetUsersByGroupChannelIds(t *testing.T) {
usersByChannelId, resp = th.Client.GetUsersByGroupChannelIds([]string{gc1.Id})
CheckNoError(t, resp)
_, ok := usersByChannelId[gc1.Id]
_, ok = usersByChannelId[gc1.Id]
require.False(t, ok)
th.Client.Logout()

Просмотреть файл

@@ -12,7 +12,8 @@ import (
)
func (api *API) InitWebSocket() {
api.BaseRoutes.ApiRoot.Handle("/websocket", api.ApiHandlerTrustRequester(connectWebSocket)).Methods("GET")
// Optionally supports a trailing slash
api.BaseRoutes.ApiRoot.Handle("/{websocket:websocket(?:\\/)?}", api.ApiHandlerTrustRequester(connectWebSocket)).Methods("GET")
}
func connectWebSocket(c *Context, w http.ResponseWriter, r *http.Request) {

Просмотреть файл

@@ -20,62 +20,59 @@ func TestWebSocket(t *testing.T) {
th := Setup().InitBasic()
defer th.TearDown()
WebSocketClient, err := th.CreateWebSocketClient()
if err != nil {
t.Fatal(err)
}
require.Nil(t, err)
defer WebSocketClient.Close()
time.Sleep(300 * time.Millisecond)
// Test closing and reconnecting
WebSocketClient.Close()
if err := WebSocketClient.Connect(); err != nil {
t.Fatal(err)
}
err = WebSocketClient.Connect()
require.Nil(t, err)
WebSocketClient.Listen()
time.Sleep(300 * time.Millisecond)
if resp := <-WebSocketClient.ResponseChannel; resp.Status != model.STATUS_OK {
t.Fatal("should have responded OK to authentication challenge")
}
resp := <-WebSocketClient.ResponseChannel
require.Equal(t, resp.Status, model.STATUS_OK, "should have responded OK to authentication challenge")
WebSocketClient.SendMessage("ping", nil)
time.Sleep(300 * time.Millisecond)
if resp := <-WebSocketClient.ResponseChannel; resp.Data["text"].(string) != "pong" {
t.Fatal("wrong response")
}
resp = <-WebSocketClient.ResponseChannel
require.Equal(t, resp.Data["text"].(string), "pong", "wrong response")
WebSocketClient.SendMessage("", nil)
time.Sleep(300 * time.Millisecond)
if resp := <-WebSocketClient.ResponseChannel; resp.Error.Id != "api.web_socket_router.no_action.app_error" {
t.Fatal("should have been no action response")
}
resp = <-WebSocketClient.ResponseChannel
require.Equal(t, resp.Error.Id, "api.web_socket_router.no_action.app_error", "should have been no action response")
WebSocketClient.SendMessage("junk", nil)
time.Sleep(300 * time.Millisecond)
if resp := <-WebSocketClient.ResponseChannel; resp.Error.Id != "api.web_socket_router.bad_action.app_error" {
t.Fatal("should have been bad action response")
}
resp = <-WebSocketClient.ResponseChannel
require.Equal(t, resp.Error.Id, "api.web_socket_router.bad_action.app_error", "should have been bad action response")
req := &model.WebSocketRequest{}
req.Seq = 0
req.Action = "ping"
WebSocketClient.Conn.WriteJSON(req)
time.Sleep(300 * time.Millisecond)
if resp := <-WebSocketClient.ResponseChannel; resp.Error.Id != "api.web_socket_router.bad_seq.app_error" {
t.Fatal("should have been bad action response")
}
resp = <-WebSocketClient.ResponseChannel
require.Equal(t, resp.Error.Id, "api.web_socket_router.bad_seq.app_error", "should have been bad action response")
WebSocketClient.UserTyping("", "")
time.Sleep(300 * time.Millisecond)
if resp := <-WebSocketClient.ResponseChannel; resp.Error.Id != "api.websocket_handler.invalid_param.app_error" {
t.Fatal("should have been invalid param response")
} else {
if resp.Error.DetailedError != "" {
t.Fatal("detailed error not cleared")
}
}
resp = <-WebSocketClient.ResponseChannel
require.Equal(t, resp.Error.Id, "api.websocket_handler.invalid_param.app_error", "should have been invalid param response")
require.Equal(t, resp.Error.DetailedError, "", "detailed error not cleared")
}
func TestWebSocketTrailingSlash(t *testing.T) {
th := Setup().InitBasic()
defer th.TearDown()
url := fmt.Sprintf("ws://localhost:%v", th.App.Srv.ListenAddr.Port)
_, _, err := websocket.DefaultDialer.Dial(url+model.API_URL_SUFFIX+"/websocket/", nil)
require.NoError(t, err)
}
func TestWebSocketEvent(t *testing.T) {
@@ -83,17 +80,14 @@ func TestWebSocketEvent(t *testing.T) {
defer th.TearDown()
WebSocketClient, err := th.CreateWebSocketClient()
if err != nil {
t.Fatal(err)
}
require.Nil(t, err)
defer WebSocketClient.Close()
WebSocketClient.Listen()
time.Sleep(300 * time.Millisecond)
if resp := <-WebSocketClient.ResponseChannel; resp.Status != model.STATUS_OK {
t.Fatal("should have responded OK to authentication challenge")
}
resp := <-WebSocketClient.ResponseChannel
require.Equal(t, resp.Status, model.STATUS_OK, "should have responded OK to authentication challenge")
omitUser := make(map[string]bool, 1)
omitUser["somerandomid"] = true
@@ -123,9 +117,7 @@ func TestWebSocketEvent(t *testing.T) {
stop <- true
if !eventHit {
t.Fatal("did not receive typing event")
}
require.True(t, eventHit, "did not receive typing event")
evt2 := model.NewWebSocketEvent(model.WEBSOCKET_EVENT_TYPING, "", "somerandomid", "", nil)
th.App.Publish(evt2)
@@ -150,9 +142,7 @@ func TestWebSocketEvent(t *testing.T) {
stop <- true
if eventHit {
t.Fatal("got typing event for bad channel id")
}
require.False(t, eventHit, "got typing event for bad channel id")
}
func TestCreateDirectChannelWithSocket(t *testing.T) {
@@ -170,21 +160,16 @@ func TestCreateDirectChannelWithSocket(t *testing.T) {
}
WebSocketClient, err := th.CreateWebSocketClient()
if err != nil {
t.Fatal(err)
}
require.Nil(t, err)
defer WebSocketClient.Close()
WebSocketClient.Listen()
time.Sleep(300 * time.Millisecond)
if resp := <-WebSocketClient.ResponseChannel; resp.Status != model.STATUS_OK {
t.Fatal("should have responded OK to authentication challenge")
}
resp := <-WebSocketClient.ResponseChannel
require.Equal(t, resp.Status, model.STATUS_OK, "should have responded OK to authentication challenge")
wsr := <-WebSocketClient.EventChannel
if wsr.Event != model.WEBSOCKET_EVENT_HELLO {
t.Fatal("missing hello")
}
require.Equal(t, wsr.Event, model.WEBSOCKET_EVENT_HELLO, "missing hello")
stop := make(chan bool)
count := 0
@@ -205,19 +190,15 @@ func TestCreateDirectChannelWithSocket(t *testing.T) {
for _, user := range users {
time.Sleep(100 * time.Millisecond)
if _, resp := Client.CreateDirectChannel(th.BasicUser.Id, user.Id); resp.Error != nil {
t.Fatal("failed to create DM channel")
}
_, resp := Client.CreateDirectChannel(th.BasicUser.Id, user.Id)
require.Nil(t, resp.Error, "failed to create DM channel")
}
time.Sleep(5000 * time.Millisecond)
stop <- true
if count != len(users) {
t.Fatal("We didn't get the proper amount of direct_added messages")
}
require.Equal(t, count, len(users), "We didn't get the proper amount of direct_added messages")
}
func TestWebsocketOriginSecurity(t *testing.T) {
@@ -230,53 +211,42 @@ func TestWebsocketOriginSecurity(t *testing.T) {
_, _, err := websocket.DefaultDialer.Dial(url+model.API_URL_SUFFIX+"/websocket", http.Header{
"Origin": []string{"http://www.evil.com"},
})
if err == nil {
t.Fatal("Should have errored because Origin does not match host! SECURITY ISSUE!")
}
require.NotNil(t, err, "Should have errored because Origin does not match host! SECURITY ISSUE!")
// We are not a browser so we can spoof this just fine
_, _, err = websocket.DefaultDialer.Dial(url+model.API_URL_SUFFIX+"/websocket", http.Header{
"Origin": []string{fmt.Sprintf("http://localhost:%v", th.App.Srv.ListenAddr.Port)},
})
if err != nil {
t.Fatal(err)
}
require.Nil(t, err, err)
// Should succeed now because open CORS
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowCorsFrom = "*" })
_, _, err = websocket.DefaultDialer.Dial(url+model.API_URL_SUFFIX+"/websocket", http.Header{
"Origin": []string{"http://www.evil.com"},
})
if err != nil {
t.Fatal(err)
}
require.Nil(t, err, err)
// Should succeed now because matching CORS
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowCorsFrom = "http://www.evil.com" })
_, _, err = websocket.DefaultDialer.Dial(url+model.API_URL_SUFFIX+"/websocket", http.Header{
"Origin": []string{"http://www.evil.com"},
})
if err != nil {
t.Fatal(err)
}
require.Nil(t, err, err)
// Should fail because non-matching CORS
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowCorsFrom = "http://www.good.com" })
_, _, err = websocket.DefaultDialer.Dial(url+model.API_URL_SUFFIX+"/websocket", http.Header{
"Origin": []string{"http://www.evil.com"},
})
if err == nil {
t.Fatal("Should have errored because Origin contain AllowCorsFrom")
}
require.NotNil(t, err, "Should have errored because Origin contain AllowCorsFrom")
// Should fail because non-matching CORS
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowCorsFrom = "http://www.good.com" })
_, _, err = websocket.DefaultDialer.Dial(url+model.API_URL_SUFFIX+"/websocket", http.Header{
"Origin": []string{"http://www.good.co"},
})
if err == nil {
t.Fatal("Should have errored because Origin does not match host! SECURITY ISSUE!")
}
require.NotNil(t, err, "Should have errored because Origin does not match host! SECURITY ISSUE!")
th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.AllowCorsFrom = "" })
}
@@ -287,16 +257,13 @@ func TestWebSocketStatuses(t *testing.T) {
Client := th.Client
WebSocketClient, err := th.CreateWebSocketClient()
if err != nil {
t.Fatal(err)
}
require.Nil(t, err, err)
defer WebSocketClient.Close()
WebSocketClient.Listen()
time.Sleep(300 * time.Millisecond)
if resp := <-WebSocketClient.ResponseChannel; resp.Status != model.STATUS_OK {
t.Fatal("should have responded OK to authentication challenge")
}
resp := <-WebSocketClient.ResponseChannel
require.Equal(t, resp.Status, model.STATUS_OK, "should have responded OK to authentication challenge")
team := model.Team{DisplayName: "Name", Name: "z-z-" + model.NewId() + "a", Email: "test@nowhere.com", Type: model.TEAM_OPEN}
rteam, _ := Client.CreateTeam(&team)
@@ -318,79 +285,53 @@ func TestWebSocketStatuses(t *testing.T) {
th.LoginBasic2()
WebSocketClient2, err2 := th.CreateWebSocketClient()
if err2 != nil {
t.Fatal(err2)
}
require.Nil(t, err2, err2)
time.Sleep(1000 * time.Millisecond)
WebSocketClient.GetStatuses()
if resp := <-WebSocketClient.ResponseChannel; resp.Error != nil {
t.Fatal(resp.Error)
} else {
if resp.SeqReply != WebSocketClient.Sequence-1 {
t.Fatal("bad sequence number")
}
resp = <-WebSocketClient.ResponseChannel
require.Nil(t, resp.Error, resp.Error)
for _, status := range resp.Data {
if status != model.STATUS_OFFLINE && status != model.STATUS_AWAY && status != model.STATUS_ONLINE && status != model.STATUS_DND {
t.Fatalf("one of the statuses had an invalid value status=%v", status)
}
}
require.Equal(t, resp.SeqReply, WebSocketClient.Sequence-1, "bad sequence number")
if status, ok := resp.Data[th.BasicUser2.Id]; !ok {
t.Log(resp.Data)
t.Fatal("should have had user status")
} else if status != model.STATUS_ONLINE {
t.Log(status)
t.Fatal("status should have been online")
}
allowedValues := [4]string{model.STATUS_OFFLINE, model.STATUS_AWAY, model.STATUS_ONLINE, model.STATUS_DND}
for _, status := range resp.Data {
require.Containsf(t, allowedValues, status, "one of the statuses had an invalid value status=%v", status)
}
status, ok := resp.Data[th.BasicUser2.Id]
require.True(t, ok, "should have had user status")
require.Equal(t, status, model.STATUS_ONLINE, "status should have been online status=%v", status)
WebSocketClient.GetStatusesByIds([]string{th.BasicUser2.Id})
if resp := <-WebSocketClient.ResponseChannel; resp.Error != nil {
t.Fatal(resp.Error)
} else {
if resp.SeqReply != WebSocketClient.Sequence-1 {
t.Fatal("bad sequence number")
}
resp = <-WebSocketClient.ResponseChannel
require.Nil(t, resp.Error, resp.Error)
for _, status := range resp.Data {
if status != model.STATUS_OFFLINE && status != model.STATUS_AWAY && status != model.STATUS_ONLINE {
t.Fatal("one of the statuses had an invalid value")
}
}
require.Equal(t, resp.SeqReply, WebSocketClient.Sequence-1, "bad sequence number")
if status, ok := resp.Data[th.BasicUser2.Id]; !ok {
t.Log(len(resp.Data))
t.Fatal("should have had user status")
} else if status != model.STATUS_ONLINE {
t.Log(status)
t.Fatal("status should have been online")
} else if len(resp.Data) != 1 {
t.Fatal("only 1 status should be returned")
}
allowedValues = [4]string{model.STATUS_OFFLINE, model.STATUS_AWAY, model.STATUS_ONLINE}
for _, status := range resp.Data {
require.Containsf(t, allowedValues, status, "one of the statuses had an invalid value status")
}
status, ok = resp.Data[th.BasicUser2.Id]
require.True(t, ok, "should have had user status")
require.Equal(t, status, model.STATUS_ONLINE, "status should have been online status=%v", status)
require.Equal(t, len(resp.Data), 1, "only 1 status should be returned")
WebSocketClient.GetStatusesByIds([]string{ruser2.Id, "junk"})
if resp := <-WebSocketClient.ResponseChannel; resp.Error != nil {
t.Fatal(resp.Error)
} else {
if resp.SeqReply != WebSocketClient.Sequence-1 {
t.Fatal("bad sequence number")
}
if len(resp.Data) != 2 {
t.Fatal("2 statuses should be returned")
}
}
resp = <-WebSocketClient.ResponseChannel
require.Nil(t, resp.Error, resp.Error)
require.Equal(t, resp.SeqReply, WebSocketClient.Sequence-1, "bad sequence number")
require.Equal(t, len(resp.Data), 2, "2 statuses should be returned")
WebSocketClient.GetStatusesByIds([]string{})
if resp := <-WebSocketClient.ResponseChannel; resp.Error == nil {
if resp.SeqReply != WebSocketClient.Sequence-1 {
t.Fatal("bad sequence number")
}
t.Fatal("should have errored - empty user ids")
if resp2 := <-WebSocketClient.ResponseChannel; resp2.Error == nil {
require.Equal(t, resp2.SeqReply, WebSocketClient.Sequence-1, "bad sequence number")
require.NotNil(t, resp2.Error, "should have errored - empty user ids")
}
WebSocketClient2.Close()
@@ -411,17 +352,12 @@ func TestWebSocketStatuses(t *testing.T) {
time.Sleep(1500 * time.Millisecond)
WebSocketClient.GetStatuses()
if resp := <-WebSocketClient.ResponseChannel; resp.Error != nil {
t.Fatal(resp.Error)
} else {
if resp.SeqReply != WebSocketClient.Sequence-1 {
t.Fatal("bad sequence number")
}
resp = <-WebSocketClient.ResponseChannel
require.Nil(t, resp.Error)
if _, ok := resp.Data[th.BasicUser2.Id]; ok {
t.Fatal("should not have had user status")
}
}
require.Equal(t, resp.SeqReply, WebSocketClient.Sequence-1, "bad sequence number")
_, ok = resp.Data[th.BasicUser2.Id]
require.False(t, ok, "should not have had user status")
stop := make(chan bool)
onlineHit := false
@@ -449,12 +385,8 @@ func TestWebSocketStatuses(t *testing.T) {
stop <- true
if !onlineHit {
t.Fatal("didn't get online event")
}
if !awayHit {
t.Fatal("didn't get away event")
}
require.True(t, onlineHit, "didn't get online event")
require.True(t, awayHit, "didn't get away event")
time.Sleep(500 * time.Millisecond)