github.com/trigonella/mattermost-server@v5.11.1+incompatible/plugin/plugintest/example_hello_user_test.go (about)

     1  package plugintest_test
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"net/http"
     7  	"net/http/httptest"
     8  	"testing"
     9  
    10  	"github.com/stretchr/testify/assert"
    11  	"github.com/stretchr/testify/require"
    12  
    13  	"github.com/mattermost/mattermost-server/model"
    14  	"github.com/mattermost/mattermost-server/plugin"
    15  	"github.com/mattermost/mattermost-server/plugin/plugintest"
    16  )
    17  
    18  type HelloUserPlugin struct {
    19  	plugin.MattermostPlugin
    20  }
    21  
    22  func (p *HelloUserPlugin) ServeHTTP(context *plugin.Context, w http.ResponseWriter, r *http.Request) {
    23  	userId := r.Header.Get("Mattermost-User-Id")
    24  	user, err := p.API.GetUser(userId)
    25  	if err != nil {
    26  		w.WriteHeader(http.StatusBadRequest)
    27  		p.API.LogError(err.Error())
    28  		return
    29  	}
    30  
    31  	fmt.Fprintf(w, "Welcome back, %s!", user.Username)
    32  }
    33  
    34  func Example() {
    35  	t := &testing.T{}
    36  	user := &model.User{
    37  		Id:       model.NewId(),
    38  		Username: "billybob",
    39  	}
    40  
    41  	api := &plugintest.API{}
    42  	api.On("GetUser", user.Id).Return(user, nil)
    43  	defer api.AssertExpectations(t)
    44  
    45  	p := &HelloUserPlugin{}
    46  	p.SetAPI(api)
    47  
    48  	w := httptest.NewRecorder()
    49  	r := httptest.NewRequest("GET", "/", nil)
    50  	r.Header.Add("Mattermost-User-Id", user.Id)
    51  	p.ServeHTTP(&plugin.Context{}, w, r)
    52  	body, err := ioutil.ReadAll(w.Result().Body)
    53  	require.NoError(t, err)
    54  	assert.Equal(t, "Welcome back, billybob!", string(body))
    55  }