diff --git a/api4/user_test.go b/api4/user_test.go index 003573fd09..06984e53e6 100644 --- a/api4/user_test.go +++ b/api4/user_test.go @@ -7,13 +7,11 @@ import ( "fmt" "net/http" "regexp" - "strconv" "strings" "testing" "time" "github.com/dgryski/dgoogauth" - "github.com/mattermost/mattermost-server/app" "github.com/mattermost/mattermost-server/model" "github.com/mattermost/mattermost-server/services/mailservice" @@ -34,14 +32,8 @@ func TestCreateUser(t *testing.T) { _, _ = th.Client.Login(user.Email, user.Password) - if ruser.Nickname != user.Nickname { - t.Fatal("nickname didn't match") - } - - if ruser.Roles != model.SYSTEM_USER_ROLE_ID { - t.Log(ruser.Roles) - t.Fatal("did not clear roles") - } + require.Equal(t, user.Nickname, ruser.Nickname, "nickname didn't match") + require.Equal(t, model.SYSTEM_USER_ROLE_ID, ruser.Roles, "did not clear roles") CheckUserSanitization(t, ruser) @@ -169,22 +161,16 @@ func TestCreateUserWithToken(t *testing.T) { CheckCreatedStatus(t, resp) th.Client.Login(user.Email, user.Password) - if ruser.Nickname != user.Nickname { - t.Fatal("nickname didn't match") - } - if ruser.Roles != model.SYSTEM_USER_ROLE_ID { - t.Log(ruser.Roles) - t.Fatal("did not clear roles") - } + require.Equal(t, user.Nickname, ruser.Nickname) + require.Equal(t, model.SYSTEM_USER_ROLE_ID, ruser.Roles, "should clear roles") CheckUserSanitization(t, ruser) _, err := th.App.Srv.Store.Token().GetByToken(token.Token) require.NotNil(t, err, "The token must be deleted after being used") - if teams, err := th.App.GetTeamsForUser(ruser.Id); err != nil || len(teams) == 0 { - t.Fatal("The user must have teams") - } else if teams[0].Id != th.BasicTeam.Id { - t.Fatal("The user joined team must be the team provided.") - } + teams, err := th.App.GetTeamsForUser(ruser.Id) + require.Nil(t, err) + require.NotEmpty(t, teams, "The user must have teams") + require.Equal(t, th.BasicTeam.Id, teams[0].Id, "The user joined team must be the team provided.") }) t.Run("NoToken", func(t *testing.T) { @@ -271,13 +257,8 @@ func TestCreateUserWithToken(t *testing.T) { CheckCreatedStatus(t, resp) th.Client.Login(user.Email, user.Password) - if ruser.Nickname != user.Nickname { - t.Fatal("nickname didn't match") - } - if ruser.Roles != model.SYSTEM_USER_ROLE_ID { - t.Log(ruser.Roles) - t.Fatal("did not clear roles") - } + require.Equal(t, user.Nickname, ruser.Nickname) + require.Equal(t, model.SYSTEM_USER_ROLE_ID, ruser.Roles, "should clear roles") CheckUserSanitization(t, ruser) _, err := th.App.Srv.Store.Token().GetByToken(token.Token) require.NotNil(t, err, "The token must be deleted after be used") @@ -298,13 +279,8 @@ func TestCreateUserWithInviteId(t *testing.T) { CheckCreatedStatus(t, resp) th.Client.Login(user.Email, user.Password) - if ruser.Nickname != user.Nickname { - t.Fatal("nickname didn't match") - } - if ruser.Roles != model.SYSTEM_USER_ROLE_ID { - t.Log(ruser.Roles) - t.Fatal("did not clear roles") - } + require.Equal(t, user.Nickname, ruser.Nickname) + require.Equal(t, model.SYSTEM_USER_ROLE_ID, ruser.Roles, "should clear roles") CheckUserSanitization(t, ruser) }) @@ -394,13 +370,8 @@ func TestCreateUserWithInviteId(t *testing.T) { CheckCreatedStatus(t, resp) th.Client.Login(user.Email, user.Password) - if ruser.Nickname != user.Nickname { - t.Fatal("nickname didn't match") - } - if ruser.Roles != model.SYSTEM_USER_ROLE_ID { - t.Log(ruser.Roles) - t.Fatal("did not clear roles") - } + require.Equal(t, user.Nickname, ruser.Nickname) + require.Equal(t, model.SYSTEM_USER_ROLE_ID, ruser.Roles, "should clear roles") CheckUserSanitization(t, ruser) }) } @@ -412,9 +383,7 @@ func TestGetMe(t *testing.T) { ruser, resp := th.Client.GetMe("") CheckNoError(t, resp) - if ruser.Id != th.BasicUser.Id { - t.Fatal("wrong user") - } + require.Equal(t, th.BasicUser.Id, ruser.Id) th.Client.Logout() _, resp = th.Client.GetMe("") @@ -434,9 +403,7 @@ func TestGetUser(t *testing.T) { CheckNoError(t, resp) CheckUserSanitization(t, ruser) - if ruser.Email != user.Email { - t.Fatal("emails did not match") - } + require.Equal(t, user.Email, ruser.Email) assert.NotNil(t, ruser.Props) assert.Equal(t, ruser.Props["testpropkey"], "testpropvalue") @@ -458,15 +425,9 @@ func TestGetUser(t *testing.T) { ruser, resp = th.Client.GetUser(user.Id, "") CheckNoError(t, resp) - if ruser.Email != "" { - t.Fatal("email should be blank") - } - if ruser.FirstName != "" { - t.Fatal("first name should be blank") - } - if ruser.LastName != "" { - t.Fatal("last name should be blank") - } + require.Empty(t, ruser.Email, "email should be blank") + require.Empty(t, ruser.FirstName, "first name should be blank") + require.Empty(t, ruser.LastName, "last name should be blank") th.Client.Logout() _, resp = th.Client.GetUser(user.Id, "") @@ -474,15 +435,9 @@ func TestGetUser(t *testing.T) { // System admins should ignore privacy settings ruser, _ = th.SystemAdminClient.GetUser(user.Id, resp.Etag) - if ruser.Email == "" { - t.Fatal("email should not be blank") - } - if ruser.FirstName == "" { - t.Fatal("first name should not be blank") - } - if ruser.LastName == "" { - t.Fatal("last name should not be blank") - } + require.NotEmpty(t, ruser.Email, "email should not be blank") + require.NotEmpty(t, ruser.FirstName, "first name should not be blank") + require.NotEmpty(t, ruser.LastName, "last name should not be blank") } func TestGetUserWithAcceptedTermsOfServiceForOtherUser(t *testing.T) { @@ -499,9 +454,7 @@ func TestGetUserWithAcceptedTermsOfServiceForOtherUser(t *testing.T) { CheckNoError(t, resp) CheckUserSanitization(t, ruser) - if ruser.Email != user.Email { - t.Fatal("emails did not match") - } + require.Equal(t, user.Email, ruser.Email) assert.Empty(t, ruser.TermsOfServiceId) @@ -511,9 +464,7 @@ func TestGetUserWithAcceptedTermsOfServiceForOtherUser(t *testing.T) { CheckNoError(t, resp) CheckUserSanitization(t, ruser) - if ruser.Email != user.Email { - t.Fatal("emails did not match") - } + require.Equal(t, user.Email, ruser.Email) // user TOS data cannot be fetched for other users by non-admin users assert.Empty(t, ruser.TermsOfServiceId) @@ -531,9 +482,7 @@ func TestGetUserWithAcceptedTermsOfService(t *testing.T) { CheckNoError(t, resp) CheckUserSanitization(t, ruser) - if ruser.Email != user.Email { - t.Fatal("emails did not match") - } + require.Equal(t, user.Email, ruser.Email) assert.Empty(t, ruser.TermsOfServiceId) @@ -543,9 +492,7 @@ func TestGetUserWithAcceptedTermsOfService(t *testing.T) { CheckNoError(t, resp) CheckUserSanitization(t, ruser) - if ruser.Email != user.Email { - t.Fatal("emails did not match") - } + require.Equal(t, user.Email, ruser.Email) // a user can view their own TOS details assert.Equal(t, tos.Id, ruser.TermsOfServiceId) @@ -564,9 +511,7 @@ func TestGetUserWithAcceptedTermsOfServiceWithAdminUser(t *testing.T) { CheckNoError(t, resp) CheckUserSanitization(t, ruser) - if ruser.Email != user.Email { - t.Fatal("emails did not match") - } + require.Equal(t, user.Email, ruser.Email) assert.Empty(t, ruser.TermsOfServiceId) @@ -576,9 +521,7 @@ func TestGetUserWithAcceptedTermsOfServiceWithAdminUser(t *testing.T) { CheckNoError(t, resp) CheckUserSanitization(t, ruser) - if ruser.Email != user.Email { - t.Fatal("emails did not match") - } + require.Equal(t, user.Email, ruser.Email) // admin can view anyone's TOS details assert.Equal(t, tos.Id, ruser.TermsOfServiceId) @@ -623,9 +566,7 @@ func TestGetUserByUsername(t *testing.T) { CheckNoError(t, resp) CheckUserSanitization(t, ruser) - if ruser.Email != user.Email { - t.Fatal("emails did not match") - } + require.Equal(t, user.Email, ruser.Email) ruser, resp = th.Client.GetUserByUsername(user.Username, resp.Etag) CheckEtag(t, ruser, resp) @@ -640,21 +581,13 @@ func TestGetUserByUsername(t *testing.T) { ruser, resp = th.Client.GetUserByUsername(th.BasicUser2.Username, "") CheckNoError(t, resp) - if ruser.Email != "" { - t.Fatal("email should be blank") - } - if ruser.FirstName != "" { - t.Fatal("first name should be blank") - } - if ruser.LastName != "" { - t.Fatal("last name should be blank") - } + require.Empty(t, ruser.Email, "email should be blank") + require.Empty(t, ruser.FirstName, "first name should be blank") + require.Empty(t, ruser.LastName, "last name should be blank") ruser, resp = th.Client.GetUserByUsername(th.BasicUser.Username, "") CheckNoError(t, resp) - if len(ruser.NotifyProps) == 0 { - t.Fatal("notify props should be sent") - } + require.NotEmpty(t, ruser.NotifyProps, "notify props should be sent") th.Client.Logout() _, resp = th.Client.GetUserByUsername(user.Username, "") @@ -662,15 +595,9 @@ func TestGetUserByUsername(t *testing.T) { // System admins should ignore privacy settings ruser, _ = th.SystemAdminClient.GetUserByUsername(user.Username, resp.Etag) - if ruser.Email == "" { - t.Fatal("email should not be blank") - } - if ruser.FirstName == "" { - t.Fatal("first name should not be blank") - } - if ruser.LastName == "" { - t.Fatal("last name should not be blank") - } + require.NotEmpty(t, ruser.Email, "email should not be blank") + require.NotEmpty(t, ruser.FirstName, "first name should not be blank") + require.NotEmpty(t, ruser.LastName, "last name should not be blank") } func TestGetUserByUsernameWithAcceptedTermsOfService(t *testing.T) { @@ -683,9 +610,7 @@ func TestGetUserByUsernameWithAcceptedTermsOfService(t *testing.T) { CheckNoError(t, resp) CheckUserSanitization(t, ruser) - if ruser.Email != user.Email { - t.Fatal("emails did not match") - } + require.Equal(t, user.Email, ruser.Email) tos, _ := th.App.CreateTermsOfService("Dummy TOS", user.Id) th.App.SaveUserTermsOfService(ruser.Id, tos.Id, true) @@ -694,13 +619,9 @@ func TestGetUserByUsernameWithAcceptedTermsOfService(t *testing.T) { CheckNoError(t, resp) CheckUserSanitization(t, ruser) - if ruser.Email != user.Email { - t.Fatal("emails did not match") - } + require.Equal(t, user.Email, ruser.Email) - if ruser.TermsOfServiceId != tos.Id { - t.Fatal("Terms of service ID didn't match") - } + require.Equal(t, tos.Id, ruser.TermsOfServiceId, "Terms of service ID should match") } func TestGetUserByEmail(t *testing.T) { @@ -719,9 +640,7 @@ func TestGetUserByEmail(t *testing.T) { CheckNoError(t, resp) CheckUserSanitization(t, ruser) - if ruser.Email != user.Email { - t.Fatal("emails did not match") - } + require.Equal(t, user.Email, ruser.Email) }) t.Run("should return not modified when provided with a matching etag", func(t *testing.T) { @@ -829,14 +748,10 @@ func TestSearchUsers(t *testing.T) { users, resp := th.Client.SearchUsers(search) CheckNoError(t, resp) - if !findUserInList(th.BasicUser.Id, users) { - t.Fatal("should have found user") - } + require.True(t, findUserInList(th.BasicUser.Id, users), "should have found user") _, err := th.App.UpdateActive(th.BasicUser2, false) - if err != nil { - t.Fatal(err) - } + require.Nil(t, err) search.Term = th.BasicUser2.Username search.AllowInactive = false @@ -844,18 +759,14 @@ func TestSearchUsers(t *testing.T) { users, resp = th.Client.SearchUsers(search) CheckNoError(t, resp) - if findUserInList(th.BasicUser2.Id, users) { - t.Fatal("should not have found user") - } + require.False(t, findUserInList(th.BasicUser2.Id, users), "should not have found user") search.AllowInactive = true users, resp = th.Client.SearchUsers(search) CheckNoError(t, resp) - if !findUserInList(th.BasicUser2.Id, users) { - t.Fatal("should have found user") - } + require.True(t, findUserInList(th.BasicUser2.Id, users), "should have found user") search.Term = th.BasicUser.Username search.AllowInactive = false @@ -864,18 +775,14 @@ func TestSearchUsers(t *testing.T) { users, resp = th.Client.SearchUsers(search) CheckNoError(t, resp) - if !findUserInList(th.BasicUser.Id, users) { - t.Fatal("should have found user") - } + require.True(t, findUserInList(th.BasicUser.Id, users), "should have found user") search.NotInChannelId = th.BasicChannel.Id users, resp = th.Client.SearchUsers(search) CheckNoError(t, resp) - if findUserInList(th.BasicUser.Id, users) { - t.Fatal("should not have found user") - } + require.False(t, findUserInList(th.BasicUser.Id, users), "should not have found user") search.TeamId = "" search.NotInChannelId = "" @@ -884,9 +791,7 @@ func TestSearchUsers(t *testing.T) { users, resp = th.Client.SearchUsers(search) CheckNoError(t, resp) - if !findUserInList(th.BasicUser.Id, users) { - t.Fatal("should have found user") - } + require.True(t, findUserInList(th.BasicUser.Id, users), "should have found user") search.InChannelId = "" search.NotInChannelId = th.BasicChannel.Id @@ -917,9 +822,7 @@ func TestSearchUsers(t *testing.T) { users, resp = th.Client.SearchUsers(search) CheckNoError(t, resp) - if findUserInList(th.BasicUser.Id, users) { - t.Fatal("should not have found user") - } + require.False(t, findUserInList(th.BasicUser.Id, users), "should not have found user") oddUser := th.CreateUser() search.Term = oddUser.Username @@ -927,9 +830,7 @@ func TestSearchUsers(t *testing.T) { users, resp = th.Client.SearchUsers(search) CheckNoError(t, resp) - if !findUserInList(oddUser.Id, users) { - t.Fatal("should have found user") - } + require.True(t, findUserInList(oddUser.Id, users), "should have found user") _, resp = th.SystemAdminClient.AddTeamMember(th.BasicTeam.Id, oddUser.Id) CheckNoError(t, resp) @@ -937,9 +838,7 @@ func TestSearchUsers(t *testing.T) { users, resp = th.Client.SearchUsers(search) CheckNoError(t, resp) - if findUserInList(oddUser.Id, users) { - t.Fatal("should not have found user") - } + require.False(t, findUserInList(oddUser.Id, users), "should not have found user") search.NotInTeamId = model.NewId() _, resp = th.Client.SearchUsers(search) @@ -951,9 +850,7 @@ func TestSearchUsers(t *testing.T) { th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PrivacySettings.ShowFullName = false }) _, err = th.App.UpdateActive(th.BasicUser2, true) - if err != nil { - t.Fatal(err) - } + require.Nil(t, err) search.InChannelId = "" search.NotInTeamId = "" @@ -961,25 +858,19 @@ func TestSearchUsers(t *testing.T) { users, resp = th.Client.SearchUsers(search) CheckNoError(t, resp) - if findUserInList(th.BasicUser2.Id, users) { - t.Fatal("should not have found user") - } + require.False(t, findUserInList(th.BasicUser2.Id, users), "should not have found user") search.Term = th.BasicUser2.FirstName users, resp = th.Client.SearchUsers(search) CheckNoError(t, resp) - if findUserInList(th.BasicUser2.Id, users) { - t.Fatal("should not have found user") - } + require.False(t, findUserInList(th.BasicUser2.Id, users), "should not have found user") search.Term = th.BasicUser2.LastName users, resp = th.Client.SearchUsers(search) CheckNoError(t, resp) - if findUserInList(th.BasicUser2.Id, users) { - t.Fatal("should not have found user") - } + require.False(t, findUserInList(th.BasicUser2.Id, users), "should not have found user") search.Term = th.BasicUser.FirstName search.InChannelId = th.BasicChannel.Id @@ -988,9 +879,7 @@ func TestSearchUsers(t *testing.T) { users, resp = th.SystemAdminClient.SearchUsers(search) CheckNoError(t, resp) - if !findUserInList(th.BasicUser.Id, users) { - t.Fatal("should have found user") - } + require.True(t, findUserInList(th.BasicUser.Id, users), "should have found user") } func findUserInList(id string, users []*model.User) bool { @@ -1265,14 +1154,10 @@ func TestGetProfileImage(t *testing.T) { data, resp := th.Client.GetProfileImage(user.Id, "") CheckNoError(t, resp) - if len(data) == 0 { - t.Fatal("Should not be empty") - } + require.NotEmpty(t, data, "should not be empty") _, resp = th.Client.GetProfileImage(user.Id, resp.Etag) - if resp.StatusCode == http.StatusNotModified { - t.Fatal("Shouldn't have hit etag") - } + require.NotEqual(t, http.StatusNotModified, resp.StatusCode, "should not hit etag") _, resp = th.Client.GetProfileImage("junk", "") CheckBadRequestStatus(t, resp) @@ -1288,9 +1173,8 @@ func TestGetProfileImage(t *testing.T) { CheckNoError(t, resp) info := &model.FileInfo{Path: "/users/" + user.Id + "/profile.png"} - if err := th.cleanupTestFile(info); err != nil { - t.Fatal(err) - } + err := th.cleanupTestFile(info) + require.NoError(t, err) } func TestGetUsersByIds(t *testing.T) { @@ -1316,18 +1200,15 @@ func TestGetUsersByIds(t *testing.T) { users, resp := th.Client.GetUsersByIds([]string{"junk"}) CheckNoError(t, resp) - if len(users) > 0 { - t.Fatal("no users should be returned") - } + require.Empty(t, users, "no users should be returned") }) t.Run("should still return users for valid IDs when invalid IDs are specified", func(t *testing.T) { users, resp := th.Client.GetUsersByIds([]string{"junk", th.BasicUser.Id}) CheckNoError(t, resp) - if len(users) != 1 { - t.Fatal("1 user should be returned") - } + + require.Len(t, users, 1, "1 user should be returned") }) t.Run("should return error when not logged in", func(t *testing.T) { @@ -1402,9 +1283,7 @@ func TestGetUsersByUsernames(t *testing.T) { users, resp := th.Client.GetUsersByUsernames([]string{th.BasicUser.Username}) CheckNoError(t, resp) - if users[0].Id != th.BasicUser.Id { - t.Fatal("returned wrong user") - } + require.Equal(t, th.BasicUser.Id, users[0].Id) CheckUserSanitization(t, users[0]) _, resp = th.Client.GetUsersByIds([]string{}) @@ -1412,15 +1291,11 @@ func TestGetUsersByUsernames(t *testing.T) { users, resp = th.Client.GetUsersByUsernames([]string{"junk"}) CheckNoError(t, resp) - if len(users) > 0 { - t.Fatal("no users should be returned") - } + require.Empty(t, users, "no users should be returned") users, resp = th.Client.GetUsersByUsernames([]string{"junk", th.BasicUser.Username}) CheckNoError(t, resp) - if len(users) != 1 { - t.Fatal("1 user should be returned") - } + require.Len(t, users, 1, "1 user should be returned") th.Client.Logout() _, resp = th.Client.GetUsersByUsernames([]string{th.BasicUser.Username}) @@ -1439,9 +1314,7 @@ func TestGetTotalUsersStat(t *testing.T) { rstats, resp := th.Client.GetTotalUsersStats("") CheckNoError(t, resp) - if rstats.TotalUsersCount != total { - t.Fatal("wrong count") - } + require.Equal(t, total, rstats.TotalUsersCount) } func TestUpdateUser(t *testing.T) { @@ -1459,15 +1332,9 @@ func TestUpdateUser(t *testing.T) { CheckNoError(t, resp) CheckUserSanitization(t, ruser) - if ruser.Nickname != "Joram Wilander" { - t.Fatal("Nickname did not update properly") - } - if ruser.Roles != model.SYSTEM_USER_ROLE_ID { - t.Fatal("Roles should not have updated") - } - if ruser.LastPasswordUpdate == 123 { - t.Fatal("LastPasswordUpdate should not have updated") - } + require.Equal(t, "Joram Wilander", ruser.Nickname, "Nickname should update properly") + require.Equal(t, model.SYSTEM_USER_ROLE_ID, ruser.Roles, "Roles should not update") + require.NotEqual(t, 123, ruser.LastPasswordUpdate, "LastPasswordUpdate should not update") ruser.Email = th.GenerateTestEmail() _, resp = th.Client.UpdateUser(ruser) @@ -1486,15 +1353,9 @@ func TestUpdateUser(t *testing.T) { _, resp = th.Client.UpdateUser(ruser) CheckForbiddenStatus(t, resp) - if r, err := th.Client.DoApiPut("/users/"+ruser.Id, "garbage"); err == nil { - t.Fatal("should have errored") - } else { - if r.StatusCode != http.StatusBadRequest { - t.Log("actual: " + strconv.Itoa(r.StatusCode)) - t.Log("expected: " + strconv.Itoa(http.StatusBadRequest)) - t.Fatal("wrong status code") - } - } + r, err := th.Client.DoApiPut("/users/"+ruser.Id, "garbage") + require.Error(t, err) + require.Equal(t, http.StatusBadRequest, r.StatusCode) session, _ := th.App.GetSession(th.Client.AuthToken) session.IsOAuth = true @@ -1541,50 +1402,26 @@ func TestPatchUser(t *testing.T) { CheckNoError(t, resp) CheckUserSanitization(t, ruser) - if ruser.Nickname != "Joram Wilander" { - t.Fatal("Nickname did not update properly") - } - if ruser.FirstName != "Joram" { - t.Fatal("FirstName did not update properly") - } - if ruser.LastName != "Wilander" { - t.Fatal("LastName did not update properly") - } - if ruser.Position != "" { - t.Fatal("Position did not update properly") - } - if ruser.Username != user.Username { - t.Fatal("Username should not have updated") - } - if ruser.Password != "" { - t.Fatal("Password should not be returned") - } - if ruser.NotifyProps["comment"] != "somethingrandom" { - t.Fatal("NotifyProps did not update properly") - } - if ruser.Timezone["useAutomaticTimezone"] != "true" { - t.Fatal("useAutomaticTimezone did not update properly") - } - if ruser.Timezone["automaticTimezone"] != "America/New_York" { - t.Fatal("automaticTimezone did not update properly") - } - if ruser.Timezone["manualTimezone"] != "" { - t.Fatal("manualTimezone did not update properly") - } + require.Equal(t, "Joram Wilander", ruser.Nickname, "Nickname should update properly") + require.Equal(t, "Joram", ruser.FirstName, "FirstName should update properly") + require.Equal(t, "Wilander", ruser.LastName, "LastName should update properly") + require.Empty(t, ruser.Position, "Position should update properly") + require.Equal(t, user.Username, ruser.Username, "Username should not update") + require.Empty(t, ruser.Password, "Password should not be returned") + require.Equal(t, "somethingrandom", ruser.NotifyProps["comment"], "NotifyProps should update properly") + require.Equal(t, "true", ruser.Timezone["useAutomaticTimezone"], "useAutomaticTimezone should update properly") + require.Equal(t, "America/New_York", ruser.Timezone["automaticTimezone"], "automaticTimezone should update properly") + require.Empty(t, ruser.Timezone["manualTimezone"], "manualTimezone should update properly") err := th.App.CheckPasswordAndAllCriteria(ruser, *patch.Password, "") assert.Error(t, err, "Password should not match") currentPassword := user.Password user, err = th.App.GetUser(ruser.Id) - if err != nil { - t.Fatal("User Get shouldn't error") - } + require.Nil(t, err) err = th.App.CheckPasswordAndAllCriteria(user, currentPassword, "") - if err != nil { - t.Fatal("Password should still match") - } + require.Nil(t, err, "Password should still match") patch = &model.UserPatch{} patch.Email = model.NewString(th.GenerateTestEmail()) @@ -1596,9 +1433,7 @@ func TestPatchUser(t *testing.T) { ruser, resp = th.Client.PatchUser(user.Id, patch) CheckNoError(t, resp) - if ruser.Email != *patch.Email { - t.Fatal("Email did not update properly") - } + require.Equal(t, *patch.Email, ruser.Email, "Email should update properly") patch.Username = model.NewString(th.BasicUser2.Username) _, resp = th.Client.PatchUser(user.Id, patch) @@ -1613,15 +1448,9 @@ func TestPatchUser(t *testing.T) { _, resp = th.Client.PatchUser(model.NewId(), patch) CheckForbiddenStatus(t, resp) - if r, err := th.Client.DoApiPut("/users/"+user.Id+"/patch", "garbage"); err == nil { - t.Fatal("should have errored") - } else { - if r.StatusCode != http.StatusBadRequest { - t.Log("actual: " + strconv.Itoa(r.StatusCode)) - t.Log("expected: " + strconv.Itoa(http.StatusBadRequest)) - t.Fatal("wrong status code") - } - } + r, err := th.Client.DoApiPut("/users/"+user.Id+"/patch", "garbage") + require.Error(t, err) + require.Equal(t, http.StatusBadRequest, r.StatusCode) session, _ := th.App.GetSession(th.Client.AuthToken) session.IsOAuth = true @@ -1661,9 +1490,8 @@ func TestUpdateUserAuth(t *testing.T) { userAuth.Password = user.Password // Regular user can not use endpoint - if _, err := th.SystemAdminClient.UpdateUserAuth(user.Id, userAuth); err == nil { - t.Fatal("Shouldn't have permissions. Only Admins") - } + _, respErr := th.SystemAdminClient.UpdateUserAuth(user.Id, userAuth) + require.NotNil(t, respErr, "Shouldn't have permissions. Only Admins") userAuth.AuthData = model.NewString("test@test.com") userAuth.AuthService = model.USER_AUTH_SERVICE_SAML @@ -1672,23 +1500,16 @@ func TestUpdateUserAuth(t *testing.T) { CheckNoError(t, resp) // AuthData and AuthService are set, password is set to empty - if *ruser.AuthData != *userAuth.AuthData { - t.Fatal("Should have set the correct AuthData") - } - if ruser.AuthService != model.USER_AUTH_SERVICE_SAML { - t.Fatal("Should have set the correct AuthService") - } - if ruser.Password != "" { - t.Fatal("Password should be empty") - } + require.Equal(t, *userAuth.AuthData, *ruser.AuthData) + require.Equal(t, model.USER_AUTH_SERVICE_SAML, ruser.AuthService) + require.Empty(t, ruser.Password) // When AuthData or AuthService are empty, password must be valid userAuth.AuthData = user.AuthData userAuth.AuthService = "" userAuth.Password = "1" - if _, err := th.SystemAdminClient.UpdateUserAuth(user.Id, userAuth); err == nil { - t.Fatal("Should have errored - user password not valid") - } + _, respErr = th.SystemAdminClient.UpdateUserAuth(user.Id, userAuth) + require.NotNil(t, respErr) // Regular user can not use endpoint user2 := th.CreateUser() @@ -1701,9 +1522,8 @@ func TestUpdateUserAuth(t *testing.T) { userAuth.AuthData = user.AuthData userAuth.AuthService = user.AuthService userAuth.Password = user.Password - if _, err := th.SystemAdminClient.UpdateUserAuth(user.Id, userAuth); err == nil { - t.Fatal("Should have errored") - } + _, respErr = th.SystemAdminClient.UpdateUserAuth(user.Id, userAuth) + require.NotNil(t, respErr, "Should have errored") } func TestDeleteUser(t *testing.T) { @@ -1778,9 +1598,8 @@ func assertExpectedWebsocketEvent(t *testing.T, client *model.WebSocketClient, e for { select { case resp, ok := <-client.EventChannel: - if !ok { - t.Fatalf("channel closed before receiving expected event %s", model.WEBSOCKET_EVENT_USER_UPDATED) - } else if resp.Event == model.WEBSOCKET_EVENT_USER_UPDATED { + require.Truef(t, ok, "channel closed before receiving expected event %s", model.WEBSOCKET_EVENT_USER_UPDATED) + if resp.Event == model.WEBSOCKET_EVENT_USER_UPDATED { test(resp) return } @@ -1792,13 +1611,11 @@ func assertExpectedWebsocketEvent(t *testing.T, client *model.WebSocketClient, e func assertWebsocketEventUserUpdatedWithEmail(t *testing.T, client *model.WebSocketClient, email string) { assertExpectedWebsocketEvent(t, client, model.WEBSOCKET_EVENT_USER_UPDATED, func(event *model.WebSocketEvent) { - if eventUser, ok := event.Data["user"].(map[string]interface{}); !ok { - t.Fatalf("expected user") - } else if userEmail, ok := eventUser["email"].(string); !ok { - t.Fatalf("expected email %s, but got nil", email) - } else { - assert.Equal(t, email, userEmail) - } + eventUser, ok := event.Data["user"].(map[string]interface{}) + require.True(t, ok, "expected user") + userEmail, ok := eventUser["email"].(string) + require.Truef(t, ok, "expected email %s, but got nil", email) + assert.Equal(t, email, userEmail) }) } @@ -1813,25 +1630,19 @@ func TestUpdateUserActive(t *testing.T) { pass, resp := th.Client.UpdateUserActive(user.Id, false) CheckNoError(t, resp) - if !pass { - t.Fatal("should have returned true") - } + require.True(t, pass) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableUserDeactivation = false }) pass, resp = th.Client.UpdateUserActive(user.Id, false) CheckUnauthorizedStatus(t, resp) - if pass { - t.Fatal("should have returned false") - } + require.False(t, pass) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.TeamSettings.EnableUserDeactivation = true }) pass, resp = th.Client.UpdateUserActive(user.Id, false) CheckUnauthorizedStatus(t, resp) - if pass { - t.Fatal("should have returned false") - } + require.False(t, pass) th.LoginBasic2() @@ -1878,9 +1689,8 @@ func TestUpdateUserActive(t *testing.T) { 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, model.STATUS_OK, resp.Status) adminWebSocketClient, err := th.CreateWebSocketSystemAdminClient() assert.Nil(t, err) @@ -1889,22 +1699,21 @@ func TestUpdateUserActive(t *testing.T) { adminWebSocketClient.Listen() time.Sleep(300 * time.Millisecond) - if resp := <-adminWebSocketClient.ResponseChannel; resp.Status != model.STATUS_OK { - t.Fatal("should have responded OK to authentication challenge") - } + resp = <-adminWebSocketClient.ResponseChannel + require.Equal(t, model.STATUS_OK, resp.Status) // Verify that both admins and regular users see the email when privacy settings allow same. th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PrivacySettings.ShowEmailAddress = true }) - _, resp := th.SystemAdminClient.UpdateUserActive(user.Id, false) - CheckNoError(t, resp) + _, respErr := th.SystemAdminClient.UpdateUserActive(user.Id, false) + CheckNoError(t, respErr) assertWebsocketEventUserUpdatedWithEmail(t, webSocketClient, user.Email) assertWebsocketEventUserUpdatedWithEmail(t, adminWebSocketClient, user.Email) // Verify that only admins see the email when privacy settings hide emails. th.App.UpdateConfig(func(cfg *model.Config) { *cfg.PrivacySettings.ShowEmailAddress = false }) - _, resp = th.SystemAdminClient.UpdateUserActive(user.Id, true) - CheckNoError(t, resp) + _, respErr = th.SystemAdminClient.UpdateUserActive(user.Id, true) + CheckNoError(t, respErr) assertWebsocketEventUserUpdatedWithEmail(t, webSocketClient, "") assertWebsocketEventUserUpdatedWithEmail(t, adminWebSocketClient, user.Email) @@ -1926,26 +1735,19 @@ func TestGetUsers(t *testing.T) { rusers, resp = th.Client.GetUsers(0, 1, "") CheckNoError(t, resp) - if len(rusers) != 1 { - t.Fatal("should be 1 per page") - } + require.Len(t, rusers, 1, "should be 1 per page") rusers, resp = th.Client.GetUsers(1, 1, "") CheckNoError(t, resp) - if len(rusers) != 1 { - t.Fatal("should be 1 per page") - } + require.Len(t, rusers, 1, "should be 1 per page") rusers, resp = th.Client.GetUsers(10000, 100, "") CheckNoError(t, resp) - if len(rusers) != 0 { - t.Fatal("should be no users") - } + require.Empty(t, rusers, "should be no users") // Check default params for page and per_page - if _, err := th.Client.DoApiGet("/users", ""); err != nil { - t.Fatal("should not have errored") - } + _, err := th.Client.DoApiGet("/users", "") + require.Nil(t, err) th.Client.Logout() _, resp = th.Client.GetUsers(0, 60, "") @@ -1962,18 +1764,14 @@ func TestGetNewUsersInTeam(t *testing.T) { lastCreateAt := model.GetMillis() for _, u := range rusers { - if u.CreateAt > lastCreateAt { - t.Fatal("bad sorting") - } + require.LessOrEqual(t, u.CreateAt, lastCreateAt, "right sorting") lastCreateAt = u.CreateAt CheckUserSanitization(t, u) } rusers, resp = th.Client.GetNewUsersInTeam(teamId, 1, 1, "") CheckNoError(t, resp) - if len(rusers) != 1 { - t.Fatal("should be 1 per page") - } + require.Len(t, rusers, 1, "should be 1 per page") th.Client.Logout() _, resp = th.Client.GetNewUsersInTeam(teamId, 1, 1, "") @@ -1991,17 +1789,13 @@ func TestGetRecentlyActiveUsersInTeam(t *testing.T) { CheckNoError(t, resp) for _, u := range rusers { - if u.LastActivityAt == 0 { - t.Fatal("did not return last activity at") - } + require.NotZero(t, u.LastActivityAt, "should return last activity at") CheckUserSanitization(t, u) } rusers, resp = th.Client.GetRecentlyActiveUsersInTeam(teamId, 0, 1, "") CheckNoError(t, resp) - if len(rusers) != 1 { - t.Fatal("should be 1 per page") - } + require.Len(t, rusers, 1, "should be 1 per page") th.Client.Logout() _, resp = th.Client.GetRecentlyActiveUsersInTeam(teamId, 0, 1, "") @@ -2012,9 +1806,8 @@ func TestGetUsersWithoutTeam(t *testing.T) { th := Setup().InitBasic() defer th.TearDown() - if _, resp := th.Client.GetUsersWithoutTeam(0, 100, ""); resp.Error == nil { - t.Fatal("should prevent non-admin user from getting users without a team") - } + _, resp := th.Client.GetUsersWithoutTeam(0, 100, "") + require.Error(t, resp.Error, "should prevent non-admin user from getting users without a team") // These usernames need to appear in the first 100 users for this to work @@ -2049,11 +1842,8 @@ func TestGetUsersWithoutTeam(t *testing.T) { } } - if found1 { - t.Fatal("shouldn't have returned user that has a team") - } else if !found2 { - t.Fatal("should've returned user that has no teams") - } + require.False(t, found1, "should not return user that as a team") + require.True(t, found2, "should return user that has no teams") } func TestGetUsersInTeam(t *testing.T) { @@ -2072,21 +1862,15 @@ func TestGetUsersInTeam(t *testing.T) { rusers, resp = th.Client.GetUsersInTeam(teamId, 0, 1, "") CheckNoError(t, resp) - if len(rusers) != 1 { - t.Fatal("should be 1 per page") - } + require.Len(t, rusers, 1, "should be 1 per page") rusers, resp = th.Client.GetUsersInTeam(teamId, 1, 1, "") CheckNoError(t, resp) - if len(rusers) != 1 { - t.Fatal("should be 1 per page") - } + require.Len(t, rusers, 1, "should be 1 per page") rusers, resp = th.Client.GetUsersInTeam(teamId, 10000, 100, "") CheckNoError(t, resp) - if len(rusers) != 0 { - t.Fatal("should be no users") - } + require.Empty(t, rusers, "should be no users") th.Client.Logout() _, resp = th.Client.GetUsersInTeam(teamId, 0, 60, "") @@ -2154,21 +1938,15 @@ func TestGetUsersInChannel(t *testing.T) { rusers, resp = th.Client.GetUsersInChannel(channelId, 0, 1, "") CheckNoError(t, resp) - if len(rusers) != 1 { - t.Fatal("should be 1 per page") - } + require.Len(t, rusers, 1, "should be 1 per page") rusers, resp = th.Client.GetUsersInChannel(channelId, 1, 1, "") CheckNoError(t, resp) - if len(rusers) != 1 { - t.Fatal("should be 1 per page") - } + require.Len(t, rusers, 1, "should be 1 per page") rusers, resp = th.Client.GetUsersInChannel(channelId, 10000, 100, "") CheckNoError(t, resp) - if len(rusers) != 0 { - t.Fatal("should be no users") - } + require.Len(t, rusers, 0, "should be no users") th.Client.Logout() _, resp = th.Client.GetUsersInChannel(channelId, 0, 60, "") @@ -2200,16 +1978,11 @@ func TestGetUsersNotInChannel(t *testing.T) { rusers, resp = th.Client.GetUsersNotInChannel(teamId, channelId, 0, 1, "") CheckNoError(t, resp) - if len(rusers) != 1 { - t.Log(len(rusers)) - t.Fatal("should be 1 per page") - } + require.Len(t, rusers, 1, "should be 1 per page") rusers, resp = th.Client.GetUsersNotInChannel(teamId, channelId, 10000, 100, "") CheckNoError(t, resp) - if len(rusers) != 0 { - t.Fatal("should be no users") - } + require.Len(t, rusers, 0, "should be no users") th.Client.Logout() _, resp = th.Client.GetUsersNotInChannel(teamId, channelId, 0, 60, "") @@ -2250,9 +2023,7 @@ func TestCheckUserMfa(t *testing.T) { required, resp := th.Client.CheckUserMfa(th.BasicUser.Email) CheckNoError(t, resp) - if required { - t.Fatal("should be false - mfa not active") - } + require.False(t, required, "mfa not active") _, resp = th.Client.CheckUserMfa("") CheckBadRequestStatus(t, resp) @@ -2262,9 +2033,7 @@ func TestCheckUserMfa(t *testing.T) { required, resp = th.Client.CheckUserMfa(th.BasicUser.Email) CheckNoError(t, resp) - if required { - t.Fatal("should be false - mfa not active") - } + require.False(t, required, "mfa not active") th.App.SetLicense(model.NewTestLicense("mfa")) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableMultifactorAuthentication = true }) @@ -2274,18 +2043,14 @@ func TestCheckUserMfa(t *testing.T) { required, resp = th.Client.CheckUserMfa(th.BasicUser.Email) CheckNoError(t, resp) - if required { - t.Fatal("should be false - mfa not active") - } + require.False(t, required, "mfa not active") th.Client.Logout() required, resp = th.Client.CheckUserMfa(th.BasicUser.Email) CheckNoError(t, resp) - if required { - t.Fatal("should be false - mfa not active") - } + require.False(t, required, "mfa not active") th.App.UpdateConfig(func(c *model.Config) { *c.ServiceSettings.DisableLegacyMFA = true @@ -2314,13 +2079,14 @@ func TestUserLoginMFAFlow(t *testing.T) { assert.Nil(t, err) // Fake user has MFA enabled - if err = th.Server.Store.User().UpdateMfaActive(th.BasicUser.Id, true); err != nil { - t.Fatal(err) - } + err = th.Server.Store.User().UpdateMfaActive(th.BasicUser.Id, true) + require.Nil(t, err) - if err = th.Server.Store.User().UpdateMfaSecret(th.BasicUser.Id, secret.Secret); err != nil { - t.Fatal(err) - } + err = th.Server.Store.User().UpdateMfaActive(th.BasicUser.Id, true) + require.Nil(t, err) + + err = th.Server.Store.User().UpdateMfaSecret(th.BasicUser.Id, secret.Secret) + require.Nil(t, err) user, resp := th.Client.Login(th.BasicUser.Email, th.BasicUser.Password) CheckErrorMessage(t, resp, "mfa.validate_token.authenticate.app_error") @@ -2346,13 +2112,11 @@ func TestUserLoginMFAFlow(t *testing.T) { assert.Nil(t, err) // Fake user has MFA enabled - if err = th.Server.Store.User().UpdateMfaActive(th.BasicUser.Id, true); err != nil { - t.Fatal(err) - } + err = th.Server.Store.User().UpdateMfaActive(th.BasicUser.Id, true) + require.Nil(t, err) - if err = th.Server.Store.User().UpdateMfaSecret(th.BasicUser.Id, secret.Secret); err != nil { - t.Fatal(err) - } + err = th.Server.Store.User().UpdateMfaSecret(th.BasicUser.Id, secret.Secret) + require.Nil(t, err) code := dgoogauth.ComputeCode(secret.Secret, time.Now().UTC().Unix()/30) @@ -2404,9 +2168,7 @@ func TestUpdateUserPassword(t *testing.T) { pass, resp := th.Client.UpdateUserPassword(th.BasicUser.Id, th.BasicUser.Password, password) CheckNoError(t, resp) - if !pass { - t.Fatal("should have returned true") - } + require.True(t, pass) _, resp = th.Client.UpdateUserPassword(th.BasicUser.Id, password, "") CheckBadRequestStatus(t, resp) @@ -2455,9 +2217,7 @@ func TestUpdateUserPassword(t *testing.T) { pass, resp = th.SystemAdminClient.UpdateUserPassword(th.BasicUser.Id, "", adminSetPassword) CheckNoError(t, resp) - if !pass { - t.Fatal("should have returned true") - } + require.True(t, pass) _, resp = th.Client.Login(th.BasicUser.Email, adminSetPassword) CheckNoError(t, resp) @@ -2474,17 +2234,13 @@ func TestResetPassword(t *testing.T) { mailservice.DeleteMailBox(user.Email) success, resp := th.Client.SendPasswordResetEmail(user.Email) CheckNoError(t, resp) - if !success { - t.Fatal("should have succeeded") - } + require.True(t, success, "should succeed") _, resp = th.Client.SendPasswordResetEmail("") CheckBadRequestStatus(t, resp) // Should not leak whether the email is attached to an account or not success, resp = th.Client.SendPasswordResetEmail("notreal@example.com") CheckNoError(t, resp) - if !success { - t.Fatal("should have succeeded") - } + require.True(t, success, "should succeed") // Check if the email was send to the right email address and the recovery key match var resultsMailbox mailservice.JSONMessageHeaderInbucket err := mailservice.RetryInbucket(5, func() error { @@ -2498,20 +2254,13 @@ func TestResetPassword(t *testing.T) { } var recoveryTokenString string if err == nil && len(resultsMailbox) > 0 { - if !strings.ContainsAny(resultsMailbox[0].To[0], user.Email) { - t.Fatal("Wrong To recipient") - } else { - var resultsEmail mailservice.JSONMessageInbucket - if resultsEmail, err = mailservice.GetMessageFromMailbox(user.Email, resultsMailbox[0].ID); err == nil { - loc := strings.Index(resultsEmail.Body.Text, "token=") - if loc == -1 { - t.Log(resultsEmail.Body.Text) - t.Fatal("Code not found in email") - } - loc += 6 - recoveryTokenString = resultsEmail.Body.Text[loc : loc+model.TOKEN_SIZE] - } - } + require.Contains(t, resultsMailbox[0].To[0], user.Email, "Correct To recipient") + resultsEmail, mailErr := mailservice.GetMessageFromMailbox(user.Email, resultsMailbox[0].ID) + require.NoError(t, mailErr) + loc := strings.Index(resultsEmail.Body.Text, "token=") + require.NotEqual(t, -1, loc, "Code should be found in email") + loc += 6 + recoveryTokenString = resultsEmail.Body.Text[loc : loc+model.TOKEN_SIZE] } recoveryToken, err := th.App.Srv.Store.Token().GetByToken(recoveryTokenString) require.Nil(t, err, "Recovery token not found (%s)", recoveryTokenString) @@ -2532,17 +2281,14 @@ func TestResetPassword(t *testing.T) { CheckBadRequestStatus(t, resp) success, resp = th.Client.ResetPassword(recoveryToken.Token, "newpwd") CheckNoError(t, resp) - if !success { - t.Fatal("should have succeeded") - } + require.True(t, success) th.Client.Login(user.Email, "newpwd") th.Client.Logout() _, resp = th.Client.ResetPassword(recoveryToken.Token, "newpwd") CheckBadRequestStatus(t, resp) authData := model.NewId() - if _, err := th.App.Srv.Store.User().UpdateAuthData(user.Id, "random", &authData, "", true); err != nil { - t.Fatal(err) - } + _, err = th.App.Srv.Store.User().UpdateAuthData(user.Id, "random", &authData, "", true) + require.Nil(t, err) _, resp = th.Client.SendPasswordResetEmail(user.Email) CheckBadRequestStatus(t, resp) } @@ -2557,9 +2303,7 @@ func TestGetSessions(t *testing.T) { sessions, resp := th.Client.GetSessions(user.Id, "") for _, session := range sessions { - if session.UserId != user.Id { - t.Fatal("user id does not match session user id") - } + require.Equal(t, user.Id, session.UserId, "user id should match session user id") } CheckNoError(t, resp) @@ -2593,13 +2337,9 @@ func TestRevokeSessions(t *testing.T) { user := th.BasicUser th.Client.Login(user.Email, user.Password) sessions, _ := th.Client.GetSessions(user.Id, "") - if len(sessions) == 0 { - t.Fatal("sessions should exist") - } + require.NotZero(t, len(sessions), "sessions should exist") for _, session := range sessions { - if session.UserId != user.Id { - t.Fatal("user id does not match session user id") - } + require.Equal(t, user.Id, session.UserId, "user id does not match session user id") } session := sessions[0] @@ -2613,9 +2353,7 @@ func TestRevokeSessions(t *testing.T) { CheckBadRequestStatus(t, resp) status, resp := th.Client.RevokeSession(user.Id, session.Id) - if !status { - t.Fatal("user session revoke unsuccessful") - } + require.True(t, status, "user session revoke successfuly") CheckNoError(t, resp) th.LoginBasic() @@ -2634,13 +2372,9 @@ func TestRevokeSessions(t *testing.T) { CheckBadRequestStatus(t, resp) sessions, _ = th.SystemAdminClient.GetSessions(th.SystemAdminUser.Id, "") - if len(sessions) == 0 { - t.Fatal("sessions should exist") - } + require.NotEmpty(t, sessions, "sessions should exist") for _, session := range sessions { - if session.UserId != th.SystemAdminUser.Id { - t.Fatal("user id does not match session user id") - } + require.Equal(t, th.SystemAdminUser.Id, session.UserId, "user id should match session user id") } session = sessions[0] @@ -2662,9 +2396,7 @@ func TestRevokeAllSessions(t *testing.T) { CheckBadRequestStatus(t, resp) status, resp := th.Client.RevokeAllSessions(user.Id) - if !status { - t.Fatal("user all sessions revoke unsuccessful") - } + require.True(t, status, "user all sessions revoke unsuccessful") CheckNoError(t, resp) th.Client.Logout() @@ -2674,17 +2406,13 @@ func TestRevokeAllSessions(t *testing.T) { th.Client.Login(user.Email, user.Password) sessions, _ := th.Client.GetSessions(user.Id, "") - if len(sessions) < 1 { - t.Fatal("session should exist") - } + require.NotEmpty(t, sessions, "session should exist") _, resp = th.Client.RevokeAllSessions(user.Id) CheckNoError(t, resp) sessions, _ = th.SystemAdminClient.GetSessions(user.Id, "") - if len(sessions) != 0 { - t.Fatal("no sessions should exist for user") - } + require.Empty(t, sessions, "no sessions should exist for user") _, resp = th.Client.RevokeAllSessions(user.Id) CheckUnauthorizedStatus(t, resp) @@ -2787,9 +2515,7 @@ func TestGetUserAudits(t *testing.T) { audits, resp := th.Client.GetUserAudits(user.Id, 0, 100, "") for _, audit := range audits { - if audit.UserId != user.Id { - t.Fatal("user id does not match audit user id") - } + require.Equal(t, user.Id, audit.UserId, "user id should match audit user id") } CheckNoError(t, resp) @@ -2814,9 +2540,7 @@ func TestVerifyUserEmail(t *testing.T) { ruser, _ := th.Client.CreateUser(&user) token, err := th.App.CreateVerifyEmailToken(ruser.Id, email) - if err != nil { - t.Fatal("Unable to create email verify token") - } + require.Nil(t, err, "Unable to create email verify token") _, resp := th.Client.VerifyUserEmail(token.Token) CheckNoError(t, resp) @@ -2835,9 +2559,7 @@ func TestSendVerificationEmail(t *testing.T) { pass, resp := th.Client.SendVerificationEmail(th.BasicUser.Email) CheckNoError(t, resp) - if !pass { - t.Fatal("should have passed") - } + require.True(t, pass, "should have passed") _, resp = th.Client.SendVerificationEmail("") CheckBadRequestStatus(t, resp) @@ -2857,20 +2579,14 @@ func TestSetProfileImage(t *testing.T) { user := th.BasicUser data, err := testutils.ReadTestFile("test.png") - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) ok, resp := th.Client.SetProfileImage(user.Id, data) - if !ok { - t.Fatal(resp.Error) - } + require.Truef(t, ok, "%v", resp.Error) CheckNoError(t, resp) ok, resp = th.Client.SetProfileImage(model.NewId(), data) - if ok { - t.Fatal("Should return false, set profile image not allowed") - } + require.False(t, ok, "Should return false, set profile image not allowed") CheckForbiddenStatus(t, resp) // status code returns either forbidden or unauthorized @@ -2896,9 +2612,8 @@ func TestSetProfileImage(t *testing.T) { assert.True(t, buser.LastPictureUpdate < ruser.LastPictureUpdate, "Picture should have updated for user") info := &model.FileInfo{Path: "users/" + user.Id + "/profile.png"} - if err := th.cleanupTestFile(info); err != nil { - t.Fatal(err) - } + err = th.cleanupTestFile(info) + require.Nil(t, err) } func TestSetDefaultProfileImage(t *testing.T) { @@ -2907,15 +2622,11 @@ func TestSetDefaultProfileImage(t *testing.T) { user := th.BasicUser ok, resp := th.Client.SetDefaultProfileImage(user.Id) - if !ok { - t.Fatal(resp.Error) - } + require.True(t, ok) CheckNoError(t, resp) ok, resp = th.Client.SetDefaultProfileImage(model.NewId()) - if ok { - t.Fatal("Should return false, set profile image not allowed") - } + require.False(t, ok, "Should return false, set profile image not allowed") CheckForbiddenStatus(t, resp) // status code returns either forbidden or unauthorized @@ -2938,9 +2649,8 @@ func TestSetDefaultProfileImage(t *testing.T) { assert.Equal(t, int64(0), ruser.LastPictureUpdate, "Picture should have resetted to default") info := &model.FileInfo{Path: "users/" + user.Id + "/profile.png"} - if err := th.cleanupTestFile(info); err != nil { - t.Fatal(err) - } + cleanupErr := th.cleanupTestFile(info) + require.Nil(t, cleanupErr) } func TestLogin(t *testing.T) { @@ -2987,9 +2697,7 @@ func TestLogin(t *testing.T) { t.Run("login with terms_of_service set", func(t *testing.T) { termsOfService, err := th.App.CreateTermsOfService("terms of service", th.BasicUser.Id) - if err != nil { - t.Fatal(err) - } + require.Nil(t, err) success, resp := th.Client.RegisterTermsOfServiceAction(th.BasicUser.Id, termsOfService.Id, true) CheckNoError(t, resp) @@ -3205,9 +2913,7 @@ func TestSwitchAccount(t *testing.T) { link, resp := th.Client.SwitchAccountType(sr) CheckNoError(t, resp) - if link == "" { - t.Fatal("bad link") - } + require.NotEmpty(t, link, "bad link") th.App.SetLicense(model.NewTestLicense()) th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.ExperimentalEnableAuthenticationTransfer = false }) @@ -3253,9 +2959,8 @@ func TestSwitchAccount(t *testing.T) { th.LoginBasic() fakeAuthData := model.NewId() - if _, err := th.App.Srv.Store.User().UpdateAuthData(th.BasicUser.Id, model.USER_AUTH_SERVICE_GITLAB, &fakeAuthData, th.BasicUser.Email, true); err != nil { - t.Fatal(err) - } + _, err := th.App.Srv.Store.User().UpdateAuthData(th.BasicUser.Id, model.USER_AUTH_SERVICE_GITLAB, &fakeAuthData, th.BasicUser.Email, true) + require.Nil(t, err) sr = &model.SwitchRequest{ CurrentService: model.USER_AUTH_SERVICE_GITLAB, @@ -3267,10 +2972,7 @@ func TestSwitchAccount(t *testing.T) { link, resp = th.Client.SwitchAccountType(sr) CheckNoError(t, resp) - if link != "/login?extra=signin_change" { - t.Log(link) - t.Fatal("bad link") - } + require.Equal(t, "/login?extra=signin_change", link) th.Client.Logout() _, resp = th.Client.Login(th.BasicUser.Email, th.BasicUser.Password) @@ -3812,30 +3514,22 @@ func TestSearchUserAccessToken(t *testing.T) { rtokens, resp := th.SystemAdminClient.SearchUserAccessTokens(&model.UserAccessTokenSearch{Term: th.BasicUser.Id}) CheckNoError(t, resp) - if len(rtokens) != 1 { - t.Fatal("should have 1 tokens") - } + require.Len(t, rtokens, 1, "should have 1 token") rtokens, resp = th.SystemAdminClient.SearchUserAccessTokens(&model.UserAccessTokenSearch{Term: token.Id}) CheckNoError(t, resp) - if len(rtokens) != 1 { - t.Fatal("should have 1 tokens") - } + require.Len(t, rtokens, 1, "should have 1 token") rtokens, resp = th.SystemAdminClient.SearchUserAccessTokens(&model.UserAccessTokenSearch{Term: th.BasicUser.Username}) CheckNoError(t, resp) - if len(rtokens) != 1 { - t.Fatal("should have 1 tokens") - } + require.Len(t, rtokens, 1, "should have 1 token") rtokens, resp = th.SystemAdminClient.SearchUserAccessTokens(&model.UserAccessTokenSearch{Term: "not found"}) CheckNoError(t, resp) - if len(rtokens) != 0 { - t.Fatal("should have 0 tokens") - } + require.Len(t, rtokens, 0, "should have 1 tokens") } func TestRevokeUserAccessToken(t *testing.T) { @@ -4293,9 +3987,8 @@ func TestGetUsersByStatus(t *testing.T) { Email: th.GenerateTestEmail(), Type: model.TEAM_OPEN, }) - if err != nil { - t.Fatalf("failed to create team: %v", err) - } + + require.Nil(t, err, "failed to create team") channel, err := th.App.CreateChannel(&model.Channel{ DisplayName: "dn_" + model.NewId(), @@ -4304,9 +3997,7 @@ func TestGetUsersByStatus(t *testing.T) { TeamId: team.Id, CreatorId: model.NewId(), }, false) - if err != nil { - t.Fatalf("failed to create channel: %v", err) - } + require.Nil(t, err, "failed to create channel") createUserWithStatus := func(username string, status string) *model.User { id := model.NewId() @@ -4317,9 +4008,7 @@ func TestGetUsersByStatus(t *testing.T) { Nickname: "nn_" + id, Password: "Password1", }) - if err != nil { - t.Fatalf("failed to create user: %v", err) - } + require.Nil(t, err, "failed to create user") th.LinkUserToTeam(user, team) th.AddUserToChannel(user, channel) @@ -4344,15 +4033,12 @@ func TestGetUsersByStatus(t *testing.T) { dndUser2 := createUserWithStatus("dnd2", model.STATUS_DND) client := th.CreateClient() - if _, resp := client.Login(onlineUser2.Username, "Password1"); resp.Error != nil { - t.Fatal(resp.Error) - } + _, resp := client.Login(onlineUser2.Username, "Password1") + require.Nil(t, resp.Error) t.Run("sorting by status then alphabetical", func(t *testing.T) { usersByStatus, resp := client.GetUsersInChannelByStatus(channel.Id, 0, 8, "") - if resp.Error != nil { - t.Fatal(resp.Error) - } + require.Nil(t, resp.Error) expectedUsersByStatus := []*model.User{ onlineUser1, @@ -4364,65 +4050,37 @@ func TestGetUsersByStatus(t *testing.T) { offlineUser1, offlineUser2, } - - if len(usersByStatus) != len(expectedUsersByStatus) { - t.Fatalf("received only %v users, expected %v", len(usersByStatus), len(expectedUsersByStatus)) - } + require.Equal(t, len(expectedUsersByStatus), len(usersByStatus)) for i := range usersByStatus { - if usersByStatus[i].Id != expectedUsersByStatus[i].Id { - t.Fatalf("received user %v at index %v, expected %v", usersByStatus[i].Username, i, expectedUsersByStatus[i].Username) - } + require.Equal(t, expectedUsersByStatus[i].Id, usersByStatus[i].Id) } }) t.Run("paging", func(t *testing.T) { usersByStatus, resp := client.GetUsersInChannelByStatus(channel.Id, 0, 3, "") - if resp.Error != nil { - t.Fatal(resp.Error) - } - - if len(usersByStatus) != 3 { - t.Fatal("received too many users") - } - - if usersByStatus[0].Id != onlineUser1.Id && usersByStatus[1].Id != onlineUser2.Id { - t.Fatal("expected to receive online users first") - } - - if usersByStatus[2].Id != awayUser1.Id { - t.Fatal("expected to receive away users second") - } + require.Nil(t, resp.Error) + require.Len(t, usersByStatus, 3) + require.Equal(t, onlineUser1.Id, usersByStatus[0].Id, "online users first") + require.Equal(t, onlineUser2.Id, usersByStatus[1].Id, "online users first") + require.Equal(t, awayUser1.Id, usersByStatus[2].Id, "expected to receive away users second") usersByStatus, resp = client.GetUsersInChannelByStatus(channel.Id, 1, 3, "") - if resp.Error != nil { - t.Fatal(resp.Error) - } + require.Nil(t, resp.Error) - if usersByStatus[0].Id != awayUser2.Id { - t.Fatal("expected to receive away users second") - } - - if usersByStatus[1].Id != dndUser1.Id && usersByStatus[2].Id != dndUser2.Id { - t.Fatal("expected to receive dnd users third") - } + require.Equal(t, awayUser2.Id, usersByStatus[0].Id, "expected to receive away users second") + require.Equal(t, dndUser1.Id, usersByStatus[1].Id, "expected to receive dnd users third") + require.Equal(t, dndUser2.Id, usersByStatus[2].Id, "expected to receive dnd users third") usersByStatus, resp = client.GetUsersInChannelByStatus(channel.Id, 1, 4, "") - if resp.Error != nil { - t.Fatal(resp.Error) - } + require.Nil(t, resp.Error) - if len(usersByStatus) != 4 { - t.Fatal("received too many users") - } + require.Len(t, usersByStatus, 4) + require.Equal(t, dndUser1.Id, usersByStatus[0].Id, "expected to receive dnd users third") + require.Equal(t, dndUser2.Id, usersByStatus[1].Id, "expected to receive dnd users third") - if usersByStatus[0].Id != dndUser1.Id && usersByStatus[1].Id != dndUser2.Id { - t.Fatal("expected to receive dnd users third") - } - - if usersByStatus[2].Id != offlineUser1.Id && usersByStatus[3].Id != offlineUser2.Id { - t.Fatal("expected to receive offline users last") - } + require.Equal(t, offlineUser1.Id, usersByStatus[2].Id, "expected to receive offline users last") + require.Equal(t, offlineUser2.Id, usersByStatus[3].Id, "expected to receive offline users last") }) } @@ -4435,18 +4093,14 @@ func TestRegisterTermsOfServiceAction(t *testing.T) { assert.Nil(t, success) termsOfService, err := th.App.CreateTermsOfService("terms of service", th.BasicUser.Id) - if err != nil { - t.Fatal(err) - } + require.Nil(t, err) success, resp = th.Client.RegisterTermsOfServiceAction(th.BasicUser.Id, termsOfService.Id, true) CheckNoError(t, resp) assert.True(t, *success) _, err = th.App.GetUser(th.BasicUser.Id) - if err != nil { - t.Fatal(err) - } + require.Nil(t, err) } func TestGetUserTermsOfService(t *testing.T) { @@ -4457,9 +4111,7 @@ func TestGetUserTermsOfService(t *testing.T) { CheckErrorMessage(t, resp, "store.sql_user_terms_of_service.get_by_user.no_rows.app_error") termsOfService, err := th.App.CreateTermsOfService("terms of service", th.BasicUser.Id) - if err != nil { - t.Fatal(err) - } + require.Nil(t, err) success, resp := th.Client.RegisterTermsOfServiceAction(th.BasicUser.Id, termsOfService.Id, true) CheckNoError(t, resp) @@ -4553,9 +4205,8 @@ func TestLoginLockout(t *testing.T) { CheckErrorMessage(t, resp, "api.user.check_user_login_attempts.too_many.app_error") // Fake user has MFA enabled - if err := th.Server.Store.User().UpdateMfaActive(th.BasicUser2.Id, true); err != nil { - t.Fatal(err) - } + err := th.Server.Store.User().UpdateMfaActive(th.BasicUser2.Id, true) + require.Nil(t, err) _, resp = th.Client.LoginWithMFA(th.BasicUser2.Email, th.BasicUser2.Password, "000000") CheckErrorMessage(t, resp, "api.user.check_user_mfa.bad_code.app_error") _, resp = th.Client.LoginWithMFA(th.BasicUser2.Email, th.BasicUser2.Password, "000000") @@ -4568,9 +4219,8 @@ func TestLoginLockout(t *testing.T) { CheckErrorMessage(t, resp, "api.user.check_user_login_attempts.too_many.app_error") // Fake user has MFA disabled - if err := th.Server.Store.User().UpdateMfaActive(th.BasicUser2.Id, false); err != nil { - t.Fatal(err) - } + err = th.Server.Store.User().UpdateMfaActive(th.BasicUser2.Id, false) + require.Nil(t, err) //Check if lock is active _, resp = th.Client.Login(th.BasicUser2.Email, th.BasicUser2.Password)