github.com/xzl8028/xenia-server@v0.0.0-20190809101854-18450a97da63/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/xzl8028/xenia-server/model" 14 "github.com/xzl8028/xenia-server/plugin" 15 "github.com/xzl8028/xenia-server/plugin/plugintest" 16 ) 17 18 type HelloUserPlugin struct { 19 plugin.XeniaPlugin 20 } 21 22 func (p *HelloUserPlugin) ServeHTTP(context *plugin.Context, w http.ResponseWriter, r *http.Request) { 23 userId := r.Header.Get("Xenia-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 helpers := &plugintest.Helpers{} 46 defer helpers.AssertExpectations(t) 47 48 p := &HelloUserPlugin{} 49 p.SetAPI(api) 50 p.SetHelpers(helpers) 51 52 w := httptest.NewRecorder() 53 r := httptest.NewRequest("GET", "/", nil) 54 r.Header.Add("Xenia-User-Id", user.Id) 55 p.ServeHTTP(&plugin.Context{}, w, r) 56 body, err := ioutil.ReadAll(w.Result().Body) 57 require.NoError(t, err) 58 assert.Equal(t, "Welcome back, billybob!", string(body)) 59 }