github.com/haalcala/mattermost-server-change-repo@v0.0.0-20210713015153-16753fbeee5f/plugin/plugintest/example_hello_user_test.go (about) 1 // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. 2 // See LICENSE.txt for license information. 3 4 package plugintest_test 5 6 import ( 7 "fmt" 8 "io/ioutil" 9 "net/http" 10 "net/http/httptest" 11 "testing" 12 13 "github.com/stretchr/testify/assert" 14 "github.com/stretchr/testify/require" 15 16 "github.com/mattermost/mattermost-server/v5/model" 17 "github.com/mattermost/mattermost-server/v5/plugin" 18 "github.com/mattermost/mattermost-server/v5/plugin/plugintest" 19 ) 20 21 type HelloUserPlugin struct { 22 plugin.MattermostPlugin 23 } 24 25 func (p *HelloUserPlugin) ServeHTTP(context *plugin.Context, w http.ResponseWriter, r *http.Request) { 26 userID := r.Header.Get("Mattermost-User-Id") 27 user, err := p.API.GetUser(userID) 28 if err != nil { 29 w.WriteHeader(http.StatusBadRequest) 30 p.API.LogError(err.Error()) 31 return 32 } 33 34 fmt.Fprintf(w, "Welcome back, %s!", user.Username) 35 } 36 37 func Example() { 38 t := &testing.T{} 39 user := &model.User{ 40 Id: model.NewId(), 41 Username: "billybob", 42 } 43 44 api := &plugintest.API{} 45 api.On("GetUser", user.Id).Return(user, nil) 46 defer api.AssertExpectations(t) 47 48 helpers := &plugintest.Helpers{} 49 defer helpers.AssertExpectations(t) 50 51 p := &HelloUserPlugin{} 52 p.SetAPI(api) 53 p.SetHelpers(helpers) 54 55 w := httptest.NewRecorder() 56 r := httptest.NewRequest("GET", "/", nil) 57 r.Header.Add("Mattermost-User-Id", user.Id) 58 p.ServeHTTP(&plugin.Context{}, w, r) 59 body, err := ioutil.ReadAll(w.Result().Body) 60 require.NoError(t, err) 61 assert.Equal(t, "Welcome back, billybob!", string(body)) 62 }