github.com/mattermosttest/mattermost-server/v5@v5.0.0-20200917143240-9dfa12e121f9/app/auto_posts.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 "bytes" 8 "io" 9 "os" 10 "path/filepath" 11 12 "github.com/mattermost/mattermost-server/v5/model" 13 "github.com/mattermost/mattermost-server/v5/utils" 14 "github.com/mattermost/mattermost-server/v5/utils/fileutils" 15 ) 16 17 type AutoPostCreator struct { 18 a *App 19 channelid string 20 userid string 21 Fuzzy bool 22 TextLength utils.Range 23 HasImage bool 24 ImageFilenames []string 25 Users []string 26 Mentions utils.Range 27 Tags utils.Range 28 } 29 30 // Automatic poster used for testing 31 func NewAutoPostCreator(a *App, channelid, userid string) *AutoPostCreator { 32 return &AutoPostCreator{ 33 a: a, 34 channelid: channelid, 35 userid: userid, 36 Fuzzy: false, 37 TextLength: utils.Range{Begin: 100, End: 200}, 38 HasImage: false, 39 ImageFilenames: TEST_IMAGE_FILENAMES, 40 Users: []string{}, 41 Mentions: utils.Range{Begin: 0, End: 5}, 42 Tags: utils.Range{Begin: 0, End: 7}, 43 } 44 } 45 46 func (cfg *AutoPostCreator) UploadTestFile() ([]string, error) { 47 filename := cfg.ImageFilenames[utils.RandIntFromRange(utils.Range{Begin: 0, End: len(cfg.ImageFilenames) - 1})] 48 49 path, _ := fileutils.FindDir("tests") 50 file, err := os.Open(filepath.Join(path, filename)) 51 if err != nil { 52 return nil, err 53 } 54 defer file.Close() 55 56 data := &bytes.Buffer{} 57 _, err = io.Copy(data, file) 58 if err != nil { 59 return nil, err 60 } 61 62 fileResp, err2 := cfg.a.UploadFile(data.Bytes(), cfg.channelid, filename) 63 if err2 != nil { 64 return nil, err2 65 } 66 67 return []string{fileResp.Id}, nil 68 } 69 70 func (cfg *AutoPostCreator) CreateRandomPost() (*model.Post, error) { 71 return cfg.CreateRandomPostNested("", "") 72 } 73 74 func (cfg *AutoPostCreator) CreateRandomPostNested(parentId, rootId string) (*model.Post, error) { 75 var fileIds []string 76 if cfg.HasImage { 77 var err error 78 fileIds, err = cfg.UploadTestFile() 79 if err != nil { 80 return nil, err 81 } 82 } 83 84 var postText string 85 if cfg.Fuzzy { 86 postText = utils.FuzzPost() 87 } else { 88 postText = utils.RandomText(cfg.TextLength, cfg.Tags, cfg.Mentions, cfg.Users) 89 } 90 91 post := &model.Post{ 92 ChannelId: cfg.channelid, 93 UserId: cfg.userid, 94 ParentId: parentId, 95 RootId: rootId, 96 Message: postText, 97 FileIds: fileIds, 98 } 99 rpost, err := cfg.a.CreatePostMissingChannel(post, true) 100 if err != nil { 101 return nil, err 102 } 103 return rpost, nil 104 }