github.com/crspeller/mattermost-server@v0.0.0-20190328001957-a200beb3d111/app/import_test.go (about)

     1  // Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
     2  // See License.txt for license information.
     3  
     4  package app
     5  
     6  import (
     7  	"path/filepath"
     8  	"runtime/debug"
     9  	"strings"
    10  	"testing"
    11  
    12  	"github.com/stretchr/testify/assert"
    13  
    14  	"github.com/crspeller/mattermost-server/model"
    15  	"github.com/crspeller/mattermost-server/utils/fileutils"
    16  )
    17  
    18  func ptrStr(s string) *string {
    19  	return &s
    20  }
    21  
    22  func ptrInt64(i int64) *int64 {
    23  	return &i
    24  }
    25  
    26  func ptrInt(i int) *int {
    27  	return &i
    28  }
    29  
    30  func ptrBool(b bool) *bool {
    31  	return &b
    32  }
    33  
    34  func checkPreference(t *testing.T, a *App, userId string, category string, name string, value string) {
    35  	if res := <-a.Srv.Store.Preference().GetCategory(userId, category); res.Err != nil {
    36  		debug.PrintStack()
    37  		t.Fatalf("Failed to get preferences for user %v with category %v", userId, category)
    38  	} else {
    39  		preferences := res.Data.(model.Preferences)
    40  		found := false
    41  		for _, preference := range preferences {
    42  			if preference.Name == name {
    43  				found = true
    44  				if preference.Value != value {
    45  					debug.PrintStack()
    46  					t.Fatalf("Preference for user %v in category %v with name %v has value %v, expected %v", userId, category, name, preference.Value, value)
    47  				}
    48  				break
    49  			}
    50  		}
    51  		if !found {
    52  			debug.PrintStack()
    53  			t.Fatalf("Did not find preference for user %v in category %v with name %v", userId, category, name)
    54  		}
    55  	}
    56  }
    57  
    58  func checkNotifyProp(t *testing.T, user *model.User, key string, value string) {
    59  	if actual, ok := user.NotifyProps[key]; !ok {
    60  		debug.PrintStack()
    61  		t.Fatalf("Notify prop %v not found. User: %v", key, user.Id)
    62  	} else if actual != value {
    63  		debug.PrintStack()
    64  		t.Fatalf("Notify Prop %v was %v but expected %v. User: %v", key, actual, value, user.Id)
    65  	}
    66  }
    67  
    68  func checkError(t *testing.T, err *model.AppError) {
    69  	if err == nil {
    70  		debug.PrintStack()
    71  		t.Fatal("Should have returned an error.")
    72  	}
    73  }
    74  
    75  func checkNoError(t *testing.T, err *model.AppError) {
    76  	if err != nil {
    77  		debug.PrintStack()
    78  		t.Fatalf("Unexpected Error: %v", err.Error())
    79  	}
    80  }
    81  
    82  func AssertAllPostsCount(t *testing.T, a *App, initialCount int64, change int64, teamName string) {
    83  	if result := <-a.Srv.Store.Post().AnalyticsPostCount(teamName, false, false); result.Err != nil {
    84  		t.Fatal(result.Err)
    85  	} else {
    86  		if initialCount+change != result.Data.(int64) {
    87  			debug.PrintStack()
    88  			t.Fatalf("Did not find the expected number of posts.")
    89  		}
    90  	}
    91  }
    92  
    93  func AssertChannelCount(t *testing.T, a *App, channelType string, expectedCount int64) {
    94  	if r := <-a.Srv.Store.Channel().AnalyticsTypeCount("", channelType); r.Err == nil {
    95  		count := r.Data.(int64)
    96  		if count != expectedCount {
    97  			debug.PrintStack()
    98  			t.Fatalf("Channel count of type: %v. Expected: %v, Got: %v", channelType, expectedCount, count)
    99  		}
   100  	} else {
   101  		debug.PrintStack()
   102  		t.Fatalf("Failed to get channel count.")
   103  	}
   104  }
   105  
   106  func TestImportImportLine(t *testing.T) {
   107  	th := Setup(t)
   108  	defer th.TearDown()
   109  
   110  	// Try import line with an invalid type.
   111  	line := LineImportData{
   112  		Type: "gibberish",
   113  	}
   114  
   115  	if err := th.App.ImportLine(line, false); err == nil {
   116  		t.Fatalf("Expected an error when importing a line with invalid type.")
   117  	}
   118  
   119  	// Try import line with team type but nil team.
   120  	line.Type = "team"
   121  	if err := th.App.ImportLine(line, false); err == nil {
   122  		t.Fatalf("Expected an error when importing a line of type team with a nil team.")
   123  	}
   124  
   125  	// Try import line with channel type but nil channel.
   126  	line.Type = "channel"
   127  	if err := th.App.ImportLine(line, false); err == nil {
   128  		t.Fatalf("Expected an error when importing a line with type channel with a nil channel.")
   129  	}
   130  
   131  	// Try import line with user type but nil user.
   132  	line.Type = "user"
   133  	if err := th.App.ImportLine(line, false); err == nil {
   134  		t.Fatalf("Expected an error when importing a line with type uesr with a nil user.")
   135  	}
   136  
   137  	// Try import line with post type but nil post.
   138  	line.Type = "post"
   139  	if err := th.App.ImportLine(line, false); err == nil {
   140  		t.Fatalf("Expected an error when importing a line with type post with a nil post.")
   141  	}
   142  
   143  	// Try import line with direct_channel type but nil direct_channel.
   144  	line.Type = "direct_channel"
   145  	if err := th.App.ImportLine(line, false); err == nil {
   146  		t.Fatalf("Expected an error when importing a line with type direct_channel with a nil direct_channel.")
   147  	}
   148  
   149  	// Try import line with direct_post type but nil direct_post.
   150  	line.Type = "direct_post"
   151  	if err := th.App.ImportLine(line, false); err == nil {
   152  		t.Fatalf("Expected an error when importing a line with type direct_post with a nil direct_post.")
   153  	}
   154  
   155  	// Try import line with scheme type but nil scheme.
   156  	line.Type = "scheme"
   157  	if err := th.App.ImportLine(line, false); err == nil {
   158  		t.Fatalf("Expected an error when importing a line with type scheme with a nil scheme.")
   159  	}
   160  }
   161  
   162  func TestImportBulkImport(t *testing.T) {
   163  	th := Setup(t)
   164  	defer th.TearDown()
   165  
   166  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = true })
   167  
   168  	teamName := model.NewId()
   169  	channelName := model.NewId()
   170  	username := model.NewId()
   171  	username2 := model.NewId()
   172  	username3 := model.NewId()
   173  	emojiName := model.NewId()
   174  	testsDir, _ := fileutils.FindDir("tests")
   175  	testImage := filepath.Join(testsDir, "test.png")
   176  	teamTheme1 := `{\"awayIndicator\":\"#DBBD4E\",\"buttonBg\":\"#23A1FF\",\"buttonColor\":\"#FFFFFF\",\"centerChannelBg\":\"#ffffff\",\"centerChannelColor\":\"#333333\",\"codeTheme\":\"github\",\"image\":\"/static/files/a4a388b38b32678e83823ef1b3e17766.png\",\"linkColor\":\"#2389d7\",\"mentionBg\":\"#2389d7\",\"mentionColor\":\"#ffffff\",\"mentionHighlightBg\":\"#fff2bb\",\"mentionHighlightLink\":\"#2f81b7\",\"newMessageSeparator\":\"#FF8800\",\"onlineIndicator\":\"#7DBE00\",\"sidebarBg\":\"#fafafa\",\"sidebarHeaderBg\":\"#3481B9\",\"sidebarHeaderTextColor\":\"#ffffff\",\"sidebarText\":\"#333333\",\"sidebarTextActiveBorder\":\"#378FD2\",\"sidebarTextActiveColor\":\"#111111\",\"sidebarTextHoverBg\":\"#e6f2fa\",\"sidebarUnreadText\":\"#333333\",\"type\":\"Mattermost\"}`
   177  	teamTheme2 := `{\"awayIndicator\":\"#DBBD4E\",\"buttonBg\":\"#23A100\",\"buttonColor\":\"#EEEEEE\",\"centerChannelBg\":\"#ffffff\",\"centerChannelColor\":\"#333333\",\"codeTheme\":\"github\",\"image\":\"/static/files/a4a388b38b32678e83823ef1b3e17766.png\",\"linkColor\":\"#2389d7\",\"mentionBg\":\"#2389d7\",\"mentionColor\":\"#ffffff\",\"mentionHighlightBg\":\"#fff2bb\",\"mentionHighlightLink\":\"#2f81b7\",\"newMessageSeparator\":\"#FF8800\",\"onlineIndicator\":\"#7DBE00\",\"sidebarBg\":\"#fafafa\",\"sidebarHeaderBg\":\"#3481B9\",\"sidebarHeaderTextColor\":\"#ffffff\",\"sidebarText\":\"#333333\",\"sidebarTextActiveBorder\":\"#378FD2\",\"sidebarTextActiveColor\":\"#222222\",\"sidebarTextHoverBg\":\"#e6f2fa\",\"sidebarUnreadText\":\"#444444\",\"type\":\"Mattermost\"}`
   178  
   179  	// Run bulk import with a valid 1 of everything.
   180  	data1 := `{"type": "version", "version": 1}
   181  {"type": "team", "team": {"type": "O", "display_name": "lskmw2d7a5ao7ppwqh5ljchvr4", "name": "` + teamName + `"}}
   182  {"type": "channel", "channel": {"type": "O", "display_name": "xr6m6udffngark2uekvr3hoeny", "team": "` + teamName + `", "name": "` + channelName + `"}}
   183  {"type": "user", "user": {"username": "` + username + `", "email": "` + username + `@example.com", "teams": [{"name": "` + teamName + `","theme": "` + teamTheme1 + `", "channels": [{"name": "` + channelName + `"}]}]}}
   184  {"type": "user", "user": {"username": "` + username2 + `", "email": "` + username2 + `@example.com", "teams": [{"name": "` + teamName + `","theme": "` + teamTheme2 + `", "channels": [{"name": "` + channelName + `"}]}]}}
   185  {"type": "user", "user": {"username": "` + username3 + `", "email": "` + username3 + `@example.com", "teams": [{"name": "` + teamName + `", "channels": [{"name": "` + channelName + `"}], "delete_at": 123456789016}]}}
   186  {"type": "post", "post": {"team": "` + teamName + `", "channel": "` + channelName + `", "user": "` + username + `", "message": "Hello World", "create_at": 123456789012, "attachments":[{"path": "` + testImage + `"}]}}
   187  {"type": "post", "post": {"team": "` + teamName + `", "channel": "` + channelName + `", "user": "` + username3 + `", "message": "Hey Everyone!", "create_at": 123456789013, "attachments":[{"path": "` + testImage + `"}]}}
   188  {"type": "direct_channel", "direct_channel": {"members": ["` + username + `", "` + username2 + `"]}}
   189  {"type": "direct_channel", "direct_channel": {"members": ["` + username + `", "` + username2 + `", "` + username3 + `"]}}
   190  {"type": "direct_post", "direct_post": {"channel_members": ["` + username + `", "` + username2 + `"], "user": "` + username + `", "message": "Hello Direct Channel", "create_at": 123456789014}}
   191  {"type": "direct_post", "direct_post": {"channel_members": ["` + username + `", "` + username2 + `", "` + username3 + `"], "user": "` + username + `", "message": "Hello Group Channel", "create_at": 123456789015}}
   192  {"type": "emoji", "emoji": {"name": "` + emojiName + `", "image": "` + testImage + `"}}`
   193  
   194  	if err, line := th.App.BulkImport(strings.NewReader(data1), false, 2); err != nil || line != 0 {
   195  		t.Fatalf("BulkImport should have succeeded: %v, %v", err.Error(), line)
   196  	}
   197  
   198  	// Run bulk import using a string that contains a line with invalid json.
   199  	data2 := `{"type": "version", "version": 1`
   200  	if err, line := th.App.BulkImport(strings.NewReader(data2), false, 2); err == nil || line != 1 {
   201  		t.Fatalf("Should have failed due to invalid JSON on line 1.")
   202  	}
   203  
   204  	// Run bulk import using valid JSON but missing version line at the start.
   205  	data3 := `{"type": "team", "team": {"type": "O", "display_name": "lskmw2d7a5ao7ppwqh5ljchvr4", "name": "` + teamName + `"}}
   206  {"type": "channel", "channel": {"type": "O", "display_name": "xr6m6udffngark2uekvr3hoeny", "team": "` + teamName + `", "name": "` + channelName + `"}}
   207  {"type": "user", "user": {"username": "kufjgnkxkrhhfgbrip6qxkfsaa", "email": "kufjgnkxkrhhfgbrip6qxkfsaa@example.com"}}
   208  {"type": "user", "user": {"username": "bwshaim6qnc2ne7oqkd5b2s2rq", "email": "bwshaim6qnc2ne7oqkd5b2s2rq@example.com", "teams": [{"name": "` + teamName + `", "channels": [{"name": "` + channelName + `"}]}]}}`
   209  	if err, line := th.App.BulkImport(strings.NewReader(data3), false, 2); err == nil || line != 1 {
   210  		t.Fatalf("Should have failed due to missing version line on line 1.")
   211  	}
   212  }
   213  
   214  func TestImportProcessImportDataFileVersionLine(t *testing.T) {
   215  	data := LineImportData{
   216  		Type:    "version",
   217  		Version: ptrInt(1),
   218  	}
   219  	if version, err := processImportDataFileVersionLine(data); err != nil || version != 1 {
   220  		t.Fatalf("Expected no error and version 1.")
   221  	}
   222  
   223  	data.Type = "NotVersion"
   224  	if _, err := processImportDataFileVersionLine(data); err == nil {
   225  		t.Fatalf("Expected error on invalid version line.")
   226  	}
   227  
   228  	data.Type = "version"
   229  	data.Version = nil
   230  	if _, err := processImportDataFileVersionLine(data); err == nil {
   231  		t.Fatalf("Expected error on invalid version line.")
   232  	}
   233  }
   234  
   235  func GetAttachments(userId string, th *TestHelper, t *testing.T) []*model.FileInfo {
   236  	if result := <-th.App.Srv.Store.FileInfo().GetForUser(userId); result.Err != nil {
   237  		t.Fatal(result.Err.Error())
   238  	} else {
   239  		return result.Data.([]*model.FileInfo)
   240  	}
   241  	return nil
   242  }
   243  
   244  func AssertFileIdsInPost(files []*model.FileInfo, th *TestHelper, t *testing.T) {
   245  	postId := files[0].PostId
   246  	assert.NotNil(t, postId)
   247  
   248  	if result := <-th.App.Srv.Store.Post().GetPostsByIds([]string{postId}); result.Err != nil {
   249  		t.Fatal(result.Err.Error())
   250  	} else {
   251  		posts := result.Data.([]*model.Post)
   252  		assert.Equal(t, len(posts), 1)
   253  		for _, file := range files {
   254  			assert.Contains(t, posts[0].FileIds, file.Id)
   255  		}
   256  	}
   257  }