github.com/lologarithm/mattermost-server@v5.3.2-0.20181002060438-c82a84ed765b+incompatible/app/import_functions_test.go (about)

     1  // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
     2  // See License.txt for license information.
     3  
     4  package app
     5  
     6  import (
     7  	"path/filepath"
     8  	"strings"
     9  	"testing"
    10  
    11  	"github.com/mattermost/mattermost-server/model"
    12  	"github.com/mattermost/mattermost-server/store"
    13  	"github.com/mattermost/mattermost-server/utils"
    14  	"github.com/stretchr/testify/assert"
    15  )
    16  
    17  func TestImportImportScheme(t *testing.T) {
    18  	th := Setup()
    19  	defer th.TearDown()
    20  
    21  	// Mark the phase 2 permissions migration as completed.
    22  	<-th.App.Srv.Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"})
    23  
    24  	defer func() {
    25  		<-th.App.Srv.Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2)
    26  	}()
    27  
    28  	// Try importing an invalid scheme in dryRun mode.
    29  	data := SchemeImportData{
    30  		Name:  ptrStr(model.NewId()),
    31  		Scope: ptrStr("team"),
    32  		DefaultTeamUserRole: &RoleImportData{
    33  			Name:        ptrStr(model.NewId()),
    34  			DisplayName: ptrStr(model.NewId()),
    35  		},
    36  		DefaultTeamAdminRole: &RoleImportData{
    37  			Name:        ptrStr(model.NewId()),
    38  			DisplayName: ptrStr(model.NewId()),
    39  		},
    40  		DefaultChannelUserRole: &RoleImportData{
    41  			Name:        ptrStr(model.NewId()),
    42  			DisplayName: ptrStr(model.NewId()),
    43  		},
    44  		DefaultChannelAdminRole: &RoleImportData{
    45  			Name:        ptrStr(model.NewId()),
    46  			DisplayName: ptrStr(model.NewId()),
    47  		},
    48  		Description: ptrStr("description"),
    49  	}
    50  
    51  	if err := th.App.ImportScheme(&data, true); err == nil {
    52  		t.Fatalf("Should have failed to import.")
    53  	}
    54  
    55  	if res := <-th.App.Srv.Store.Scheme().GetByName(*data.Name); res.Err == nil {
    56  		t.Fatalf("Scheme should not have imported.")
    57  	}
    58  
    59  	// Try importing a valid scheme in dryRun mode.
    60  	data.DisplayName = ptrStr("display name")
    61  
    62  	if err := th.App.ImportScheme(&data, true); err != nil {
    63  		t.Fatalf("Should have succeeded.")
    64  	}
    65  
    66  	if res := <-th.App.Srv.Store.Scheme().GetByName(*data.Name); res.Err == nil {
    67  		t.Fatalf("Scheme should not have imported.")
    68  	}
    69  
    70  	// Try importing an invalid scheme.
    71  	data.DisplayName = nil
    72  
    73  	if err := th.App.ImportScheme(&data, false); err == nil {
    74  		t.Fatalf("Should have failed to import.")
    75  	}
    76  
    77  	if res := <-th.App.Srv.Store.Scheme().GetByName(*data.Name); res.Err == nil {
    78  		t.Fatalf("Scheme should not have imported.")
    79  	}
    80  
    81  	// Try importing a valid scheme with all params set.
    82  	data.DisplayName = ptrStr("display name")
    83  
    84  	if err := th.App.ImportScheme(&data, false); err != nil {
    85  		t.Fatalf("Should have succeeded.")
    86  	}
    87  
    88  	if res := <-th.App.Srv.Store.Scheme().GetByName(*data.Name); res.Err != nil {
    89  		t.Fatalf("Failed to import scheme: %v", res.Err)
    90  	} else {
    91  		scheme := res.Data.(*model.Scheme)
    92  		assert.Equal(t, *data.Name, scheme.Name)
    93  		assert.Equal(t, *data.DisplayName, scheme.DisplayName)
    94  		assert.Equal(t, *data.Description, scheme.Description)
    95  		assert.Equal(t, *data.Scope, scheme.Scope)
    96  
    97  		if res := <-th.App.Srv.Store.Role().GetByName(scheme.DefaultTeamAdminRole); res.Err != nil {
    98  			t.Fatalf("Should have found the imported role.")
    99  		} else {
   100  			role := res.Data.(*model.Role)
   101  			assert.Equal(t, *data.DefaultTeamAdminRole.DisplayName, role.DisplayName)
   102  			assert.False(t, role.BuiltIn)
   103  			assert.True(t, role.SchemeManaged)
   104  		}
   105  
   106  		if res := <-th.App.Srv.Store.Role().GetByName(scheme.DefaultTeamUserRole); res.Err != nil {
   107  			t.Fatalf("Should have found the imported role.")
   108  		} else {
   109  			role := res.Data.(*model.Role)
   110  			assert.Equal(t, *data.DefaultTeamUserRole.DisplayName, role.DisplayName)
   111  			assert.False(t, role.BuiltIn)
   112  			assert.True(t, role.SchemeManaged)
   113  		}
   114  
   115  		if res := <-th.App.Srv.Store.Role().GetByName(scheme.DefaultChannelAdminRole); res.Err != nil {
   116  			t.Fatalf("Should have found the imported role.")
   117  		} else {
   118  			role := res.Data.(*model.Role)
   119  			assert.Equal(t, *data.DefaultChannelAdminRole.DisplayName, role.DisplayName)
   120  			assert.False(t, role.BuiltIn)
   121  			assert.True(t, role.SchemeManaged)
   122  		}
   123  
   124  		if res := <-th.App.Srv.Store.Role().GetByName(scheme.DefaultChannelUserRole); res.Err != nil {
   125  			t.Fatalf("Should have found the imported role.")
   126  		} else {
   127  			role := res.Data.(*model.Role)
   128  			assert.Equal(t, *data.DefaultChannelUserRole.DisplayName, role.DisplayName)
   129  			assert.False(t, role.BuiltIn)
   130  			assert.True(t, role.SchemeManaged)
   131  		}
   132  	}
   133  
   134  	// Try modifying all the fields and re-importing.
   135  	data.DisplayName = ptrStr("new display name")
   136  	data.Description = ptrStr("new description")
   137  
   138  	if err := th.App.ImportScheme(&data, false); err != nil {
   139  		t.Fatalf("Should have succeeded: %v", err)
   140  	}
   141  
   142  	if res := <-th.App.Srv.Store.Scheme().GetByName(*data.Name); res.Err != nil {
   143  		t.Fatalf("Failed to import scheme: %v", res.Err)
   144  	} else {
   145  		scheme := res.Data.(*model.Scheme)
   146  		assert.Equal(t, *data.Name, scheme.Name)
   147  		assert.Equal(t, *data.DisplayName, scheme.DisplayName)
   148  		assert.Equal(t, *data.Description, scheme.Description)
   149  		assert.Equal(t, *data.Scope, scheme.Scope)
   150  
   151  		if res := <-th.App.Srv.Store.Role().GetByName(scheme.DefaultTeamAdminRole); res.Err != nil {
   152  			t.Fatalf("Should have found the imported role.")
   153  		} else {
   154  			role := res.Data.(*model.Role)
   155  			assert.Equal(t, *data.DefaultTeamAdminRole.DisplayName, role.DisplayName)
   156  			assert.False(t, role.BuiltIn)
   157  			assert.True(t, role.SchemeManaged)
   158  		}
   159  
   160  		if res := <-th.App.Srv.Store.Role().GetByName(scheme.DefaultTeamUserRole); res.Err != nil {
   161  			t.Fatalf("Should have found the imported role.")
   162  		} else {
   163  			role := res.Data.(*model.Role)
   164  			assert.Equal(t, *data.DefaultTeamUserRole.DisplayName, role.DisplayName)
   165  			assert.False(t, role.BuiltIn)
   166  			assert.True(t, role.SchemeManaged)
   167  		}
   168  
   169  		if res := <-th.App.Srv.Store.Role().GetByName(scheme.DefaultChannelAdminRole); res.Err != nil {
   170  			t.Fatalf("Should have found the imported role.")
   171  		} else {
   172  			role := res.Data.(*model.Role)
   173  			assert.Equal(t, *data.DefaultChannelAdminRole.DisplayName, role.DisplayName)
   174  			assert.False(t, role.BuiltIn)
   175  			assert.True(t, role.SchemeManaged)
   176  		}
   177  
   178  		if res := <-th.App.Srv.Store.Role().GetByName(scheme.DefaultChannelUserRole); res.Err != nil {
   179  			t.Fatalf("Should have found the imported role.")
   180  		} else {
   181  			role := res.Data.(*model.Role)
   182  			assert.Equal(t, *data.DefaultChannelUserRole.DisplayName, role.DisplayName)
   183  			assert.False(t, role.BuiltIn)
   184  			assert.True(t, role.SchemeManaged)
   185  		}
   186  	}
   187  
   188  	// Try changing the scope of the scheme and reimporting.
   189  	data.Scope = ptrStr("channel")
   190  
   191  	if err := th.App.ImportScheme(&data, false); err == nil {
   192  		t.Fatalf("Should have failed to import.")
   193  	}
   194  
   195  	if res := <-th.App.Srv.Store.Scheme().GetByName(*data.Name); res.Err != nil {
   196  		t.Fatalf("Failed to import scheme: %v", res.Err)
   197  	} else {
   198  		scheme := res.Data.(*model.Scheme)
   199  		assert.Equal(t, *data.Name, scheme.Name)
   200  		assert.Equal(t, *data.DisplayName, scheme.DisplayName)
   201  		assert.Equal(t, *data.Description, scheme.Description)
   202  		assert.Equal(t, "team", scheme.Scope)
   203  	}
   204  }
   205  
   206  func TestImportImportRole(t *testing.T) {
   207  	th := Setup()
   208  	defer th.TearDown()
   209  
   210  	// Try importing an invalid role in dryRun mode.
   211  	rid1 := model.NewId()
   212  	data := RoleImportData{
   213  		Name: &rid1,
   214  	}
   215  
   216  	if err := th.App.ImportRole(&data, true, false); err == nil {
   217  		t.Fatalf("Should have failed to import.")
   218  	}
   219  
   220  	if res := <-th.App.Srv.Store.Role().GetByName(rid1); res.Err == nil {
   221  		t.Fatalf("Role should not have imported.")
   222  	}
   223  
   224  	// Try importing the valid role in dryRun mode.
   225  	data.DisplayName = ptrStr("display name")
   226  
   227  	if err := th.App.ImportRole(&data, true, false); err != nil {
   228  		t.Fatalf("Should have succeeded.")
   229  	}
   230  
   231  	if res := <-th.App.Srv.Store.Role().GetByName(rid1); res.Err == nil {
   232  		t.Fatalf("Role should not have imported as we are in dry run mode.")
   233  	}
   234  
   235  	// Try importing an invalid role.
   236  	data.DisplayName = nil
   237  
   238  	if err := th.App.ImportRole(&data, false, false); err == nil {
   239  		t.Fatalf("Should have failed to import.")
   240  	}
   241  
   242  	if res := <-th.App.Srv.Store.Role().GetByName(rid1); res.Err == nil {
   243  		t.Fatalf("Role should not have imported.")
   244  	}
   245  
   246  	// Try importing a valid role with all params set.
   247  	data.DisplayName = ptrStr("display name")
   248  	data.Description = ptrStr("description")
   249  	data.Permissions = &[]string{"invite_user", "add_user_to_team"}
   250  
   251  	if err := th.App.ImportRole(&data, false, false); err != nil {
   252  		t.Fatalf("Should have succeeded.")
   253  	}
   254  
   255  	if res := <-th.App.Srv.Store.Role().GetByName(rid1); res.Err != nil {
   256  		t.Fatalf("Should have found the imported role.")
   257  	} else {
   258  		role := res.Data.(*model.Role)
   259  		assert.Equal(t, *data.Name, role.Name)
   260  		assert.Equal(t, *data.DisplayName, role.DisplayName)
   261  		assert.Equal(t, *data.Description, role.Description)
   262  		assert.Equal(t, *data.Permissions, role.Permissions)
   263  		assert.False(t, role.BuiltIn)
   264  		assert.False(t, role.SchemeManaged)
   265  	}
   266  
   267  	// Try changing all the params and reimporting.
   268  	data.DisplayName = ptrStr("new display name")
   269  	data.Description = ptrStr("description")
   270  	data.Permissions = &[]string{"use_slash_commands"}
   271  
   272  	if err := th.App.ImportRole(&data, false, true); err != nil {
   273  		t.Fatalf("Should have succeeded. %v", err)
   274  	}
   275  
   276  	if res := <-th.App.Srv.Store.Role().GetByName(rid1); res.Err != nil {
   277  		t.Fatalf("Should have found the imported role.")
   278  	} else {
   279  		role := res.Data.(*model.Role)
   280  		assert.Equal(t, *data.Name, role.Name)
   281  		assert.Equal(t, *data.DisplayName, role.DisplayName)
   282  		assert.Equal(t, *data.Description, role.Description)
   283  		assert.Equal(t, *data.Permissions, role.Permissions)
   284  		assert.False(t, role.BuiltIn)
   285  		assert.True(t, role.SchemeManaged)
   286  	}
   287  
   288  	// Check that re-importing with only required fields doesn't update the others.
   289  	data2 := RoleImportData{
   290  		Name:        &rid1,
   291  		DisplayName: ptrStr("new display name again"),
   292  	}
   293  
   294  	if err := th.App.ImportRole(&data2, false, false); err != nil {
   295  		t.Fatalf("Should have succeeded.")
   296  	}
   297  
   298  	if res := <-th.App.Srv.Store.Role().GetByName(rid1); res.Err != nil {
   299  		t.Fatalf("Should have found the imported role.")
   300  	} else {
   301  		role := res.Data.(*model.Role)
   302  		assert.Equal(t, *data2.Name, role.Name)
   303  		assert.Equal(t, *data2.DisplayName, role.DisplayName)
   304  		assert.Equal(t, *data.Description, role.Description)
   305  		assert.Equal(t, *data.Permissions, role.Permissions)
   306  		assert.False(t, role.BuiltIn)
   307  		assert.False(t, role.SchemeManaged)
   308  	}
   309  }
   310  
   311  func TestImportImportTeam(t *testing.T) {
   312  	th := Setup()
   313  	defer th.TearDown()
   314  
   315  	// Mark the phase 2 permissions migration as completed.
   316  	<-th.App.Srv.Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"})
   317  
   318  	defer func() {
   319  		<-th.App.Srv.Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2)
   320  	}()
   321  
   322  	scheme1 := th.SetupTeamScheme()
   323  	scheme2 := th.SetupTeamScheme()
   324  
   325  	// Check how many teams are in the database.
   326  	var teamsCount int64
   327  	if r := <-th.App.Srv.Store.Team().AnalyticsTeamCount(); r.Err == nil {
   328  		teamsCount = r.Data.(int64)
   329  	} else {
   330  		t.Fatalf("Failed to get team count.")
   331  	}
   332  
   333  	data := TeamImportData{
   334  		Name:            ptrStr(model.NewId()),
   335  		DisplayName:     ptrStr("Display Name"),
   336  		Type:            ptrStr("XYZ"),
   337  		Description:     ptrStr("The team description."),
   338  		AllowOpenInvite: ptrBool(true),
   339  		Scheme:          &scheme1.Name,
   340  	}
   341  
   342  	// Try importing an invalid team in dryRun mode.
   343  	if err := th.App.ImportTeam(&data, true); err == nil {
   344  		t.Fatalf("Should have received an error importing an invalid team.")
   345  	}
   346  
   347  	// Do a valid team in dry-run mode.
   348  	data.Type = ptrStr("O")
   349  	if err := th.App.ImportTeam(&data, true); err != nil {
   350  		t.Fatalf("Received an error validating valid team.")
   351  	}
   352  
   353  	// Check that no more teams are in the DB.
   354  	th.CheckTeamCount(t, teamsCount)
   355  
   356  	// Do an invalid team in apply mode, check db changes.
   357  	data.Type = ptrStr("XYZ")
   358  	if err := th.App.ImportTeam(&data, false); err == nil {
   359  		t.Fatalf("Import should have failed on invalid team.")
   360  	}
   361  
   362  	// Check that no more teams are in the DB.
   363  	th.CheckTeamCount(t, teamsCount)
   364  
   365  	// Do a valid team in apply mode, check db changes.
   366  	data.Type = ptrStr("O")
   367  	if err := th.App.ImportTeam(&data, false); err != nil {
   368  		t.Fatalf("Received an error importing valid team: %v", err)
   369  	}
   370  
   371  	// Check that one more team is in the DB.
   372  	th.CheckTeamCount(t, teamsCount+1)
   373  
   374  	// Get the team and check that all the fields are correct.
   375  	if team, err := th.App.GetTeamByName(*data.Name); err != nil {
   376  		t.Fatalf("Failed to get team from database.")
   377  	} else {
   378  		assert.Equal(t, *data.DisplayName, team.DisplayName)
   379  		assert.Equal(t, *data.Type, team.Type)
   380  		assert.Equal(t, *data.Description, team.Description)
   381  		assert.Equal(t, *data.AllowOpenInvite, team.AllowOpenInvite)
   382  		assert.Equal(t, scheme1.Id, *team.SchemeId)
   383  	}
   384  
   385  	// Alter all the fields of that team (apart from unique identifier) and import again.
   386  	data.DisplayName = ptrStr("Display Name 2")
   387  	data.Type = ptrStr("P")
   388  	data.Description = ptrStr("The new description")
   389  	data.AllowOpenInvite = ptrBool(false)
   390  	data.Scheme = &scheme2.Name
   391  
   392  	// Check that the original number of teams are again in the DB (because this query doesn't include deleted).
   393  	data.Type = ptrStr("O")
   394  	if err := th.App.ImportTeam(&data, false); err != nil {
   395  		t.Fatalf("Received an error importing updated valid team.")
   396  	}
   397  
   398  	th.CheckTeamCount(t, teamsCount+1)
   399  
   400  	// Get the team and check that all fields are correct.
   401  	if team, err := th.App.GetTeamByName(*data.Name); err != nil {
   402  		t.Fatalf("Failed to get team from database.")
   403  	} else {
   404  		assert.Equal(t, *data.DisplayName, team.DisplayName)
   405  		assert.Equal(t, *data.Type, team.Type)
   406  		assert.Equal(t, *data.Description, team.Description)
   407  		assert.Equal(t, *data.AllowOpenInvite, team.AllowOpenInvite)
   408  		assert.Equal(t, scheme2.Id, *team.SchemeId)
   409  	}
   410  }
   411  
   412  func TestImportImportChannel(t *testing.T) {
   413  	th := Setup()
   414  	defer th.TearDown()
   415  
   416  	// Mark the phase 2 permissions migration as completed.
   417  	<-th.App.Srv.Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"})
   418  
   419  	defer func() {
   420  		<-th.App.Srv.Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2)
   421  	}()
   422  
   423  	scheme1 := th.SetupChannelScheme()
   424  	scheme2 := th.SetupChannelScheme()
   425  
   426  	// Import a Team.
   427  	teamName := model.NewId()
   428  	th.App.ImportTeam(&TeamImportData{
   429  		Name:        &teamName,
   430  		DisplayName: ptrStr("Display Name"),
   431  		Type:        ptrStr("O"),
   432  	}, false)
   433  	team, err := th.App.GetTeamByName(teamName)
   434  	if err != nil {
   435  		t.Fatalf("Failed to get team from database.")
   436  	}
   437  
   438  	// Check how many channels are in the database.
   439  	var channelCount int64
   440  	if r := <-th.App.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_OPEN); r.Err == nil {
   441  		channelCount = r.Data.(int64)
   442  	} else {
   443  		t.Fatalf("Failed to get team count.")
   444  	}
   445  
   446  	// Do an invalid channel in dry-run mode.
   447  	data := ChannelImportData{
   448  		Team:        &teamName,
   449  		DisplayName: ptrStr("Display Name"),
   450  		Type:        ptrStr("O"),
   451  		Header:      ptrStr("Channe Header"),
   452  		Purpose:     ptrStr("Channel Purpose"),
   453  		Scheme:      &scheme1.Name,
   454  	}
   455  	if err := th.App.ImportChannel(&data, true); err == nil {
   456  		t.Fatalf("Expected error due to invalid name.")
   457  	}
   458  
   459  	// Check that no more channels are in the DB.
   460  	th.CheckChannelsCount(t, channelCount)
   461  
   462  	// Do a valid channel with a nonexistent team in dry-run mode.
   463  	data.Name = ptrStr("channelname")
   464  	data.Team = ptrStr(model.NewId())
   465  	if err := th.App.ImportChannel(&data, true); err != nil {
   466  		t.Fatalf("Expected success as cannot validate channel name in dry run mode.")
   467  	}
   468  
   469  	// Check that no more channels are in the DB.
   470  	th.CheckChannelsCount(t, channelCount)
   471  
   472  	// Do a valid channel in dry-run mode.
   473  	data.Team = &teamName
   474  	if err := th.App.ImportChannel(&data, true); err != nil {
   475  		t.Fatalf("Expected success as valid team.")
   476  	}
   477  
   478  	// Check that no more channels are in the DB.
   479  	th.CheckChannelsCount(t, channelCount)
   480  
   481  	// Do an invalid channel in apply mode.
   482  	data.Name = nil
   483  	if err := th.App.ImportChannel(&data, false); err == nil {
   484  		t.Fatalf("Expected error due to invalid name (apply mode).")
   485  	}
   486  
   487  	// Check that no more channels are in the DB.
   488  	th.CheckChannelsCount(t, channelCount)
   489  
   490  	// Do a valid channel in apply mode with a non-existent team.
   491  	data.Name = ptrStr("channelname")
   492  	data.Team = ptrStr(model.NewId())
   493  	if err := th.App.ImportChannel(&data, false); err == nil {
   494  		t.Fatalf("Expected error due to non-existent team (apply mode).")
   495  	}
   496  
   497  	// Check that no more channels are in the DB.
   498  	th.CheckChannelsCount(t, channelCount)
   499  
   500  	// Do a valid channel in apply mode.
   501  	data.Team = &teamName
   502  	if err := th.App.ImportChannel(&data, false); err != nil {
   503  		t.Fatalf("Expected success in apply mode: %v", err.Error())
   504  	}
   505  
   506  	// Check that 1 more channel is in the DB.
   507  	th.CheckChannelsCount(t, channelCount+1)
   508  
   509  	// Get the Channel and check all the fields are correct.
   510  	if channel, err := th.App.GetChannelByName(*data.Name, team.Id, false); err != nil {
   511  		t.Fatalf("Failed to get channel from database.")
   512  	} else {
   513  		assert.Equal(t, *data.Name, channel.Name)
   514  		assert.Equal(t, *data.DisplayName, channel.DisplayName)
   515  		assert.Equal(t, *data.Type, channel.Type)
   516  		assert.Equal(t, *data.Header, channel.Header)
   517  		assert.Equal(t, *data.Purpose, channel.Purpose)
   518  		assert.Equal(t, scheme1.Id, *channel.SchemeId)
   519  	}
   520  
   521  	// Alter all the fields of that channel.
   522  	data.DisplayName = ptrStr("Chaned Disp Name")
   523  	data.Type = ptrStr(model.CHANNEL_PRIVATE)
   524  	data.Header = ptrStr("New Header")
   525  	data.Purpose = ptrStr("New Purpose")
   526  	data.Scheme = &scheme2.Name
   527  	if err := th.App.ImportChannel(&data, false); err != nil {
   528  		t.Fatalf("Expected success in apply mode: %v", err.Error())
   529  	}
   530  
   531  	// Check channel count the same.
   532  	th.CheckChannelsCount(t, channelCount)
   533  
   534  	// Get the Channel and check all the fields are correct.
   535  	if channel, err := th.App.GetChannelByName(*data.Name, team.Id, false); err != nil {
   536  		t.Fatalf("Failed to get channel from database.")
   537  	} else {
   538  		assert.Equal(t, *data.Name, channel.Name)
   539  		assert.Equal(t, *data.DisplayName, channel.DisplayName)
   540  		assert.Equal(t, *data.Type, channel.Type)
   541  		assert.Equal(t, *data.Header, channel.Header)
   542  		assert.Equal(t, *data.Purpose, channel.Purpose)
   543  		assert.Equal(t, scheme2.Id, *channel.SchemeId)
   544  	}
   545  
   546  }
   547  
   548  func TestImportImportUser(t *testing.T) {
   549  	th := Setup()
   550  	defer th.TearDown()
   551  
   552  	// Check how many users are in the database.
   553  	var userCount int64
   554  	if r := <-th.App.Srv.Store.User().GetTotalUsersCount(); r.Err == nil {
   555  		userCount = r.Data.(int64)
   556  	} else {
   557  		t.Fatalf("Failed to get user count.")
   558  	}
   559  
   560  	// Do an invalid user in dry-run mode.
   561  	data := UserImportData{
   562  		Username: ptrStr(model.NewId()),
   563  	}
   564  	if err := th.App.ImportUser(&data, true); err == nil {
   565  		t.Fatalf("Should have failed to import invalid user.")
   566  	}
   567  
   568  	// Check that no more users are in the DB.
   569  	if r := <-th.App.Srv.Store.User().GetTotalUsersCount(); r.Err == nil {
   570  		if r.Data.(int64) != userCount {
   571  			t.Fatalf("Unexpected number of users")
   572  		}
   573  	} else {
   574  		t.Fatalf("Failed to get user count.")
   575  	}
   576  
   577  	// Do a valid user in dry-run mode.
   578  	data = UserImportData{
   579  		Username: ptrStr(model.NewId()),
   580  		Email:    ptrStr(model.NewId() + "@example.com"),
   581  	}
   582  	if err := th.App.ImportUser(&data, true); err != nil {
   583  		t.Fatalf("Should have succeeded to import valid user.")
   584  	}
   585  
   586  	// Check that no more users are in the DB.
   587  	if r := <-th.App.Srv.Store.User().GetTotalUsersCount(); r.Err == nil {
   588  		if r.Data.(int64) != userCount {
   589  			t.Fatalf("Unexpected number of users")
   590  		}
   591  	} else {
   592  		t.Fatalf("Failed to get user count.")
   593  	}
   594  
   595  	// Do an invalid user in apply mode.
   596  	data = UserImportData{
   597  		Username: ptrStr(model.NewId()),
   598  	}
   599  	if err := th.App.ImportUser(&data, false); err == nil {
   600  		t.Fatalf("Should have failed to import invalid user.")
   601  	}
   602  
   603  	// Check that no more users are in the DB.
   604  	if r := <-th.App.Srv.Store.User().GetTotalUsersCount(); r.Err == nil {
   605  		if r.Data.(int64) != userCount {
   606  			t.Fatalf("Unexpected number of users")
   607  		}
   608  	} else {
   609  		t.Fatalf("Failed to get user count.")
   610  	}
   611  
   612  	// Do a valid user in apply mode.
   613  	username := model.NewId()
   614  	testsDir, _ := utils.FindDir("tests")
   615  	data = UserImportData{
   616  		ProfileImage: ptrStr(filepath.Join(testsDir, "test.png")),
   617  		Username:     &username,
   618  		Email:        ptrStr(model.NewId() + "@example.com"),
   619  		Nickname:     ptrStr(model.NewId()),
   620  		FirstName:    ptrStr(model.NewId()),
   621  		LastName:     ptrStr(model.NewId()),
   622  		Position:     ptrStr(model.NewId()),
   623  	}
   624  	if err := th.App.ImportUser(&data, false); err != nil {
   625  		t.Fatalf("Should have succeeded to import valid user.")
   626  	}
   627  
   628  	// Check that one more user is in the DB.
   629  	if r := <-th.App.Srv.Store.User().GetTotalUsersCount(); r.Err == nil {
   630  		if r.Data.(int64) != userCount+1 {
   631  			t.Fatalf("Unexpected number of users")
   632  		}
   633  	} else {
   634  		t.Fatalf("Failed to get user count.")
   635  	}
   636  
   637  	// Get the user and check all the fields are correct.
   638  	if user, err := th.App.GetUserByUsername(username); err != nil {
   639  		t.Fatalf("Failed to get user from database.")
   640  	} else {
   641  		if user.Email != *data.Email || user.Nickname != *data.Nickname || user.FirstName != *data.FirstName || user.LastName != *data.LastName || user.Position != *data.Position {
   642  			t.Fatalf("User properties do not match Import Data.")
   643  		}
   644  		// Check calculated properties.
   645  		if user.AuthService != "" {
   646  			t.Fatalf("Expected Auth Service to be empty.")
   647  		}
   648  
   649  		if !(user.AuthData == nil || *user.AuthData == "") {
   650  			t.Fatalf("Expected AuthData to be empty.")
   651  		}
   652  
   653  		if len(user.Password) == 0 {
   654  			t.Fatalf("Expected password to be set.")
   655  		}
   656  
   657  		if !user.EmailVerified {
   658  			t.Fatalf("Expected EmailVerified to be true.")
   659  		}
   660  
   661  		if user.Locale != *th.App.Config().LocalizationSettings.DefaultClientLocale {
   662  			t.Fatalf("Expected Locale to be the default.")
   663  		}
   664  
   665  		if user.Roles != "system_user" {
   666  			t.Fatalf("Expected roles to be system_user")
   667  		}
   668  	}
   669  
   670  	// Alter all the fields of that user.
   671  	data.Email = ptrStr(model.NewId() + "@example.com")
   672  	data.ProfileImage = ptrStr(filepath.Join(testsDir, "testgif.gif"))
   673  	data.AuthService = ptrStr("ldap")
   674  	data.AuthData = &username
   675  	data.Nickname = ptrStr(model.NewId())
   676  	data.FirstName = ptrStr(model.NewId())
   677  	data.LastName = ptrStr(model.NewId())
   678  	data.Position = ptrStr(model.NewId())
   679  	data.Roles = ptrStr("system_admin system_user")
   680  	data.Locale = ptrStr("zh_CN")
   681  	if err := th.App.ImportUser(&data, false); err != nil {
   682  		t.Fatalf("Should have succeeded to update valid user %v", err)
   683  	}
   684  
   685  	// Check user count the same.
   686  	if r := <-th.App.Srv.Store.User().GetTotalUsersCount(); r.Err == nil {
   687  		if r.Data.(int64) != userCount+1 {
   688  			t.Fatalf("Unexpected number of users")
   689  		}
   690  	} else {
   691  		t.Fatalf("Failed to get user count.")
   692  	}
   693  
   694  	// Get the user and check all the fields are correct.
   695  	if user, err := th.App.GetUserByUsername(username); err != nil {
   696  		t.Fatalf("Failed to get user from database.")
   697  	} else {
   698  		if user.Email != *data.Email || user.Nickname != *data.Nickname || user.FirstName != *data.FirstName || user.LastName != *data.LastName || user.Position != *data.Position {
   699  			t.Fatalf("Updated User properties do not match Import Data.")
   700  		}
   701  		// Check calculated properties.
   702  		if user.AuthService != "ldap" {
   703  			t.Fatalf("Expected Auth Service to be ldap \"%v\"", user.AuthService)
   704  		}
   705  
   706  		if !(user.AuthData == data.AuthData || *user.AuthData == *data.AuthData) {
   707  			t.Fatalf("Expected AuthData to be set.")
   708  		}
   709  
   710  		if len(user.Password) != 0 {
   711  			t.Fatalf("Expected password to be empty.")
   712  		}
   713  
   714  		if !user.EmailVerified {
   715  			t.Fatalf("Expected EmailVerified to be true.")
   716  		}
   717  
   718  		if user.Locale != *data.Locale {
   719  			t.Fatalf("Expected Locale to be the set.")
   720  		}
   721  
   722  		if user.Roles != *data.Roles {
   723  			t.Fatalf("Expected roles to be set: %v", user.Roles)
   724  		}
   725  	}
   726  
   727  	// Check Password and AuthData together.
   728  	data.Password = ptrStr("PasswordTest")
   729  	if err := th.App.ImportUser(&data, false); err == nil {
   730  		t.Fatalf("Should have failed to import invalid user.")
   731  	}
   732  
   733  	data.AuthData = nil
   734  	if err := th.App.ImportUser(&data, false); err != nil {
   735  		t.Fatalf("Should have succeeded to update valid user %v", err)
   736  	}
   737  
   738  	data.Password = ptrStr("")
   739  	if err := th.App.ImportUser(&data, false); err == nil {
   740  		t.Fatalf("Should have failed to import invalid user.")
   741  	}
   742  
   743  	data.Password = ptrStr(strings.Repeat("0123456789", 10))
   744  	if err := th.App.ImportUser(&data, false); err == nil {
   745  		t.Fatalf("Should have failed to import invalid user.")
   746  	}
   747  
   748  	data.Password = ptrStr("TestPassword")
   749  
   750  	// Test team and channel memberships
   751  	teamName := model.NewId()
   752  	th.App.ImportTeam(&TeamImportData{
   753  		Name:        &teamName,
   754  		DisplayName: ptrStr("Display Name"),
   755  		Type:        ptrStr("O"),
   756  	}, false)
   757  	team, err := th.App.GetTeamByName(teamName)
   758  	if err != nil {
   759  		t.Fatalf("Failed to get team from database.")
   760  	}
   761  
   762  	channelName := model.NewId()
   763  	th.App.ImportChannel(&ChannelImportData{
   764  		Team:        &teamName,
   765  		Name:        &channelName,
   766  		DisplayName: ptrStr("Display Name"),
   767  		Type:        ptrStr("O"),
   768  	}, false)
   769  	channel, err := th.App.GetChannelByName(channelName, team.Id, false)
   770  	if err != nil {
   771  		t.Fatalf("Failed to get channel from database.")
   772  	}
   773  
   774  	username = model.NewId()
   775  	data = UserImportData{
   776  		Username:  &username,
   777  		Email:     ptrStr(model.NewId() + "@example.com"),
   778  		Nickname:  ptrStr(model.NewId()),
   779  		FirstName: ptrStr(model.NewId()),
   780  		LastName:  ptrStr(model.NewId()),
   781  		Position:  ptrStr(model.NewId()),
   782  	}
   783  
   784  	teamMembers, err := th.App.GetTeamMembers(team.Id, 0, 1000)
   785  	if err != nil {
   786  		t.Fatalf("Failed to get team member count")
   787  	}
   788  	teamMemberCount := len(teamMembers)
   789  
   790  	channelMemberCount, err := th.App.GetChannelMemberCount(channel.Id)
   791  	if err != nil {
   792  		t.Fatalf("Failed to get channel member count")
   793  	}
   794  
   795  	// Test with an invalid team & channel membership in dry-run mode.
   796  	data.Teams = &[]UserTeamImportData{
   797  		{
   798  			Roles: ptrStr("invalid"),
   799  			Channels: &[]UserChannelImportData{
   800  				{
   801  					Roles: ptrStr("invalid"),
   802  				},
   803  			},
   804  		},
   805  	}
   806  	if err := th.App.ImportUser(&data, true); err == nil {
   807  		t.Fatalf("Should have failed.")
   808  	}
   809  
   810  	// Test with an unknown team name & invalid channel membership in dry-run mode.
   811  	data.Teams = &[]UserTeamImportData{
   812  		{
   813  			Name: ptrStr(model.NewId()),
   814  			Channels: &[]UserChannelImportData{
   815  				{
   816  					Roles: ptrStr("invalid"),
   817  				},
   818  			},
   819  		},
   820  	}
   821  	if err := th.App.ImportUser(&data, true); err == nil {
   822  		t.Fatalf("Should have failed.")
   823  	}
   824  
   825  	// Test with a valid team & invalid channel membership in dry-run mode.
   826  	data.Teams = &[]UserTeamImportData{
   827  		{
   828  			Name: &teamName,
   829  			Channels: &[]UserChannelImportData{
   830  				{
   831  					Roles: ptrStr("invalid"),
   832  				},
   833  			},
   834  		},
   835  	}
   836  	if err := th.App.ImportUser(&data, true); err == nil {
   837  		t.Fatalf("Should have failed.")
   838  	}
   839  
   840  	// Test with a valid team & unknown channel name in dry-run mode.
   841  	data.Teams = &[]UserTeamImportData{
   842  		{
   843  			Name: &teamName,
   844  			Channels: &[]UserChannelImportData{
   845  				{
   846  					Name: ptrStr(model.NewId()),
   847  				},
   848  			},
   849  		},
   850  	}
   851  	if err := th.App.ImportUser(&data, true); err != nil {
   852  		t.Fatalf("Should have succeeded.")
   853  	}
   854  
   855  	// Test with a valid team & valid channel name in dry-run mode.
   856  	data.Teams = &[]UserTeamImportData{
   857  		{
   858  			Name: &teamName,
   859  			Channels: &[]UserChannelImportData{
   860  				{
   861  					Name: &channelName,
   862  				},
   863  			},
   864  		},
   865  	}
   866  	if err := th.App.ImportUser(&data, true); err != nil {
   867  		t.Fatalf("Should have succeeded.")
   868  	}
   869  
   870  	// Check no new member objects were created because dry run mode.
   871  	if tmc, err := th.App.GetTeamMembers(team.Id, 0, 1000); err != nil {
   872  		t.Fatalf("Failed to get Team Member Count")
   873  	} else if len(tmc) != teamMemberCount {
   874  		t.Fatalf("Number of team members not as expected")
   875  	}
   876  
   877  	if cmc, err := th.App.GetChannelMemberCount(channel.Id); err != nil {
   878  		t.Fatalf("Failed to get Channel Member Count")
   879  	} else if cmc != channelMemberCount {
   880  		t.Fatalf("Number of channel members not as expected")
   881  	}
   882  
   883  	// Test with an invalid team & channel membership in apply mode.
   884  	data.Teams = &[]UserTeamImportData{
   885  		{
   886  			Roles: ptrStr("invalid"),
   887  			Channels: &[]UserChannelImportData{
   888  				{
   889  					Roles: ptrStr("invalid"),
   890  				},
   891  			},
   892  		},
   893  	}
   894  	if err := th.App.ImportUser(&data, false); err == nil {
   895  		t.Fatalf("Should have failed.")
   896  	}
   897  
   898  	// Test with an unknown team name & invalid channel membership in apply mode.
   899  	data.Teams = &[]UserTeamImportData{
   900  		{
   901  			Name: ptrStr(model.NewId()),
   902  			Channels: &[]UserChannelImportData{
   903  				{
   904  					Roles: ptrStr("invalid"),
   905  				},
   906  			},
   907  		},
   908  	}
   909  	if err := th.App.ImportUser(&data, false); err == nil {
   910  		t.Fatalf("Should have failed.")
   911  	}
   912  
   913  	// Test with a valid team & invalid channel membership in apply mode.
   914  	data.Teams = &[]UserTeamImportData{
   915  		{
   916  			Name: &teamName,
   917  			Channels: &[]UserChannelImportData{
   918  				{
   919  					Roles: ptrStr("invalid"),
   920  				},
   921  			},
   922  		},
   923  	}
   924  	if err := th.App.ImportUser(&data, false); err == nil {
   925  		t.Fatalf("Should have failed.")
   926  	}
   927  
   928  	// Check no new member objects were created because all tests should have failed so far.
   929  	if tmc, err := th.App.GetTeamMembers(team.Id, 0, 1000); err != nil {
   930  		t.Fatalf("Failed to get Team Member Count")
   931  	} else if len(tmc) != teamMemberCount {
   932  		t.Fatalf("Number of team members not as expected")
   933  	}
   934  
   935  	if cmc, err := th.App.GetChannelMemberCount(channel.Id); err != nil {
   936  		t.Fatalf("Failed to get Channel Member Count")
   937  	} else if cmc != channelMemberCount {
   938  		t.Fatalf("Number of channel members not as expected")
   939  	}
   940  
   941  	// Test with a valid team & unknown channel name in apply mode.
   942  	data.Teams = &[]UserTeamImportData{
   943  		{
   944  			Name: &teamName,
   945  			Channels: &[]UserChannelImportData{
   946  				{
   947  					Name: ptrStr(model.NewId()),
   948  				},
   949  			},
   950  		},
   951  	}
   952  	if err := th.App.ImportUser(&data, false); err == nil {
   953  		t.Fatalf("Should have failed.")
   954  	}
   955  
   956  	// Check only new team member object created because dry run mode.
   957  	if tmc, err := th.App.GetTeamMembers(team.Id, 0, 1000); err != nil {
   958  		t.Fatalf("Failed to get Team Member Count")
   959  	} else if len(tmc) != teamMemberCount+1 {
   960  		t.Fatalf("Number of team members not as expected")
   961  	}
   962  
   963  	if cmc, err := th.App.GetChannelMemberCount(channel.Id); err != nil {
   964  		t.Fatalf("Failed to get Channel Member Count")
   965  	} else if cmc != channelMemberCount {
   966  		t.Fatalf("Number of channel members not as expected")
   967  	}
   968  
   969  	// Check team member properties.
   970  	user, err := th.App.GetUserByUsername(username)
   971  	if err != nil {
   972  		t.Fatalf("Failed to get user from database.")
   973  	}
   974  	if teamMember, err := th.App.GetTeamMember(team.Id, user.Id); err != nil {
   975  		t.Fatalf("Failed to get team member from database.")
   976  	} else if teamMember.Roles != "team_user" {
   977  		t.Fatalf("Team member properties not as expected")
   978  	}
   979  
   980  	// Test with a valid team & valid channel name in apply mode.
   981  	data.Teams = &[]UserTeamImportData{
   982  		{
   983  			Name: &teamName,
   984  			Channels: &[]UserChannelImportData{
   985  				{
   986  					Name: &channelName,
   987  				},
   988  			},
   989  		},
   990  	}
   991  	if err := th.App.ImportUser(&data, false); err != nil {
   992  		t.Fatalf("Should have succeeded.")
   993  	}
   994  
   995  	// Check only new channel member object created because dry run mode.
   996  	if tmc, err := th.App.GetTeamMembers(team.Id, 0, 1000); err != nil {
   997  		t.Fatalf("Failed to get Team Member Count")
   998  	} else if len(tmc) != teamMemberCount+1 {
   999  		t.Fatalf("Number of team members not as expected")
  1000  	}
  1001  
  1002  	if cmc, err := th.App.GetChannelMemberCount(channel.Id); err != nil {
  1003  		t.Fatalf("Failed to get Channel Member Count")
  1004  	} else if cmc != channelMemberCount+1 {
  1005  		t.Fatalf("Number of channel members not as expected")
  1006  	}
  1007  
  1008  	// Check channel member properties.
  1009  	if channelMember, err := th.App.GetChannelMember(channel.Id, user.Id); err != nil {
  1010  		t.Fatalf("Failed to get channel member from database.")
  1011  	} else if channelMember.Roles != "channel_user" || channelMember.NotifyProps[model.DESKTOP_NOTIFY_PROP] != "default" || channelMember.NotifyProps[model.PUSH_NOTIFY_PROP] != "default" || channelMember.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP] != "all" {
  1012  		t.Fatalf("Channel member properties not as expected")
  1013  	}
  1014  
  1015  	// Test with the properties of the team and channel membership changed.
  1016  	data.Teams = &[]UserTeamImportData{
  1017  		{
  1018  			Name:  &teamName,
  1019  			Theme: ptrStr(`{"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"}`),
  1020  			Roles: ptrStr("team_user team_admin"),
  1021  			Channels: &[]UserChannelImportData{
  1022  				{
  1023  					Name:  &channelName,
  1024  					Roles: ptrStr("channel_user channel_admin"),
  1025  					NotifyProps: &UserChannelNotifyPropsImportData{
  1026  						Desktop:    ptrStr(model.USER_NOTIFY_MENTION),
  1027  						Mobile:     ptrStr(model.USER_NOTIFY_MENTION),
  1028  						MarkUnread: ptrStr(model.USER_NOTIFY_MENTION),
  1029  					},
  1030  					Favorite: ptrBool(true),
  1031  				},
  1032  			},
  1033  		},
  1034  	}
  1035  	if err := th.App.ImportUser(&data, false); err != nil {
  1036  		t.Fatalf("Should have succeeded.")
  1037  	}
  1038  
  1039  	// Check both member properties.
  1040  	if teamMember, err := th.App.GetTeamMember(team.Id, user.Id); err != nil {
  1041  		t.Fatalf("Failed to get team member from database.")
  1042  	} else if teamMember.Roles != "team_user team_admin" {
  1043  		t.Fatalf("Team member properties not as expected: %v", teamMember.Roles)
  1044  	}
  1045  
  1046  	if channelMember, err := th.App.GetChannelMember(channel.Id, user.Id); err != nil {
  1047  		t.Fatalf("Failed to get channel member Desktop from database.")
  1048  	} else if channelMember.Roles != "channel_user channel_admin" || channelMember.NotifyProps[model.DESKTOP_NOTIFY_PROP] != model.USER_NOTIFY_MENTION || channelMember.NotifyProps[model.PUSH_NOTIFY_PROP] != model.USER_NOTIFY_MENTION || channelMember.NotifyProps[model.MARK_UNREAD_NOTIFY_PROP] != model.USER_NOTIFY_MENTION {
  1049  		t.Fatalf("Channel member properties not as expected")
  1050  	}
  1051  
  1052  	checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id, "true")
  1053  	checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_THEME, team.Id, *(*data.Teams)[0].Theme)
  1054  
  1055  	// No more new member objects.
  1056  	if tmc, err := th.App.GetTeamMembers(team.Id, 0, 1000); err != nil {
  1057  		t.Fatalf("Failed to get Team Member Count")
  1058  	} else if len(tmc) != teamMemberCount+1 {
  1059  		t.Fatalf("Number of team members not as expected")
  1060  	}
  1061  
  1062  	if cmc, err := th.App.GetChannelMemberCount(channel.Id); err != nil {
  1063  		t.Fatalf("Failed to get Channel Member Count")
  1064  	} else if cmc != channelMemberCount+1 {
  1065  		t.Fatalf("Number of channel members not as expected")
  1066  	}
  1067  
  1068  	// Add a user with some preferences.
  1069  	username = model.NewId()
  1070  	data = UserImportData{
  1071  		Username:           &username,
  1072  		Email:              ptrStr(model.NewId() + "@example.com"),
  1073  		Theme:              ptrStr(`{"awayIndicator":"#DCBD4E","buttonBg":"#23A2FF","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"}`),
  1074  		UseMilitaryTime:    ptrStr("true"),
  1075  		CollapsePreviews:   ptrStr("true"),
  1076  		MessageDisplay:     ptrStr("compact"),
  1077  		ChannelDisplayMode: ptrStr("centered"),
  1078  		TutorialStep:       ptrStr("3"),
  1079  		UseMarkdownPreview: ptrStr("true"),
  1080  		UseFormatting:      ptrStr("true"),
  1081  		ShowUnreadSection:  ptrStr("true"),
  1082  	}
  1083  	if err := th.App.ImportUser(&data, false); err != nil {
  1084  		t.Fatalf("Should have succeeded.")
  1085  	}
  1086  
  1087  	// Check their values.
  1088  	user, err = th.App.GetUserByUsername(username)
  1089  	if err != nil {
  1090  		t.Fatalf("Failed to get user from database.")
  1091  	}
  1092  
  1093  	checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_THEME, "", *data.Theme)
  1094  	checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_USE_MILITARY_TIME, *data.UseMilitaryTime)
  1095  	checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_COLLAPSE_SETTING, *data.CollapsePreviews)
  1096  	checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_MESSAGE_DISPLAY, *data.MessageDisplay)
  1097  	checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_CHANNEL_DISPLAY_MODE, *data.ChannelDisplayMode)
  1098  	checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, user.Id, *data.TutorialStep)
  1099  	checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, "feature_enabled_markdown_preview", *data.UseMarkdownPreview)
  1100  	checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_ADVANCED_SETTINGS, "formatting", *data.UseFormatting)
  1101  	checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_SIDEBAR_SETTINGS, "show_unread_section", *data.ShowUnreadSection)
  1102  
  1103  	// Change those preferences.
  1104  	data = UserImportData{
  1105  		Username:           &username,
  1106  		Email:              ptrStr(model.NewId() + "@example.com"),
  1107  		Theme:              ptrStr(`{"awayIndicator":"#123456","buttonBg":"#23A2FF","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"}`),
  1108  		UseMilitaryTime:    ptrStr("false"),
  1109  		CollapsePreviews:   ptrStr("false"),
  1110  		MessageDisplay:     ptrStr("clean"),
  1111  		ChannelDisplayMode: ptrStr("full"),
  1112  		TutorialStep:       ptrStr("2"),
  1113  	}
  1114  	if err := th.App.ImportUser(&data, false); err != nil {
  1115  		t.Fatalf("Should have succeeded.")
  1116  	}
  1117  
  1118  	// Check their values again.
  1119  	checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_THEME, "", *data.Theme)
  1120  	checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_USE_MILITARY_TIME, *data.UseMilitaryTime)
  1121  	checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_COLLAPSE_SETTING, *data.CollapsePreviews)
  1122  	checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_MESSAGE_DISPLAY, *data.MessageDisplay)
  1123  	checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_DISPLAY_SETTINGS, model.PREFERENCE_NAME_CHANNEL_DISPLAY_MODE, *data.ChannelDisplayMode)
  1124  	checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_TUTORIAL_STEPS, user.Id, *data.TutorialStep)
  1125  
  1126  	// Set Notify Props
  1127  	data.NotifyProps = &UserNotifyPropsImportData{
  1128  		Desktop:          ptrStr(model.USER_NOTIFY_ALL),
  1129  		DesktopSound:     ptrStr("true"),
  1130  		Email:            ptrStr("true"),
  1131  		Mobile:           ptrStr(model.USER_NOTIFY_ALL),
  1132  		MobilePushStatus: ptrStr(model.STATUS_ONLINE),
  1133  		ChannelTrigger:   ptrStr("true"),
  1134  		CommentsTrigger:  ptrStr(model.COMMENTS_NOTIFY_ROOT),
  1135  		MentionKeys:      ptrStr("valid,misc"),
  1136  	}
  1137  	if err := th.App.ImportUser(&data, false); err != nil {
  1138  		t.Fatalf("Should have succeeded.")
  1139  	}
  1140  
  1141  	user, err = th.App.GetUserByUsername(username)
  1142  	if err != nil {
  1143  		t.Fatalf("Failed to get user from database.")
  1144  	}
  1145  
  1146  	checkNotifyProp(t, user, model.DESKTOP_NOTIFY_PROP, model.USER_NOTIFY_ALL)
  1147  	checkNotifyProp(t, user, model.DESKTOP_SOUND_NOTIFY_PROP, "true")
  1148  	checkNotifyProp(t, user, model.EMAIL_NOTIFY_PROP, "true")
  1149  	checkNotifyProp(t, user, model.PUSH_NOTIFY_PROP, model.USER_NOTIFY_ALL)
  1150  	checkNotifyProp(t, user, model.PUSH_STATUS_NOTIFY_PROP, model.STATUS_ONLINE)
  1151  	checkNotifyProp(t, user, model.CHANNEL_MENTIONS_NOTIFY_PROP, "true")
  1152  	checkNotifyProp(t, user, model.COMMENTS_NOTIFY_PROP, model.COMMENTS_NOTIFY_ROOT)
  1153  	checkNotifyProp(t, user, model.MENTION_KEYS_NOTIFY_PROP, "valid,misc")
  1154  
  1155  	// Change Notify Props
  1156  	data.NotifyProps = &UserNotifyPropsImportData{
  1157  		Desktop:          ptrStr(model.USER_NOTIFY_MENTION),
  1158  		DesktopSound:     ptrStr("false"),
  1159  		Email:            ptrStr("false"),
  1160  		Mobile:           ptrStr(model.USER_NOTIFY_NONE),
  1161  		MobilePushStatus: ptrStr(model.STATUS_AWAY),
  1162  		ChannelTrigger:   ptrStr("false"),
  1163  		CommentsTrigger:  ptrStr(model.COMMENTS_NOTIFY_ANY),
  1164  		MentionKeys:      ptrStr("misc"),
  1165  	}
  1166  	if err := th.App.ImportUser(&data, false); err != nil {
  1167  		t.Fatalf("Should have succeeded.")
  1168  	}
  1169  
  1170  	user, err = th.App.GetUserByUsername(username)
  1171  	if err != nil {
  1172  		t.Fatalf("Failed to get user from database.")
  1173  	}
  1174  
  1175  	checkNotifyProp(t, user, model.DESKTOP_NOTIFY_PROP, model.USER_NOTIFY_MENTION)
  1176  	checkNotifyProp(t, user, model.DESKTOP_SOUND_NOTIFY_PROP, "false")
  1177  	checkNotifyProp(t, user, model.EMAIL_NOTIFY_PROP, "false")
  1178  	checkNotifyProp(t, user, model.PUSH_NOTIFY_PROP, model.USER_NOTIFY_NONE)
  1179  	checkNotifyProp(t, user, model.PUSH_STATUS_NOTIFY_PROP, model.STATUS_AWAY)
  1180  	checkNotifyProp(t, user, model.CHANNEL_MENTIONS_NOTIFY_PROP, "false")
  1181  	checkNotifyProp(t, user, model.COMMENTS_NOTIFY_PROP, model.COMMENTS_NOTIFY_ANY)
  1182  	checkNotifyProp(t, user, model.MENTION_KEYS_NOTIFY_PROP, "misc")
  1183  
  1184  	// Check Notify Props get set on *create* user.
  1185  	username = model.NewId()
  1186  	data = UserImportData{
  1187  		Username: &username,
  1188  		Email:    ptrStr(model.NewId() + "@example.com"),
  1189  	}
  1190  	data.NotifyProps = &UserNotifyPropsImportData{
  1191  		Desktop:          ptrStr(model.USER_NOTIFY_MENTION),
  1192  		DesktopSound:     ptrStr("false"),
  1193  		Email:            ptrStr("false"),
  1194  		Mobile:           ptrStr(model.USER_NOTIFY_NONE),
  1195  		MobilePushStatus: ptrStr(model.STATUS_AWAY),
  1196  		ChannelTrigger:   ptrStr("false"),
  1197  		CommentsTrigger:  ptrStr(model.COMMENTS_NOTIFY_ANY),
  1198  		MentionKeys:      ptrStr("misc"),
  1199  	}
  1200  
  1201  	if err := th.App.ImportUser(&data, false); err != nil {
  1202  		t.Fatalf("Should have succeeded.")
  1203  	}
  1204  
  1205  	user, err = th.App.GetUserByUsername(username)
  1206  	if err != nil {
  1207  		t.Fatalf("Failed to get user from database.")
  1208  	}
  1209  
  1210  	checkNotifyProp(t, user, model.DESKTOP_NOTIFY_PROP, model.USER_NOTIFY_MENTION)
  1211  	checkNotifyProp(t, user, model.DESKTOP_SOUND_NOTIFY_PROP, "false")
  1212  	checkNotifyProp(t, user, model.EMAIL_NOTIFY_PROP, "false")
  1213  	checkNotifyProp(t, user, model.PUSH_NOTIFY_PROP, model.USER_NOTIFY_NONE)
  1214  	checkNotifyProp(t, user, model.PUSH_STATUS_NOTIFY_PROP, model.STATUS_AWAY)
  1215  	checkNotifyProp(t, user, model.CHANNEL_MENTIONS_NOTIFY_PROP, "false")
  1216  	checkNotifyProp(t, user, model.COMMENTS_NOTIFY_PROP, model.COMMENTS_NOTIFY_ANY)
  1217  	checkNotifyProp(t, user, model.MENTION_KEYS_NOTIFY_PROP, "misc")
  1218  
  1219  	// Test importing a user with roles set to a team and a channel which are affected by an override scheme.
  1220  	// The import subsystem should translate `channel_admin/channel_user/team_admin/team_user`
  1221  	// to the appropriate scheme-managed-role booleans.
  1222  
  1223  	// Mark the phase 2 permissions migration as completed.
  1224  	<-th.App.Srv.Store.System().Save(&model.System{Name: model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2, Value: "true"})
  1225  
  1226  	defer func() {
  1227  		<-th.App.Srv.Store.System().PermanentDeleteByName(model.MIGRATION_KEY_ADVANCED_PERMISSIONS_PHASE_2)
  1228  	}()
  1229  
  1230  	teamSchemeData := &SchemeImportData{
  1231  		Name:        ptrStr(model.NewId()),
  1232  		DisplayName: ptrStr(model.NewId()),
  1233  		Scope:       ptrStr("team"),
  1234  		DefaultTeamUserRole: &RoleImportData{
  1235  			Name:        ptrStr(model.NewId()),
  1236  			DisplayName: ptrStr(model.NewId()),
  1237  		},
  1238  		DefaultTeamAdminRole: &RoleImportData{
  1239  			Name:        ptrStr(model.NewId()),
  1240  			DisplayName: ptrStr(model.NewId()),
  1241  		},
  1242  		DefaultChannelUserRole: &RoleImportData{
  1243  			Name:        ptrStr(model.NewId()),
  1244  			DisplayName: ptrStr(model.NewId()),
  1245  		},
  1246  		DefaultChannelAdminRole: &RoleImportData{
  1247  			Name:        ptrStr(model.NewId()),
  1248  			DisplayName: ptrStr(model.NewId()),
  1249  		},
  1250  		Description: ptrStr("description"),
  1251  	}
  1252  
  1253  	if err := th.App.ImportScheme(teamSchemeData, false); err != nil {
  1254  		t.Fatalf("Should have succeeded.")
  1255  	}
  1256  
  1257  	var teamScheme *model.Scheme
  1258  	if res := <-th.App.Srv.Store.Scheme().GetByName(*teamSchemeData.Name); res.Err != nil {
  1259  		t.Fatalf("Failed to import scheme: %v", res.Err)
  1260  	} else {
  1261  		teamScheme = res.Data.(*model.Scheme)
  1262  	}
  1263  
  1264  	teamData := &TeamImportData{
  1265  		Name:            ptrStr(model.NewId()),
  1266  		DisplayName:     ptrStr("Display Name"),
  1267  		Type:            ptrStr("O"),
  1268  		Description:     ptrStr("The team description."),
  1269  		AllowOpenInvite: ptrBool(true),
  1270  		Scheme:          &teamScheme.Name,
  1271  	}
  1272  	if err := th.App.ImportTeam(teamData, false); err != nil {
  1273  		t.Fatalf("Import should have succeeded: %v", err.Error())
  1274  	}
  1275  	team, err = th.App.GetTeamByName(teamName)
  1276  	if err != nil {
  1277  		t.Fatalf("Failed to get team from database.")
  1278  	}
  1279  
  1280  	channelData := &ChannelImportData{
  1281  		Team:        &teamName,
  1282  		Name:        ptrStr(model.NewId()),
  1283  		DisplayName: ptrStr("Display Name"),
  1284  		Type:        ptrStr("O"),
  1285  		Header:      ptrStr("Channe Header"),
  1286  		Purpose:     ptrStr("Channel Purpose"),
  1287  	}
  1288  	if err := th.App.ImportChannel(channelData, false); err != nil {
  1289  		t.Fatalf("Import should have succeeded.")
  1290  	}
  1291  	channel, err = th.App.GetChannelByName(*channelData.Name, team.Id, false)
  1292  	if err != nil {
  1293  		t.Fatalf("Failed to get channel from database: %v", err.Error())
  1294  	}
  1295  
  1296  	// Test with a valid team & valid channel name in apply mode.
  1297  	userData := &UserImportData{
  1298  		Username: &username,
  1299  		Email:    ptrStr(model.NewId() + "@example.com"),
  1300  		Teams: &[]UserTeamImportData{
  1301  			{
  1302  				Name:  &team.Name,
  1303  				Roles: ptrStr("team_user team_admin"),
  1304  				Channels: &[]UserChannelImportData{
  1305  					{
  1306  						Name:  &channel.Name,
  1307  						Roles: ptrStr("channel_admin channel_user"),
  1308  					},
  1309  				},
  1310  			},
  1311  		},
  1312  	}
  1313  	if err := th.App.ImportUser(userData, false); err != nil {
  1314  		t.Fatalf("Should have succeeded.")
  1315  	}
  1316  
  1317  	user, err = th.App.GetUserByUsername(*userData.Username)
  1318  	if err != nil {
  1319  		t.Fatalf("Failed to get user from database.")
  1320  	}
  1321  
  1322  	teamMember, err := th.App.GetTeamMember(team.Id, user.Id)
  1323  	if err != nil {
  1324  		t.Fatalf("Failed to get the team member")
  1325  	}
  1326  	assert.True(t, teamMember.SchemeAdmin)
  1327  	assert.True(t, teamMember.SchemeUser)
  1328  	assert.Equal(t, "", teamMember.ExplicitRoles)
  1329  
  1330  	channelMember, err := th.App.GetChannelMember(channel.Id, user.Id)
  1331  	if err != nil {
  1332  		t.Fatalf("Failed to get the channel member")
  1333  	}
  1334  	assert.True(t, channelMember.SchemeAdmin)
  1335  	assert.True(t, channelMember.SchemeUser)
  1336  	assert.Equal(t, "", channelMember.ExplicitRoles)
  1337  
  1338  }
  1339  
  1340  func TestImportImportPost(t *testing.T) {
  1341  	th := Setup()
  1342  	defer th.TearDown()
  1343  
  1344  	// Create a Team.
  1345  	teamName := model.NewId()
  1346  	th.App.ImportTeam(&TeamImportData{
  1347  		Name:        &teamName,
  1348  		DisplayName: ptrStr("Display Name"),
  1349  		Type:        ptrStr("O"),
  1350  	}, false)
  1351  	team, err := th.App.GetTeamByName(teamName)
  1352  	if err != nil {
  1353  		t.Fatalf("Failed to get team from database.")
  1354  	}
  1355  
  1356  	// Create a Channel.
  1357  	channelName := model.NewId()
  1358  	th.App.ImportChannel(&ChannelImportData{
  1359  		Team:        &teamName,
  1360  		Name:        &channelName,
  1361  		DisplayName: ptrStr("Display Name"),
  1362  		Type:        ptrStr("O"),
  1363  	}, false)
  1364  	channel, err := th.App.GetChannelByName(channelName, team.Id, false)
  1365  	if err != nil {
  1366  		t.Fatalf("Failed to get channel from database.")
  1367  	}
  1368  
  1369  	// Create a user.
  1370  	username := model.NewId()
  1371  	th.App.ImportUser(&UserImportData{
  1372  		Username: &username,
  1373  		Email:    ptrStr(model.NewId() + "@example.com"),
  1374  	}, false)
  1375  	user, err := th.App.GetUserByUsername(username)
  1376  	if err != nil {
  1377  		t.Fatalf("Failed to get user from database.")
  1378  	}
  1379  
  1380  	// Count the number of posts in the testing team.
  1381  	var initialPostCount int64
  1382  	if result := <-th.App.Srv.Store.Post().AnalyticsPostCount(team.Id, false, false); result.Err != nil {
  1383  		t.Fatal(result.Err)
  1384  	} else {
  1385  		initialPostCount = result.Data.(int64)
  1386  	}
  1387  
  1388  	// Try adding an invalid post in dry run mode.
  1389  	data := &PostImportData{
  1390  		Team:    &teamName,
  1391  		Channel: &channelName,
  1392  		User:    &username,
  1393  	}
  1394  	if err := th.App.ImportPost(data, true); err == nil {
  1395  		t.Fatalf("Expected error.")
  1396  	}
  1397  	AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id)
  1398  
  1399  	// Try adding a valid post in dry run mode.
  1400  	data = &PostImportData{
  1401  		Team:     &teamName,
  1402  		Channel:  &channelName,
  1403  		User:     &username,
  1404  		Message:  ptrStr("Hello"),
  1405  		CreateAt: ptrInt64(model.GetMillis()),
  1406  	}
  1407  	if err := th.App.ImportPost(data, true); err != nil {
  1408  		t.Fatalf("Expected success.")
  1409  	}
  1410  	AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id)
  1411  
  1412  	// Try adding an invalid post in apply mode.
  1413  	data = &PostImportData{
  1414  		Team:     &teamName,
  1415  		Channel:  &channelName,
  1416  		User:     &username,
  1417  		CreateAt: ptrInt64(model.GetMillis()),
  1418  	}
  1419  	if err := th.App.ImportPost(data, false); err == nil {
  1420  		t.Fatalf("Expected error.")
  1421  	}
  1422  	AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id)
  1423  
  1424  	// Try adding a valid post with invalid team in apply mode.
  1425  	data = &PostImportData{
  1426  		Team:     ptrStr(model.NewId()),
  1427  		Channel:  &channelName,
  1428  		User:     &username,
  1429  		Message:  ptrStr("Message"),
  1430  		CreateAt: ptrInt64(model.GetMillis()),
  1431  	}
  1432  	if err := th.App.ImportPost(data, false); err == nil {
  1433  		t.Fatalf("Expected error.")
  1434  	}
  1435  	AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id)
  1436  
  1437  	// Try adding a valid post with invalid channel in apply mode.
  1438  	data = &PostImportData{
  1439  		Team:     &teamName,
  1440  		Channel:  ptrStr(model.NewId()),
  1441  		User:     &username,
  1442  		Message:  ptrStr("Message"),
  1443  		CreateAt: ptrInt64(model.GetMillis()),
  1444  	}
  1445  	if err := th.App.ImportPost(data, false); err == nil {
  1446  		t.Fatalf("Expected error.")
  1447  	}
  1448  	AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id)
  1449  
  1450  	// Try adding a valid post with invalid user in apply mode.
  1451  	data = &PostImportData{
  1452  		Team:     &teamName,
  1453  		Channel:  &channelName,
  1454  		User:     ptrStr(model.NewId()),
  1455  		Message:  ptrStr("Message"),
  1456  		CreateAt: ptrInt64(model.GetMillis()),
  1457  	}
  1458  	if err := th.App.ImportPost(data, false); err == nil {
  1459  		t.Fatalf("Expected error.")
  1460  	}
  1461  	AssertAllPostsCount(t, th.App, initialPostCount, 0, team.Id)
  1462  
  1463  	// Try adding a valid post in apply mode.
  1464  	time := model.GetMillis()
  1465  	data = &PostImportData{
  1466  		Team:     &teamName,
  1467  		Channel:  &channelName,
  1468  		User:     &username,
  1469  		Message:  ptrStr("Message"),
  1470  		CreateAt: &time,
  1471  	}
  1472  	if err := th.App.ImportPost(data, false); err != nil {
  1473  		t.Fatalf("Expected success.")
  1474  	}
  1475  	AssertAllPostsCount(t, th.App, initialPostCount, 1, team.Id)
  1476  
  1477  	// Check the post values.
  1478  	if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(channel.Id, time); result.Err != nil {
  1479  		t.Fatal(result.Err.Error())
  1480  	} else {
  1481  		posts := result.Data.([]*model.Post)
  1482  		if len(posts) != 1 {
  1483  			t.Fatal("Unexpected number of posts found.")
  1484  		}
  1485  		post := posts[0]
  1486  		if post.Message != *data.Message || post.CreateAt != *data.CreateAt || post.UserId != user.Id {
  1487  			t.Fatal("Post properties not as expected")
  1488  		}
  1489  	}
  1490  
  1491  	// Update the post.
  1492  	data = &PostImportData{
  1493  		Team:     &teamName,
  1494  		Channel:  &channelName,
  1495  		User:     &username,
  1496  		Message:  ptrStr("Message"),
  1497  		CreateAt: &time,
  1498  	}
  1499  	if err := th.App.ImportPost(data, false); err != nil {
  1500  		t.Fatalf("Expected success.")
  1501  	}
  1502  	AssertAllPostsCount(t, th.App, initialPostCount, 1, team.Id)
  1503  
  1504  	// Check the post values.
  1505  	if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(channel.Id, time); result.Err != nil {
  1506  		t.Fatal(result.Err.Error())
  1507  	} else {
  1508  		posts := result.Data.([]*model.Post)
  1509  		if len(posts) != 1 {
  1510  			t.Fatal("Unexpected number of posts found.")
  1511  		}
  1512  		post := posts[0]
  1513  		if post.Message != *data.Message || post.CreateAt != *data.CreateAt || post.UserId != user.Id {
  1514  			t.Fatal("Post properties not as expected")
  1515  		}
  1516  	}
  1517  
  1518  	// Save the post with a different time.
  1519  	newTime := time + 1
  1520  	data = &PostImportData{
  1521  		Team:     &teamName,
  1522  		Channel:  &channelName,
  1523  		User:     &username,
  1524  		Message:  ptrStr("Message"),
  1525  		CreateAt: &newTime,
  1526  	}
  1527  	if err := th.App.ImportPost(data, false); err != nil {
  1528  		t.Fatalf("Expected success.")
  1529  	}
  1530  	AssertAllPostsCount(t, th.App, initialPostCount, 2, team.Id)
  1531  
  1532  	// Save the post with a different message.
  1533  	data = &PostImportData{
  1534  		Team:     &teamName,
  1535  		Channel:  &channelName,
  1536  		User:     &username,
  1537  		Message:  ptrStr("Message 2"),
  1538  		CreateAt: &time,
  1539  	}
  1540  	if err := th.App.ImportPost(data, false); err != nil {
  1541  		t.Fatalf("Expected success.")
  1542  	}
  1543  	AssertAllPostsCount(t, th.App, initialPostCount, 3, team.Id)
  1544  
  1545  	// Test with hashtags
  1546  	hashtagTime := time + 2
  1547  	data = &PostImportData{
  1548  		Team:     &teamName,
  1549  		Channel:  &channelName,
  1550  		User:     &username,
  1551  		Message:  ptrStr("Message 2 #hashtagmashupcity"),
  1552  		CreateAt: &hashtagTime,
  1553  	}
  1554  	if err := th.App.ImportPost(data, false); err != nil {
  1555  		t.Fatalf("Expected success.")
  1556  	}
  1557  	AssertAllPostsCount(t, th.App, initialPostCount, 4, team.Id)
  1558  
  1559  	if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(channel.Id, hashtagTime); result.Err != nil {
  1560  		t.Fatal(result.Err.Error())
  1561  	} else {
  1562  		posts := result.Data.([]*model.Post)
  1563  		if len(posts) != 1 {
  1564  			t.Fatal("Unexpected number of posts found.")
  1565  		}
  1566  		post := posts[0]
  1567  		if post.Message != *data.Message || post.CreateAt != *data.CreateAt || post.UserId != user.Id {
  1568  			t.Fatal("Post properties not as expected")
  1569  		}
  1570  		if post.Hashtags != "#hashtagmashupcity" {
  1571  			t.Fatalf("Hashtags not as expected: %s", post.Hashtags)
  1572  		}
  1573  	}
  1574  
  1575  	// Post with flags.
  1576  	username2 := model.NewId()
  1577  	th.App.ImportUser(&UserImportData{
  1578  		Username: &username2,
  1579  		Email:    ptrStr(model.NewId() + "@example.com"),
  1580  	}, false)
  1581  	user2, err := th.App.GetUserByUsername(username2)
  1582  	if err != nil {
  1583  		t.Fatalf("Failed to get user from database.")
  1584  	}
  1585  
  1586  	flagsTime := hashtagTime + 1
  1587  	data = &PostImportData{
  1588  		Team:     &teamName,
  1589  		Channel:  &channelName,
  1590  		User:     &username,
  1591  		Message:  ptrStr("Message with Favorites"),
  1592  		CreateAt: &flagsTime,
  1593  		FlaggedBy: &[]string{
  1594  			username,
  1595  			username2,
  1596  		},
  1597  	}
  1598  	if err := th.App.ImportPost(data, false); err != nil {
  1599  		t.Fatalf("Expected success.")
  1600  	}
  1601  	AssertAllPostsCount(t, th.App, initialPostCount, 5, team.Id)
  1602  
  1603  	// Check the post values.
  1604  	if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(channel.Id, flagsTime); result.Err != nil {
  1605  		t.Fatal(result.Err.Error())
  1606  	} else {
  1607  		posts := result.Data.([]*model.Post)
  1608  		if len(posts) != 1 {
  1609  			t.Fatal("Unexpected number of posts found.")
  1610  		}
  1611  		post := posts[0]
  1612  		if post.Message != *data.Message || post.CreateAt != *data.CreateAt || post.UserId != user.Id {
  1613  			t.Fatal("Post properties not as expected")
  1614  		}
  1615  
  1616  		checkPreference(t, th.App, user.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true")
  1617  		checkPreference(t, th.App, user2.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true")
  1618  	}
  1619  
  1620  	// Post with reaction.
  1621  	reactionPostTime := hashtagTime + 2
  1622  	reactionTime := hashtagTime + 3
  1623  	data = &PostImportData{
  1624  		Team:     &teamName,
  1625  		Channel:  &channelName,
  1626  		User:     &username,
  1627  		Message:  ptrStr("Message with reaction"),
  1628  		CreateAt: &reactionPostTime,
  1629  		Reactions: &[]ReactionImportData{{
  1630  			User:      &user2.Username,
  1631  			EmojiName: ptrStr("+1"),
  1632  			CreateAt:  &reactionTime,
  1633  		}},
  1634  	}
  1635  	if err := th.App.ImportPost(data, false); err != nil {
  1636  		t.Fatalf("Expected success.")
  1637  	}
  1638  	AssertAllPostsCount(t, th.App, initialPostCount, 6, team.Id)
  1639  
  1640  	// Check the post values.
  1641  	if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(channel.Id, reactionPostTime); result.Err != nil {
  1642  		t.Fatal(result.Err.Error())
  1643  	} else {
  1644  		posts := result.Data.([]*model.Post)
  1645  		if len(posts) != 1 {
  1646  			t.Fatal("Unexpected number of posts found.")
  1647  		}
  1648  		post := posts[0]
  1649  		if post.Message != *data.Message || post.CreateAt != *data.CreateAt || post.UserId != user.Id || !post.HasReactions {
  1650  			t.Fatal("Post properties not as expected")
  1651  		}
  1652  
  1653  		if result := <-th.App.Srv.Store.Reaction().GetForPost(post.Id, false); result.Err != nil {
  1654  			t.Fatal("Can't get reaction")
  1655  		} else if len(result.Data.([]*model.Reaction)) != 1 {
  1656  			t.Fatal("Invalid number of reactions")
  1657  		}
  1658  	}
  1659  
  1660  	// Post with reply.
  1661  	replyPostTime := hashtagTime + 4
  1662  	replyTime := hashtagTime + 5
  1663  	data = &PostImportData{
  1664  		Team:     &teamName,
  1665  		Channel:  &channelName,
  1666  		User:     &username,
  1667  		Message:  ptrStr("Message with reply"),
  1668  		CreateAt: &replyPostTime,
  1669  		Replies: &[]ReplyImportData{{
  1670  			User:     &user2.Username,
  1671  			Message:  ptrStr("Message reply"),
  1672  			CreateAt: &replyTime,
  1673  		}},
  1674  	}
  1675  	if err := th.App.ImportPost(data, false); err != nil {
  1676  		t.Fatalf("Expected success.")
  1677  	}
  1678  	AssertAllPostsCount(t, th.App, initialPostCount, 8, team.Id)
  1679  
  1680  	// Check the post values.
  1681  	if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(channel.Id, replyPostTime); result.Err != nil {
  1682  		t.Fatal(result.Err.Error())
  1683  	} else {
  1684  		posts := result.Data.([]*model.Post)
  1685  		if len(posts) != 1 {
  1686  			t.Fatal("Unexpected number of posts found.")
  1687  		}
  1688  		post := posts[0]
  1689  		if post.Message != *data.Message || post.CreateAt != *data.CreateAt || post.UserId != user.Id {
  1690  			t.Fatal("Post properties not as expected")
  1691  		}
  1692  
  1693  		// Check the reply values.
  1694  		if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(channel.Id, replyTime); result.Err != nil {
  1695  			t.Fatal(result.Err.Error())
  1696  		} else {
  1697  			replies := result.Data.([]*model.Post)
  1698  			if len(replies) != 1 {
  1699  				t.Fatal("Unexpected number of posts found.")
  1700  			}
  1701  			reply := replies[0]
  1702  			if reply.Message != *(*data.Replies)[0].Message || reply.CreateAt != *(*data.Replies)[0].CreateAt || reply.UserId != user2.Id {
  1703  				t.Fatal("Post properties not as expected")
  1704  			}
  1705  
  1706  			if reply.RootId != post.Id {
  1707  				t.Fatal("Unexpected reply RootId")
  1708  			}
  1709  		}
  1710  	}
  1711  
  1712  	// Update post with replies.
  1713  	data = &PostImportData{
  1714  		Team:     &teamName,
  1715  		Channel:  &channelName,
  1716  		User:     &user2.Username,
  1717  		Message:  ptrStr("Message with reply"),
  1718  		CreateAt: &replyPostTime,
  1719  		Replies: &[]ReplyImportData{{
  1720  			User:     &username,
  1721  			Message:  ptrStr("Message reply"),
  1722  			CreateAt: &replyTime,
  1723  		}},
  1724  	}
  1725  	if err := th.App.ImportPost(data, false); err != nil {
  1726  		t.Fatalf("Expected success.")
  1727  	}
  1728  	AssertAllPostsCount(t, th.App, initialPostCount, 8, team.Id)
  1729  
  1730  	// Create new post with replies based on the previous one.
  1731  	data = &PostImportData{
  1732  		Team:     &teamName,
  1733  		Channel:  &channelName,
  1734  		User:     &user2.Username,
  1735  		Message:  ptrStr("Message with reply 2"),
  1736  		CreateAt: &replyPostTime,
  1737  		Replies: &[]ReplyImportData{{
  1738  			User:     &username,
  1739  			Message:  ptrStr("Message reply"),
  1740  			CreateAt: &replyTime,
  1741  		}},
  1742  	}
  1743  	if err := th.App.ImportPost(data, false); err != nil {
  1744  		t.Fatalf("Expected success.")
  1745  	}
  1746  	AssertAllPostsCount(t, th.App, initialPostCount, 10, team.Id)
  1747  
  1748  	// Create new reply for existing post with replies.
  1749  	data = &PostImportData{
  1750  		Team:     &teamName,
  1751  		Channel:  &channelName,
  1752  		User:     &user2.Username,
  1753  		Message:  ptrStr("Message with reply"),
  1754  		CreateAt: &replyPostTime,
  1755  		Replies: &[]ReplyImportData{{
  1756  			User:     &username,
  1757  			Message:  ptrStr("Message reply 2"),
  1758  			CreateAt: &replyTime,
  1759  		}},
  1760  	}
  1761  	if err := th.App.ImportPost(data, false); err != nil {
  1762  		t.Fatalf("Expected success.")
  1763  	}
  1764  	AssertAllPostsCount(t, th.App, initialPostCount, 11, team.Id)
  1765  }
  1766  
  1767  func TestImportImportDirectChannel(t *testing.T) {
  1768  	th := Setup().InitBasic()
  1769  	defer th.TearDown()
  1770  
  1771  	// Check how many channels are in the database.
  1772  	var directChannelCount int64
  1773  	if r := <-th.App.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_DIRECT); r.Err == nil {
  1774  		directChannelCount = r.Data.(int64)
  1775  	} else {
  1776  		t.Fatalf("Failed to get direct channel count.")
  1777  	}
  1778  
  1779  	var groupChannelCount int64
  1780  	if r := <-th.App.Srv.Store.Channel().AnalyticsTypeCount("", model.CHANNEL_GROUP); r.Err == nil {
  1781  		groupChannelCount = r.Data.(int64)
  1782  	} else {
  1783  		t.Fatalf("Failed to get group channel count.")
  1784  	}
  1785  
  1786  	// Do an invalid channel in dry-run mode.
  1787  	data := DirectChannelImportData{
  1788  		Members: &[]string{
  1789  			model.NewId(),
  1790  		},
  1791  		Header: ptrStr("Channel Header"),
  1792  	}
  1793  	if err := th.App.ImportDirectChannel(&data, true); err == nil {
  1794  		t.Fatalf("Expected error due to invalid name.")
  1795  	}
  1796  
  1797  	// Check that no more channels are in the DB.
  1798  	AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount)
  1799  	AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount)
  1800  
  1801  	// Do a valid DIRECT channel with a nonexistent member in dry-run mode.
  1802  	data.Members = &[]string{
  1803  		model.NewId(),
  1804  		model.NewId(),
  1805  	}
  1806  	if err := th.App.ImportDirectChannel(&data, true); err != nil {
  1807  		t.Fatalf("Expected success as cannot validate existence of channel members in dry run mode.")
  1808  	}
  1809  
  1810  	// Check that no more channels are in the DB.
  1811  	AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount)
  1812  	AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount)
  1813  
  1814  	// Do a valid GROUP channel with a nonexistent member in dry-run mode.
  1815  	data.Members = &[]string{
  1816  		model.NewId(),
  1817  		model.NewId(),
  1818  		model.NewId(),
  1819  	}
  1820  	if err := th.App.ImportDirectChannel(&data, true); err != nil {
  1821  		t.Fatalf("Expected success as cannot validate existence of channel members in dry run mode.")
  1822  	}
  1823  
  1824  	// Check that no more channels are in the DB.
  1825  	AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount)
  1826  	AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount)
  1827  
  1828  	// Do an invalid channel in apply mode.
  1829  	data.Members = &[]string{
  1830  		model.NewId(),
  1831  	}
  1832  	if err := th.App.ImportDirectChannel(&data, false); err == nil {
  1833  		t.Fatalf("Expected error due to invalid member (apply mode).")
  1834  	}
  1835  
  1836  	// Check that no more channels are in the DB.
  1837  	AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount)
  1838  	AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount)
  1839  
  1840  	// Do a valid DIRECT channel.
  1841  	data.Members = &[]string{
  1842  		th.BasicUser.Username,
  1843  		th.BasicUser2.Username,
  1844  	}
  1845  	if err := th.App.ImportDirectChannel(&data, false); err != nil {
  1846  		t.Fatalf("Expected success: %v", err.Error())
  1847  	}
  1848  
  1849  	// Check that one more DIRECT channel is in the DB.
  1850  	AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1)
  1851  	AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount)
  1852  
  1853  	// Do the same DIRECT channel again.
  1854  	if err := th.App.ImportDirectChannel(&data, false); err != nil {
  1855  		t.Fatalf("Expected success.")
  1856  	}
  1857  
  1858  	// Check that no more channels are in the DB.
  1859  	AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1)
  1860  	AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount)
  1861  
  1862  	// Update the channel's HEADER
  1863  	data.Header = ptrStr("New Channel Header 2")
  1864  	if err := th.App.ImportDirectChannel(&data, false); err != nil {
  1865  		t.Fatalf("Expected success.")
  1866  	}
  1867  
  1868  	// Check that no more channels are in the DB.
  1869  	AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1)
  1870  	AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount)
  1871  
  1872  	// Get the channel to check that the header was updated.
  1873  	if channel, err := th.App.createDirectChannel(th.BasicUser.Id, th.BasicUser2.Id); err == nil || err.Id != store.CHANNEL_EXISTS_ERROR {
  1874  		t.Fatal("Should have got store.CHANNEL_EXISTS_ERROR")
  1875  	} else {
  1876  		if channel.Header != *data.Header {
  1877  			t.Fatal("Channel header has not been updated successfully.")
  1878  		}
  1879  	}
  1880  
  1881  	// Do a GROUP channel with an extra invalid member.
  1882  	user3 := th.CreateUser()
  1883  	data.Members = &[]string{
  1884  		th.BasicUser.Username,
  1885  		th.BasicUser2.Username,
  1886  		user3.Username,
  1887  		model.NewId(),
  1888  	}
  1889  	if err := th.App.ImportDirectChannel(&data, false); err == nil {
  1890  		t.Fatalf("Should have failed due to invalid member in list.")
  1891  	}
  1892  
  1893  	// Check that no more channels are in the DB.
  1894  	AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1)
  1895  	AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount)
  1896  
  1897  	// Do a valid GROUP channel.
  1898  	data.Members = &[]string{
  1899  		th.BasicUser.Username,
  1900  		th.BasicUser2.Username,
  1901  		user3.Username,
  1902  	}
  1903  	if err := th.App.ImportDirectChannel(&data, false); err != nil {
  1904  		t.Fatalf("Expected success.")
  1905  	}
  1906  
  1907  	// Check that one more GROUP channel is in the DB.
  1908  	AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1)
  1909  	AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount+1)
  1910  
  1911  	// Do the same DIRECT channel again.
  1912  	if err := th.App.ImportDirectChannel(&data, false); err != nil {
  1913  		t.Fatalf("Expected success.")
  1914  	}
  1915  
  1916  	// Check that no more channels are in the DB.
  1917  	AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1)
  1918  	AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount+1)
  1919  
  1920  	// Update the channel's HEADER
  1921  	data.Header = ptrStr("New Channel Header 3")
  1922  	if err := th.App.ImportDirectChannel(&data, false); err != nil {
  1923  		t.Fatalf("Expected success.")
  1924  	}
  1925  
  1926  	// Check that no more channels are in the DB.
  1927  	AssertChannelCount(t, th.App, model.CHANNEL_DIRECT, directChannelCount+1)
  1928  	AssertChannelCount(t, th.App, model.CHANNEL_GROUP, groupChannelCount+1)
  1929  
  1930  	// Get the channel to check that the header was updated.
  1931  	userIds := []string{
  1932  		th.BasicUser.Id,
  1933  		th.BasicUser2.Id,
  1934  		user3.Id,
  1935  	}
  1936  	if channel, err := th.App.createGroupChannel(userIds, th.BasicUser.Id); err.Id != store.CHANNEL_EXISTS_ERROR {
  1937  		t.Fatal("Should have got store.CHANNEL_EXISTS_ERROR")
  1938  	} else {
  1939  		if channel.Header != *data.Header {
  1940  			t.Fatal("Channel header has not been updated successfully.")
  1941  		}
  1942  	}
  1943  
  1944  	// Import a channel with some favorites.
  1945  	data.Members = &[]string{
  1946  		th.BasicUser.Username,
  1947  		th.BasicUser2.Username,
  1948  	}
  1949  	data.FavoritedBy = &[]string{
  1950  		th.BasicUser.Username,
  1951  		th.BasicUser2.Username,
  1952  	}
  1953  	if err := th.App.ImportDirectChannel(&data, false); err != nil {
  1954  		t.Fatal(err)
  1955  	}
  1956  
  1957  	if channel, err := th.App.createDirectChannel(th.BasicUser.Id, th.BasicUser2.Id); err == nil || err.Id != store.CHANNEL_EXISTS_ERROR {
  1958  		t.Fatal("Should have got store.CHANNEL_EXISTS_ERROR")
  1959  	} else {
  1960  		checkPreference(t, th.App, th.BasicUser.Id, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id, "true")
  1961  		checkPreference(t, th.App, th.BasicUser2.Id, model.PREFERENCE_CATEGORY_FAVORITE_CHANNEL, channel.Id, "true")
  1962  	}
  1963  }
  1964  
  1965  func TestImportImportDirectPost(t *testing.T) {
  1966  	th := Setup().InitBasic()
  1967  	defer th.TearDown()
  1968  
  1969  	// Create the DIRECT channel.
  1970  	channelData := DirectChannelImportData{
  1971  		Members: &[]string{
  1972  			th.BasicUser.Username,
  1973  			th.BasicUser2.Username,
  1974  		},
  1975  	}
  1976  	if err := th.App.ImportDirectChannel(&channelData, false); err != nil {
  1977  		t.Fatalf("Expected success: %v", err.Error())
  1978  	}
  1979  
  1980  	// Get the channel.
  1981  	var directChannel *model.Channel
  1982  	if channel, err := th.App.createDirectChannel(th.BasicUser.Id, th.BasicUser2.Id); err.Id != store.CHANNEL_EXISTS_ERROR {
  1983  		t.Fatal("Should have got store.CHANNEL_EXISTS_ERROR")
  1984  	} else {
  1985  		directChannel = channel
  1986  	}
  1987  
  1988  	// Get the number of posts in the system.
  1989  	var initialPostCount int64
  1990  	if result := <-th.App.Srv.Store.Post().AnalyticsPostCount("", false, false); result.Err != nil {
  1991  		t.Fatal(result.Err)
  1992  	} else {
  1993  		initialPostCount = result.Data.(int64)
  1994  	}
  1995  
  1996  	// Try adding an invalid post in dry run mode.
  1997  	data := &DirectPostImportData{
  1998  		ChannelMembers: &[]string{
  1999  			th.BasicUser.Username,
  2000  			th.BasicUser2.Username,
  2001  		},
  2002  		User:     ptrStr(th.BasicUser.Username),
  2003  		CreateAt: ptrInt64(model.GetMillis()),
  2004  	}
  2005  	if err := th.App.ImportDirectPost(data, true); err == nil {
  2006  		t.Fatalf("Expected error.")
  2007  	}
  2008  	AssertAllPostsCount(t, th.App, initialPostCount, 0, "")
  2009  
  2010  	// Try adding a valid post in dry run mode.
  2011  	data = &DirectPostImportData{
  2012  		ChannelMembers: &[]string{
  2013  			th.BasicUser.Username,
  2014  			th.BasicUser2.Username,
  2015  		},
  2016  		User:     ptrStr(th.BasicUser.Username),
  2017  		Message:  ptrStr("Message"),
  2018  		CreateAt: ptrInt64(model.GetMillis()),
  2019  	}
  2020  	if err := th.App.ImportDirectPost(data, true); err != nil {
  2021  		t.Fatalf("Expected success.")
  2022  	}
  2023  	AssertAllPostsCount(t, th.App, initialPostCount, 0, "")
  2024  
  2025  	// Try adding an invalid post in apply mode.
  2026  	data = &DirectPostImportData{
  2027  		ChannelMembers: &[]string{
  2028  			th.BasicUser.Username,
  2029  			model.NewId(),
  2030  		},
  2031  		User:     ptrStr(th.BasicUser.Username),
  2032  		Message:  ptrStr("Message"),
  2033  		CreateAt: ptrInt64(model.GetMillis()),
  2034  	}
  2035  	if err := th.App.ImportDirectPost(data, false); err == nil {
  2036  		t.Fatalf("Expected error.")
  2037  	}
  2038  	AssertAllPostsCount(t, th.App, initialPostCount, 0, "")
  2039  
  2040  	// Try adding a valid post in apply mode.
  2041  	data = &DirectPostImportData{
  2042  		ChannelMembers: &[]string{
  2043  			th.BasicUser.Username,
  2044  			th.BasicUser2.Username,
  2045  		},
  2046  		User:     ptrStr(th.BasicUser.Username),
  2047  		Message:  ptrStr("Message"),
  2048  		CreateAt: ptrInt64(model.GetMillis()),
  2049  	}
  2050  	if err := th.App.ImportDirectPost(data, false); err != nil {
  2051  		t.Fatalf("Expected success: %v", err.Error())
  2052  	}
  2053  	AssertAllPostsCount(t, th.App, initialPostCount, 1, "")
  2054  
  2055  	// Check the post values.
  2056  	if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt); result.Err != nil {
  2057  		t.Fatal(result.Err.Error())
  2058  	} else {
  2059  		posts := result.Data.([]*model.Post)
  2060  		if len(posts) != 1 {
  2061  			t.Fatal("Unexpected number of posts found.")
  2062  		}
  2063  		post := posts[0]
  2064  		if post.Message != *data.Message || post.CreateAt != *data.CreateAt || post.UserId != th.BasicUser.Id {
  2065  			t.Fatal("Post properties not as expected")
  2066  		}
  2067  	}
  2068  
  2069  	// Import the post again.
  2070  	if err := th.App.ImportDirectPost(data, false); err != nil {
  2071  		t.Fatalf("Expected success.")
  2072  	}
  2073  	AssertAllPostsCount(t, th.App, initialPostCount, 1, "")
  2074  
  2075  	// Check the post values.
  2076  	if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt); result.Err != nil {
  2077  		t.Fatal(result.Err.Error())
  2078  	} else {
  2079  		posts := result.Data.([]*model.Post)
  2080  		if len(posts) != 1 {
  2081  			t.Fatal("Unexpected number of posts found.")
  2082  		}
  2083  		post := posts[0]
  2084  		if post.Message != *data.Message || post.CreateAt != *data.CreateAt || post.UserId != th.BasicUser.Id {
  2085  			t.Fatal("Post properties not as expected")
  2086  		}
  2087  	}
  2088  
  2089  	// Save the post with a different time.
  2090  	data.CreateAt = ptrInt64(*data.CreateAt + 1)
  2091  	if err := th.App.ImportDirectPost(data, false); err != nil {
  2092  		t.Fatalf("Expected success.")
  2093  	}
  2094  	AssertAllPostsCount(t, th.App, initialPostCount, 2, "")
  2095  
  2096  	// Save the post with a different message.
  2097  	data.Message = ptrStr("Message 2")
  2098  	if err := th.App.ImportDirectPost(data, false); err != nil {
  2099  		t.Fatalf("Expected success.")
  2100  	}
  2101  	AssertAllPostsCount(t, th.App, initialPostCount, 3, "")
  2102  
  2103  	// Test with hashtags
  2104  	data.Message = ptrStr("Message 2 #hashtagmashupcity")
  2105  	data.CreateAt = ptrInt64(*data.CreateAt + 1)
  2106  	if err := th.App.ImportDirectPost(data, false); err != nil {
  2107  		t.Fatalf("Expected success.")
  2108  	}
  2109  	AssertAllPostsCount(t, th.App, initialPostCount, 4, "")
  2110  
  2111  	if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt); result.Err != nil {
  2112  		t.Fatal(result.Err.Error())
  2113  	} else {
  2114  		posts := result.Data.([]*model.Post)
  2115  		if len(posts) != 1 {
  2116  			t.Fatal("Unexpected number of posts found.")
  2117  		}
  2118  		post := posts[0]
  2119  		if post.Message != *data.Message || post.CreateAt != *data.CreateAt || post.UserId != th.BasicUser.Id {
  2120  			t.Fatal("Post properties not as expected")
  2121  		}
  2122  		if post.Hashtags != "#hashtagmashupcity" {
  2123  			t.Fatalf("Hashtags not as expected: %s", post.Hashtags)
  2124  		}
  2125  	}
  2126  
  2127  	// Test with some flags.
  2128  	data = &DirectPostImportData{
  2129  		ChannelMembers: &[]string{
  2130  			th.BasicUser.Username,
  2131  			th.BasicUser2.Username,
  2132  		},
  2133  		FlaggedBy: &[]string{
  2134  			th.BasicUser.Username,
  2135  			th.BasicUser2.Username,
  2136  		},
  2137  		User:     ptrStr(th.BasicUser.Username),
  2138  		Message:  ptrStr("Message"),
  2139  		CreateAt: ptrInt64(model.GetMillis()),
  2140  	}
  2141  
  2142  	if err := th.App.ImportDirectPost(data, false); err != nil {
  2143  		t.Fatalf("Expected success: %v", err.Error())
  2144  	}
  2145  
  2146  	// Check the post values.
  2147  	if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(directChannel.Id, *data.CreateAt); result.Err != nil {
  2148  		t.Fatal(result.Err.Error())
  2149  	} else {
  2150  		posts := result.Data.([]*model.Post)
  2151  		if len(posts) != 1 {
  2152  			t.Fatal("Unexpected number of posts found.")
  2153  		}
  2154  		post := posts[0]
  2155  		checkPreference(t, th.App, th.BasicUser.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true")
  2156  		checkPreference(t, th.App, th.BasicUser2.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true")
  2157  	}
  2158  
  2159  	// ------------------ Group Channel -------------------------
  2160  
  2161  	// Create the GROUP channel.
  2162  	user3 := th.CreateUser()
  2163  	channelData = DirectChannelImportData{
  2164  		Members: &[]string{
  2165  			th.BasicUser.Username,
  2166  			th.BasicUser2.Username,
  2167  			user3.Username,
  2168  		},
  2169  	}
  2170  	if err := th.App.ImportDirectChannel(&channelData, false); err != nil {
  2171  		t.Fatalf("Expected success: %v", err.Error())
  2172  	}
  2173  
  2174  	// Get the channel.
  2175  	var groupChannel *model.Channel
  2176  	userIds := []string{
  2177  		th.BasicUser.Id,
  2178  		th.BasicUser2.Id,
  2179  		user3.Id,
  2180  	}
  2181  	if channel, err := th.App.createGroupChannel(userIds, th.BasicUser.Id); err.Id != store.CHANNEL_EXISTS_ERROR {
  2182  		t.Fatal("Should have got store.CHANNEL_EXISTS_ERROR")
  2183  	} else {
  2184  		groupChannel = channel
  2185  	}
  2186  
  2187  	// Get the number of posts in the system.
  2188  	if result := <-th.App.Srv.Store.Post().AnalyticsPostCount("", false, false); result.Err != nil {
  2189  		t.Fatal(result.Err)
  2190  	} else {
  2191  		initialPostCount = result.Data.(int64)
  2192  	}
  2193  
  2194  	// Try adding an invalid post in dry run mode.
  2195  	data = &DirectPostImportData{
  2196  		ChannelMembers: &[]string{
  2197  			th.BasicUser.Username,
  2198  			th.BasicUser2.Username,
  2199  			user3.Username,
  2200  		},
  2201  		User:     ptrStr(th.BasicUser.Username),
  2202  		CreateAt: ptrInt64(model.GetMillis()),
  2203  	}
  2204  	if err := th.App.ImportDirectPost(data, true); err == nil {
  2205  		t.Fatalf("Expected error.")
  2206  	}
  2207  	AssertAllPostsCount(t, th.App, initialPostCount, 0, "")
  2208  
  2209  	// Try adding a valid post in dry run mode.
  2210  	data = &DirectPostImportData{
  2211  		ChannelMembers: &[]string{
  2212  			th.BasicUser.Username,
  2213  			th.BasicUser2.Username,
  2214  			user3.Username,
  2215  		},
  2216  		User:     ptrStr(th.BasicUser.Username),
  2217  		Message:  ptrStr("Message"),
  2218  		CreateAt: ptrInt64(model.GetMillis()),
  2219  	}
  2220  	if err := th.App.ImportDirectPost(data, true); err != nil {
  2221  		t.Fatalf("Expected success.")
  2222  	}
  2223  	AssertAllPostsCount(t, th.App, initialPostCount, 0, "")
  2224  
  2225  	// Try adding an invalid post in apply mode.
  2226  	data = &DirectPostImportData{
  2227  		ChannelMembers: &[]string{
  2228  			th.BasicUser.Username,
  2229  			th.BasicUser2.Username,
  2230  			user3.Username,
  2231  			model.NewId(),
  2232  		},
  2233  		User:     ptrStr(th.BasicUser.Username),
  2234  		Message:  ptrStr("Message"),
  2235  		CreateAt: ptrInt64(model.GetMillis()),
  2236  	}
  2237  	if err := th.App.ImportDirectPost(data, false); err == nil {
  2238  		t.Fatalf("Expected error.")
  2239  	}
  2240  	AssertAllPostsCount(t, th.App, initialPostCount, 0, "")
  2241  
  2242  	// Try adding a valid post in apply mode.
  2243  	data = &DirectPostImportData{
  2244  		ChannelMembers: &[]string{
  2245  			th.BasicUser.Username,
  2246  			th.BasicUser2.Username,
  2247  			user3.Username,
  2248  		},
  2249  		User:     ptrStr(th.BasicUser.Username),
  2250  		Message:  ptrStr("Message"),
  2251  		CreateAt: ptrInt64(model.GetMillis()),
  2252  	}
  2253  	if err := th.App.ImportDirectPost(data, false); err != nil {
  2254  		t.Fatalf("Expected success: %v", err.Error())
  2255  	}
  2256  	AssertAllPostsCount(t, th.App, initialPostCount, 1, "")
  2257  
  2258  	// Check the post values.
  2259  	if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt); result.Err != nil {
  2260  		t.Fatal(result.Err.Error())
  2261  	} else {
  2262  		posts := result.Data.([]*model.Post)
  2263  		if len(posts) != 1 {
  2264  			t.Fatal("Unexpected number of posts found.")
  2265  		}
  2266  		post := posts[0]
  2267  		if post.Message != *data.Message || post.CreateAt != *data.CreateAt || post.UserId != th.BasicUser.Id {
  2268  			t.Fatal("Post properties not as expected")
  2269  		}
  2270  	}
  2271  
  2272  	// Import the post again.
  2273  	if err := th.App.ImportDirectPost(data, false); err != nil {
  2274  		t.Fatalf("Expected success.")
  2275  	}
  2276  	AssertAllPostsCount(t, th.App, initialPostCount, 1, "")
  2277  
  2278  	// Check the post values.
  2279  	if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt); result.Err != nil {
  2280  		t.Fatal(result.Err.Error())
  2281  	} else {
  2282  		posts := result.Data.([]*model.Post)
  2283  		if len(posts) != 1 {
  2284  			t.Fatal("Unexpected number of posts found.")
  2285  		}
  2286  		post := posts[0]
  2287  		if post.Message != *data.Message || post.CreateAt != *data.CreateAt || post.UserId != th.BasicUser.Id {
  2288  			t.Fatal("Post properties not as expected")
  2289  		}
  2290  	}
  2291  
  2292  	// Save the post with a different time.
  2293  	data.CreateAt = ptrInt64(*data.CreateAt + 1)
  2294  	if err := th.App.ImportDirectPost(data, false); err != nil {
  2295  		t.Fatalf("Expected success.")
  2296  	}
  2297  	AssertAllPostsCount(t, th.App, initialPostCount, 2, "")
  2298  
  2299  	// Save the post with a different message.
  2300  	data.Message = ptrStr("Message 2")
  2301  	if err := th.App.ImportDirectPost(data, false); err != nil {
  2302  		t.Fatalf("Expected success.")
  2303  	}
  2304  	AssertAllPostsCount(t, th.App, initialPostCount, 3, "")
  2305  
  2306  	// Test with hashtags
  2307  	data.Message = ptrStr("Message 2 #hashtagmashupcity")
  2308  	data.CreateAt = ptrInt64(*data.CreateAt + 1)
  2309  	if err := th.App.ImportDirectPost(data, false); err != nil {
  2310  		t.Fatalf("Expected success.")
  2311  	}
  2312  	AssertAllPostsCount(t, th.App, initialPostCount, 4, "")
  2313  
  2314  	if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt); result.Err != nil {
  2315  		t.Fatal(result.Err.Error())
  2316  	} else {
  2317  		posts := result.Data.([]*model.Post)
  2318  		if len(posts) != 1 {
  2319  			t.Fatal("Unexpected number of posts found.")
  2320  		}
  2321  		post := posts[0]
  2322  		if post.Message != *data.Message || post.CreateAt != *data.CreateAt || post.UserId != th.BasicUser.Id {
  2323  			t.Fatal("Post properties not as expected")
  2324  		}
  2325  		if post.Hashtags != "#hashtagmashupcity" {
  2326  			t.Fatalf("Hashtags not as expected: %s", post.Hashtags)
  2327  		}
  2328  	}
  2329  
  2330  	// Test with some flags.
  2331  	data = &DirectPostImportData{
  2332  		ChannelMembers: &[]string{
  2333  			th.BasicUser.Username,
  2334  			th.BasicUser2.Username,
  2335  			user3.Username,
  2336  		},
  2337  		FlaggedBy: &[]string{
  2338  			th.BasicUser.Username,
  2339  			th.BasicUser2.Username,
  2340  		},
  2341  		User:     ptrStr(th.BasicUser.Username),
  2342  		Message:  ptrStr("Message"),
  2343  		CreateAt: ptrInt64(model.GetMillis()),
  2344  	}
  2345  
  2346  	if err := th.App.ImportDirectPost(data, false); err != nil {
  2347  		t.Fatalf("Expected success: %v", err.Error())
  2348  	}
  2349  
  2350  	// Check the post values.
  2351  	if result := <-th.App.Srv.Store.Post().GetPostsCreatedAt(groupChannel.Id, *data.CreateAt); result.Err != nil {
  2352  		t.Fatal(result.Err.Error())
  2353  	} else {
  2354  		posts := result.Data.([]*model.Post)
  2355  		if len(posts) != 1 {
  2356  			t.Fatal("Unexpected number of posts found.")
  2357  		}
  2358  		post := posts[0]
  2359  		checkPreference(t, th.App, th.BasicUser.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true")
  2360  		checkPreference(t, th.App, th.BasicUser2.Id, model.PREFERENCE_CATEGORY_FLAGGED_POST, post.Id, "true")
  2361  	}
  2362  }
  2363  
  2364  func TestImportImportEmoji(t *testing.T) {
  2365  	th := Setup()
  2366  	defer th.TearDown()
  2367  
  2368  	th.App.UpdateConfig(func(cfg *model.Config) { *cfg.ServiceSettings.EnableCustomEmoji = true })
  2369  
  2370  	testsDir, _ := utils.FindDir("tests")
  2371  	testImage := filepath.Join(testsDir, "test.png")
  2372  
  2373  	data := EmojiImportData{Name: ptrStr(model.NewId())}
  2374  	err := th.App.ImportEmoji(&data, true)
  2375  	assert.NotNil(t, err, "Invalid emoji should have failed dry run")
  2376  
  2377  	result := <-th.App.Srv.Store.Emoji().GetByName(*data.Name)
  2378  	assert.Nil(t, result.Data, "Emoji should not have been imported")
  2379  
  2380  	data.Image = ptrStr(testImage)
  2381  	err = th.App.ImportEmoji(&data, true)
  2382  	assert.Nil(t, err, "Valid emoji should have passed dry run")
  2383  
  2384  	data = EmojiImportData{Name: ptrStr(model.NewId())}
  2385  	err = th.App.ImportEmoji(&data, false)
  2386  	assert.NotNil(t, err, "Invalid emoji should have failed apply mode")
  2387  
  2388  	data.Image = ptrStr("non-existent-file")
  2389  	err = th.App.ImportEmoji(&data, false)
  2390  	assert.NotNil(t, err, "Emoji with bad image file should have failed apply mode")
  2391  
  2392  	data.Image = ptrStr(testImage)
  2393  	err = th.App.ImportEmoji(&data, false)
  2394  	assert.Nil(t, err, "Valid emoji should have succeeded apply mode")
  2395  
  2396  	result = <-th.App.Srv.Store.Emoji().GetByName(*data.Name)
  2397  	assert.NotNil(t, result.Data, "Emoji should have been imported")
  2398  
  2399  	err = th.App.ImportEmoji(&data, false)
  2400  	assert.Nil(t, err, "Second run should have succeeded apply mode")
  2401  }
  2402  
  2403  func TestImportAttachment(t *testing.T) {
  2404  	th := Setup()
  2405  	defer th.TearDown()
  2406  
  2407  	testsDir, _ := utils.FindDir("tests")
  2408  	testImage := filepath.Join(testsDir, "test.png")
  2409  	invalidPath := "some-invalid-path"
  2410  
  2411  	userId := model.NewId()
  2412  	data := AttachmentImportData{Path: &testImage}
  2413  	_, err := th.App.ImportAttachment(&data, &model.Post{UserId: userId, ChannelId: "some-channel"}, "some-team", true)
  2414  	assert.Nil(t, err, "sample run without errors")
  2415  
  2416  	attachments := GetAttachments(userId, th, t)
  2417  	assert.Equal(t, len(attachments), 1)
  2418  
  2419  	data = AttachmentImportData{Path: &invalidPath}
  2420  	_, err = th.App.ImportAttachment(&data, &model.Post{UserId: model.NewId(), ChannelId: "some-channel"}, "some-team", true)
  2421  	assert.NotNil(t, err, "should have failed when opening the file")
  2422  	assert.Equal(t, err.Id, "app.import.attachment.bad_file.error")
  2423  }
  2424  
  2425  func TestImportPostAndRepliesWithAttachments(t *testing.T) {
  2426  
  2427  	th := Setup()
  2428  	defer th.TearDown()
  2429  
  2430  	// Create a Team.
  2431  	teamName := model.NewId()
  2432  	th.App.ImportTeam(&TeamImportData{
  2433  		Name:        &teamName,
  2434  		DisplayName: ptrStr("Display Name"),
  2435  		Type:        ptrStr("O"),
  2436  	}, false)
  2437  	team, err := th.App.GetTeamByName(teamName)
  2438  	if err != nil {
  2439  		t.Fatalf("Failed to get team from database.")
  2440  	}
  2441  
  2442  	// Create a Channel.
  2443  	channelName := model.NewId()
  2444  	th.App.ImportChannel(&ChannelImportData{
  2445  		Team:        &teamName,
  2446  		Name:        &channelName,
  2447  		DisplayName: ptrStr("Display Name"),
  2448  		Type:        ptrStr("O"),
  2449  	}, false)
  2450  	_, err = th.App.GetChannelByName(channelName, team.Id, false)
  2451  	if err != nil {
  2452  		t.Fatalf("Failed to get channel from database.")
  2453  	}
  2454  
  2455  	// Create a user3.
  2456  	username := model.NewId()
  2457  	th.App.ImportUser(&UserImportData{
  2458  		Username: &username,
  2459  		Email:    ptrStr(model.NewId() + "@example.com"),
  2460  	}, false)
  2461  	user3, err := th.App.GetUserByUsername(username)
  2462  	if err != nil {
  2463  		t.Fatalf("Failed to get user3 from database.")
  2464  	}
  2465  
  2466  	username2 := model.NewId()
  2467  	th.App.ImportUser(&UserImportData{
  2468  		Username: &username2,
  2469  		Email:    ptrStr(model.NewId() + "@example.com"),
  2470  	}, false)
  2471  	user4, err := th.App.GetUserByUsername(username2)
  2472  	if err != nil {
  2473  		t.Fatalf("Failed to get user3 from database.")
  2474  	}
  2475  
  2476  	// Post with attachments.
  2477  	time := model.GetMillis()
  2478  	attachmentsPostTime := time
  2479  	attachmentsReplyTime := time + 1
  2480  	testsDir, _ := utils.FindDir("tests")
  2481  	testImage := filepath.Join(testsDir, "test.png")
  2482  	testMarkDown := filepath.Join(testsDir, "test-attachments.md")
  2483  	data := &PostImportData{
  2484  		Team:        &teamName,
  2485  		Channel:     &channelName,
  2486  		User:        &username,
  2487  		Message:     ptrStr("Message with reply"),
  2488  		CreateAt:    &attachmentsPostTime,
  2489  		Attachments: &[]AttachmentImportData{{Path: &testImage}, {Path: &testMarkDown}},
  2490  		Replies: &[]ReplyImportData{{
  2491  			User:        &user4.Username,
  2492  			Message:     ptrStr("Message reply"),
  2493  			CreateAt:    &attachmentsReplyTime,
  2494  			Attachments: &[]AttachmentImportData{{Path: &testImage}},
  2495  		}},
  2496  	}
  2497  
  2498  	if err := th.App.ImportPost(data, false); err != nil {
  2499  		t.Fatalf("Expected success.")
  2500  	}
  2501  
  2502  	attachments := GetAttachments(user3.Id, th, t)
  2503  	assert.Equal(t, len(attachments), 2)
  2504  	assert.Contains(t, attachments[0].Path, team.Id)
  2505  	assert.Contains(t, attachments[1].Path, team.Id)
  2506  	AssertFileIdsInPost(attachments, th, t)
  2507  
  2508  	attachments = GetAttachments(user4.Id, th, t)
  2509  	assert.Equal(t, len(attachments), 1)
  2510  	assert.Contains(t, attachments[0].Path, team.Id)
  2511  	AssertFileIdsInPost(attachments, th, t)
  2512  
  2513  	// Reply with Attachments in Direct Post
  2514  
  2515  	// Create direct post users.
  2516  
  2517  	username3 := model.NewId()
  2518  	th.App.ImportUser(&UserImportData{
  2519  		Username: &username3,
  2520  		Email:    ptrStr(model.NewId() + "@example.com"),
  2521  	}, false)
  2522  	user3, err = th.App.GetUserByUsername(username3)
  2523  	if err != nil {
  2524  		t.Fatalf("Failed to get user3 from database.")
  2525  	}
  2526  
  2527  	username4 := model.NewId()
  2528  	th.App.ImportUser(&UserImportData{
  2529  		Username: &username4,
  2530  		Email:    ptrStr(model.NewId() + "@example.com"),
  2531  	}, false)
  2532  
  2533  	user4, err = th.App.GetUserByUsername(username4)
  2534  	if err != nil {
  2535  		t.Fatalf("Failed to get user3 from database.")
  2536  	}
  2537  
  2538  	directImportData := &DirectPostImportData{
  2539  		ChannelMembers: &[]string{
  2540  			user3.Username,
  2541  			user4.Username,
  2542  		},
  2543  		User:     &user3.Username,
  2544  		Message:  ptrStr("Message with Replies"),
  2545  		CreateAt: ptrInt64(model.GetMillis()),
  2546  		Replies: &[]ReplyImportData{{
  2547  			User:        &user4.Username,
  2548  			Message:     ptrStr("Message reply with attachment"),
  2549  			CreateAt:    ptrInt64(model.GetMillis()),
  2550  			Attachments: &[]AttachmentImportData{{Path: &testImage}},
  2551  		}},
  2552  	}
  2553  
  2554  	if err := th.App.ImportDirectPost(directImportData, false); err != nil {
  2555  		t.Fatalf("Expected success.")
  2556  	}
  2557  
  2558  	attachments = GetAttachments(user4.Id, th, t)
  2559  	assert.Equal(t, len(attachments), 1)
  2560  	assert.Contains(t, attachments[0].Path, "noteam")
  2561  	AssertFileIdsInPost(attachments, th, t)
  2562  
  2563  }
  2564  
  2565  func TestImportDirectPostWithAttachments(t *testing.T) {
  2566  
  2567  	th := Setup()
  2568  	defer th.TearDown()
  2569  
  2570  	testsDir, _ := utils.FindDir("tests")
  2571  	testImage := filepath.Join(testsDir, "test.png")
  2572  
  2573  	// Create a user.
  2574  	username := model.NewId()
  2575  	th.App.ImportUser(&UserImportData{
  2576  		Username: &username,
  2577  		Email:    ptrStr(model.NewId() + "@example.com"),
  2578  	}, false)
  2579  	user1, err := th.App.GetUserByUsername(username)
  2580  	if err != nil {
  2581  		t.Fatalf("Failed to get user1 from database.")
  2582  	}
  2583  
  2584  	username2 := model.NewId()
  2585  	th.App.ImportUser(&UserImportData{
  2586  		Username: &username2,
  2587  		Email:    ptrStr(model.NewId() + "@example.com"),
  2588  	}, false)
  2589  
  2590  	user2, err := th.App.GetUserByUsername(username2)
  2591  	if err != nil {
  2592  		t.Fatalf("Failed to get user2 from database.")
  2593  	}
  2594  
  2595  	directImportData := &DirectPostImportData{
  2596  		ChannelMembers: &[]string{
  2597  			user1.Username,
  2598  			user2.Username,
  2599  		},
  2600  		User:        &user1.Username,
  2601  		Message:     ptrStr("Direct message"),
  2602  		CreateAt:    ptrInt64(model.GetMillis()),
  2603  		Attachments: &[]AttachmentImportData{{Path: &testImage}},
  2604  	}
  2605  
  2606  	if err := th.App.ImportDirectPost(directImportData, false); err != nil {
  2607  		t.Fatalf("Expected success.")
  2608  	}
  2609  
  2610  	attachments := GetAttachments(user1.Id, th, t)
  2611  	assert.Equal(t, len(attachments), 1)
  2612  	assert.Contains(t, attachments[0].Path, "noteam")
  2613  	AssertFileIdsInPost(attachments, th, t)
  2614  }