github.com/mattermosttest/mattermost-server/v5@v5.0.0-20200917143240-9dfa12e121f9/store/searchtest/helper.go (about)

     1  // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
     2  // See LICENSE.txt for license information.
     3  
     4  package searchtest
     5  
     6  import (
     7  	"fmt"
     8  	"testing"
     9  
    10  	"github.com/mattermost/mattermost-server/v5/model"
    11  	"github.com/mattermost/mattermost-server/v5/store"
    12  	"github.com/pkg/errors"
    13  
    14  	"github.com/stretchr/testify/assert"
    15  	"github.com/stretchr/testify/require"
    16  )
    17  
    18  type SearchTestHelper struct {
    19  	Store              store.Store
    20  	Team               *model.Team
    21  	AnotherTeam        *model.Team
    22  	User               *model.User
    23  	User2              *model.User
    24  	UserAnotherTeam    *model.User
    25  	ChannelBasic       *model.Channel
    26  	ChannelPrivate     *model.Channel
    27  	ChannelAnotherTeam *model.Channel
    28  	ChannelDeleted     *model.Channel
    29  }
    30  
    31  func (th *SearchTestHelper) SetupBasicFixtures() error {
    32  	// Remove users from previous tests
    33  	err := th.cleanAllUsers()
    34  	if err != nil {
    35  		return err
    36  	}
    37  
    38  	// Create teams
    39  	team, err := th.createTeam("searchtest-team", "Searchtest team", model.TEAM_OPEN)
    40  	if err != nil {
    41  		return err
    42  	}
    43  	anotherTeam, err := th.createTeam("another-searchtest-team", "Another Searchtest team", model.TEAM_OPEN)
    44  	if err != nil {
    45  		return err
    46  	}
    47  
    48  	// Create users
    49  	user, err := th.createUser("basicusername1", "basicnickname1", "basicfirstname1", "basiclastname1")
    50  	if err != nil {
    51  		return err
    52  	}
    53  	user2, err := th.createUser("basicusername2", "basicnickname2", "basicfirstname2", "basiclastname2")
    54  	if err != nil {
    55  		return err
    56  	}
    57  	useranother, err := th.createUser("basicusername3", "basicnickname3", "basicfirstname3", "basiclastname3")
    58  	if err != nil {
    59  		return err
    60  	}
    61  
    62  	// Create channels
    63  	channelBasic, err := th.createChannel(team.Id, "channel-a", "ChannelA", "", model.CHANNEL_OPEN, false)
    64  	if err != nil {
    65  		return err
    66  	}
    67  	channelPrivate, err := th.createChannel(team.Id, "channel-private", "ChannelPrivate", "", model.CHANNEL_PRIVATE, false)
    68  	if err != nil {
    69  		return err
    70  	}
    71  	channelDeleted, err := th.createChannel(team.Id, "channel-deleted", "ChannelA (deleted)", "", model.CHANNEL_OPEN, true)
    72  	if err != nil {
    73  		return err
    74  	}
    75  	channelAnotherTeam, err := th.createChannel(anotherTeam.Id, "channel-a", "ChannelA", "", model.CHANNEL_OPEN, false)
    76  	if err != nil {
    77  		return err
    78  	}
    79  
    80  	err = th.addUserToTeams(user, []string{team.Id, anotherTeam.Id})
    81  	if err != nil {
    82  		return err
    83  	}
    84  
    85  	err = th.addUserToTeams(user2, []string{team.Id, anotherTeam.Id})
    86  	if err != nil {
    87  		return err
    88  	}
    89  
    90  	err = th.addUserToTeams(useranother, []string{anotherTeam.Id})
    91  	if err != nil {
    92  		return err
    93  	}
    94  
    95  	_, err = th.addUserToChannels(user, []string{channelBasic.Id, channelPrivate.Id, channelDeleted.Id})
    96  	if err != nil {
    97  		return err
    98  	}
    99  
   100  	_, err = th.addUserToChannels(user2, []string{channelPrivate.Id, channelDeleted.Id})
   101  	if err != nil {
   102  		return err
   103  	}
   104  
   105  	_, err = th.addUserToChannels(useranother, []string{channelAnotherTeam.Id})
   106  	if err != nil {
   107  		return err
   108  	}
   109  
   110  	th.Team = team
   111  	th.AnotherTeam = anotherTeam
   112  	th.User = user
   113  	th.User2 = user2
   114  	th.UserAnotherTeam = useranother
   115  	th.ChannelBasic = channelBasic
   116  	th.ChannelPrivate = channelPrivate
   117  	th.ChannelAnotherTeam = channelAnotherTeam
   118  	th.ChannelDeleted = channelDeleted
   119  
   120  	return nil
   121  }
   122  
   123  func (th *SearchTestHelper) CleanFixtures() error {
   124  	err := th.deleteChannels([]*model.Channel{
   125  		th.ChannelBasic, th.ChannelPrivate, th.ChannelAnotherTeam, th.ChannelDeleted,
   126  	})
   127  	if err != nil {
   128  		return err
   129  	}
   130  
   131  	err = th.deleteTeam(th.Team)
   132  	if err != nil {
   133  		return err
   134  	}
   135  
   136  	err = th.deleteTeam(th.AnotherTeam)
   137  	if err != nil {
   138  		return err
   139  	}
   140  
   141  	err = th.cleanAllUsers()
   142  	if err != nil {
   143  		return err
   144  	}
   145  
   146  	return nil
   147  }
   148  
   149  func (th *SearchTestHelper) createTeam(name, displayName, teamType string) (*model.Team, error) {
   150  	team, appError := th.Store.Team().Save(&model.Team{
   151  		Name:        name,
   152  		DisplayName: displayName,
   153  		Type:        teamType,
   154  	})
   155  	if appError != nil {
   156  		return nil, errors.New(appError.Error())
   157  	}
   158  
   159  	return team, nil
   160  }
   161  
   162  func (th *SearchTestHelper) deleteTeam(team *model.Team) error {
   163  	appError := th.Store.Team().RemoveAllMembersByTeam(team.Id)
   164  	if appError != nil {
   165  		return errors.New(appError.Error())
   166  	}
   167  	appError = th.Store.Team().PermanentDelete(team.Id)
   168  	if appError != nil {
   169  		return errors.New(appError.Error())
   170  	}
   171  
   172  	return nil
   173  }
   174  
   175  func (th *SearchTestHelper) makeEmail() string {
   176  	return "success_" + model.NewId() + "@simulator.amazon.com"
   177  }
   178  
   179  func (th *SearchTestHelper) createUser(username, nickname, firstName, lastName string) (*model.User, error) {
   180  	user, appError := th.Store.User().Save(&model.User{
   181  		Username:  username,
   182  		Password:  username,
   183  		Nickname:  nickname,
   184  		FirstName: firstName,
   185  		LastName:  lastName,
   186  		Email:     th.makeEmail(),
   187  	})
   188  	if appError != nil {
   189  		return nil, errors.New(appError.Error())
   190  	}
   191  
   192  	return user, nil
   193  }
   194  
   195  func (th *SearchTestHelper) createGuest(username, nickname, firstName, lastName string) (*model.User, error) {
   196  	user, appError := th.Store.User().Save(&model.User{
   197  		Username:  username,
   198  		Password:  username,
   199  		Nickname:  nickname,
   200  		FirstName: firstName,
   201  		LastName:  lastName,
   202  		Email:     th.makeEmail(),
   203  		Roles:     model.SYSTEM_GUEST_ROLE_ID,
   204  	})
   205  	if appError != nil {
   206  		return nil, errors.New(appError.Error())
   207  	}
   208  
   209  	return user, nil
   210  }
   211  
   212  func (th *SearchTestHelper) deleteUser(user *model.User) error {
   213  	appError := th.Store.User().PermanentDelete(user.Id)
   214  	if appError != nil {
   215  		return errors.New(appError.Error())
   216  	}
   217  
   218  	return nil
   219  }
   220  
   221  func (th *SearchTestHelper) cleanAllUsers() error {
   222  	users, apperr := th.Store.User().GetAll()
   223  	if apperr != nil {
   224  		return apperr
   225  	}
   226  
   227  	for _, u := range users {
   228  		err := th.deleteUser(u)
   229  		if err != nil {
   230  			return err
   231  		}
   232  	}
   233  
   234  	return nil
   235  }
   236  
   237  func (th *SearchTestHelper) createBot(username, displayName, ownerID string) (*model.Bot, error) {
   238  	botModel := &model.Bot{
   239  		Username:    username,
   240  		DisplayName: displayName,
   241  		OwnerId:     ownerID,
   242  	}
   243  
   244  	user, apperr := th.Store.User().Save(model.UserFromBot(botModel))
   245  	if apperr != nil {
   246  		return nil, errors.New(apperr.Error())
   247  	}
   248  
   249  	botModel.UserId = user.Id
   250  	bot, err := th.Store.Bot().Save(botModel)
   251  	if err != nil {
   252  		th.Store.User().PermanentDelete(bot.UserId)
   253  		return nil, errors.New(err.Error())
   254  	}
   255  
   256  	return bot, nil
   257  }
   258  
   259  func (th *SearchTestHelper) deleteBot(botID string) error {
   260  	err := th.Store.Bot().PermanentDelete(botID)
   261  	if err != nil {
   262  		return errors.New(err.Error())
   263  	}
   264  	return nil
   265  }
   266  
   267  func (th *SearchTestHelper) createChannel(teamID, name, displayName, purpose, channelType string, deleted bool) (*model.Channel, error) {
   268  	channel, appError := th.Store.Channel().Save(&model.Channel{
   269  		TeamId:      teamID,
   270  		DisplayName: displayName,
   271  		Name:        name,
   272  		Type:        channelType,
   273  		Purpose:     purpose,
   274  	}, 999)
   275  	if appError != nil {
   276  		return nil, errors.New(appError.Error())
   277  	}
   278  
   279  	if deleted {
   280  		appError := th.Store.Channel().Delete(channel.Id, model.GetMillis())
   281  		if appError != nil {
   282  			return nil, errors.New(appError.Error())
   283  		}
   284  	}
   285  
   286  	return channel, nil
   287  }
   288  
   289  func (th *SearchTestHelper) createDirectChannel(teamID, name, displayName string, users []*model.User) (*model.Channel, error) {
   290  	channel := &model.Channel{
   291  		TeamId:      teamID,
   292  		Name:        name,
   293  		DisplayName: displayName,
   294  		Type:        model.CHANNEL_DIRECT,
   295  	}
   296  
   297  	m1 := &model.ChannelMember{}
   298  	m1.ChannelId = channel.Id
   299  	m1.UserId = users[0].Id
   300  	m1.NotifyProps = model.GetDefaultChannelNotifyProps()
   301  
   302  	m2 := &model.ChannelMember{}
   303  	m2.ChannelId = channel.Id
   304  	m2.UserId = users[0].Id
   305  	m2.NotifyProps = model.GetDefaultChannelNotifyProps()
   306  
   307  	channel, err := th.Store.Channel().SaveDirectChannel(channel, m1, m2)
   308  	if err != nil {
   309  		return nil, err
   310  	}
   311  	return channel, nil
   312  }
   313  
   314  func (th *SearchTestHelper) createGroupChannel(teamID, displayName string, users []*model.User) (*model.Channel, error) {
   315  	userIDS := make([]string, len(users))
   316  	for _, user := range users {
   317  		userIDS = append(userIDS, user.Id)
   318  	}
   319  
   320  	group := &model.Channel{
   321  		TeamId:      teamID,
   322  		Name:        model.GetGroupNameFromUserIds(userIDS),
   323  		DisplayName: displayName,
   324  		Type:        model.CHANNEL_GROUP,
   325  	}
   326  
   327  	channel, apperr := th.Store.Channel().Save(group, 10000)
   328  	if apperr != nil {
   329  		return nil, errors.New(apperr.Error())
   330  	}
   331  
   332  	for _, user := range users {
   333  		_, err := th.addUserToChannels(user, []string{channel.Id})
   334  		if err != nil {
   335  			return nil, err
   336  		}
   337  	}
   338  
   339  	return channel, nil
   340  
   341  }
   342  
   343  func (th *SearchTestHelper) deleteChannel(channel *model.Channel) error {
   344  	appError := th.Store.Channel().PermanentDeleteMembersByChannel(channel.Id)
   345  	if appError != nil {
   346  		return errors.New(appError.Error())
   347  	}
   348  
   349  	err := th.Store.Channel().PermanentDelete(channel.Id)
   350  	if err != nil {
   351  		return err
   352  	}
   353  
   354  	return nil
   355  }
   356  
   357  func (th *SearchTestHelper) deleteChannels(channels []*model.Channel) error {
   358  	for _, channel := range channels {
   359  		err := th.deleteChannel(channel)
   360  		if err != nil {
   361  			return err
   362  		}
   363  	}
   364  
   365  	return nil
   366  }
   367  
   368  func (th *SearchTestHelper) createPostModel(userID, channelID, message, hashtags, postType string, createAt int64, pinned bool) *model.Post {
   369  	return &model.Post{
   370  		Message:       message,
   371  		ChannelId:     channelID,
   372  		PendingPostId: model.NewId() + ":" + fmt.Sprint(model.GetMillis()),
   373  		UserId:        userID,
   374  		Hashtags:      hashtags,
   375  		IsPinned:      pinned,
   376  		CreateAt:      createAt,
   377  		Type:          postType,
   378  	}
   379  }
   380  
   381  func (th *SearchTestHelper) createPost(userID, channelID, message, hashtags, postType string, createAt int64, pinned bool) (*model.Post, error) {
   382  	var creationTime int64 = 1000000
   383  	if createAt > 0 {
   384  		creationTime = createAt
   385  	}
   386  	postModel := th.createPostModel(userID, channelID, message, hashtags, postType, creationTime, pinned)
   387  	post, appError := th.Store.Post().Save(postModel)
   388  	if appError != nil {
   389  		return nil, errors.New(appError.Error())
   390  	}
   391  
   392  	return post, nil
   393  }
   394  
   395  func (th *SearchTestHelper) createReply(userID, message, hashtags string, parent *model.Post, createAt int64, pinned bool) (*model.Post, error) {
   396  	replyModel := th.createPostModel(userID, parent.ChannelId, message, hashtags, parent.Type, createAt, pinned)
   397  	replyModel.ParentId = parent.Id
   398  	replyModel.RootId = parent.Id
   399  	reply, appError := th.Store.Post().Save(replyModel)
   400  	if appError != nil {
   401  		return nil, errors.New(appError.Error())
   402  	}
   403  	return reply, nil
   404  }
   405  
   406  func (th *SearchTestHelper) deleteUserPosts(userID string) error {
   407  	err := th.Store.Post().PermanentDeleteByUser(userID)
   408  	if err != nil {
   409  		return errors.New(err.Error())
   410  	}
   411  	return nil
   412  }
   413  
   414  func (th *SearchTestHelper) addUserToTeams(user *model.User, teamIDS []string) error {
   415  	for _, teamID := range teamIDS {
   416  		_, err := th.Store.Team().SaveMember(&model.TeamMember{TeamId: teamID, UserId: user.Id}, -1)
   417  		if err != nil {
   418  			return errors.New(err.Error())
   419  		}
   420  	}
   421  
   422  	return nil
   423  }
   424  
   425  func (th *SearchTestHelper) addUserToChannels(user *model.User, channelIDS []string) ([]*model.ChannelMember, error) {
   426  
   427  	channelMembers := make([]*model.ChannelMember, len(channelIDS))
   428  	for _, channelID := range channelIDS {
   429  		cm, err := th.Store.Channel().SaveMember(&model.ChannelMember{
   430  			ChannelId:   channelID,
   431  			UserId:      user.Id,
   432  			NotifyProps: model.GetDefaultChannelNotifyProps(),
   433  		})
   434  		if err != nil {
   435  			return nil, errors.New(err.Error())
   436  		}
   437  		channelMembers = append(channelMembers, cm)
   438  	}
   439  
   440  	return channelMembers, nil
   441  }
   442  
   443  func (th *SearchTestHelper) assertUsersMatchInAnyOrder(t *testing.T, expected, actual []*model.User) {
   444  	expectedUsernames := make([]string, 0, len(expected))
   445  	for _, user := range expected {
   446  		user.Sanitize(map[string]bool{})
   447  		expectedUsernames = append(expectedUsernames, user.Username)
   448  	}
   449  
   450  	actualUsernames := make([]string, 0, len(actual))
   451  	for _, user := range actual {
   452  		user.Sanitize(map[string]bool{})
   453  		actualUsernames = append(actualUsernames, user.Username)
   454  	}
   455  
   456  	if assert.ElementsMatch(t, expectedUsernames, actualUsernames) {
   457  		assert.ElementsMatch(t, expected, actual)
   458  	}
   459  }
   460  
   461  func (th *SearchTestHelper) checkPostInSearchResults(t *testing.T, postID string, searchResults map[string]*model.Post) {
   462  	t.Helper()
   463  	postIDS := make([]string, len(searchResults))
   464  	for ID := range searchResults {
   465  		postIDS = append(postIDS, ID)
   466  	}
   467  	assert.Contains(t, postIDS, postID, "Did not find expected post in search results.")
   468  }
   469  
   470  func (th *SearchTestHelper) checkChannelIdsMatch(t *testing.T, expected []string, results *model.ChannelList) {
   471  	t.Helper()
   472  	channelIds := make([]string, len(*results))
   473  	for i, channel := range *results {
   474  		channelIds[i] = channel.Id
   475  	}
   476  	require.ElementsMatch(t, expected, channelIds)
   477  }
   478  
   479  type ByChannelDisplayName model.ChannelList
   480  
   481  func (s ByChannelDisplayName) Len() int { return len(s) }
   482  func (s ByChannelDisplayName) Swap(i, j int) {
   483  	s[i], s[j] = s[j], s[i]
   484  }
   485  func (s ByChannelDisplayName) Less(i, j int) bool {
   486  	if s[i].DisplayName != s[j].DisplayName {
   487  		return s[i].DisplayName < s[j].DisplayName
   488  	}
   489  
   490  	return s[i].Id < s[j].Id
   491  }