github.com/singlemusic/buffalo@v0.16.30/wrappers_test.go (about)

     1  package buffalo
     2  
     3  import (
     4  	"net/http"
     5  	"testing"
     6  
     7  	"github.com/gobuffalo/buffalo/render"
     8  	"github.com/gobuffalo/httptest"
     9  	"github.com/stretchr/testify/require"
    10  )
    11  
    12  func Test_WrapHandlerFunc(t *testing.T) {
    13  	r := require.New(t)
    14  
    15  	a := New(Options{})
    16  	a.GET("/foo", WrapHandlerFunc(func(res http.ResponseWriter, req *http.Request) {
    17  		res.Write([]byte("hello"))
    18  	}))
    19  
    20  	w := httptest.New(a)
    21  	res := w.HTML("/foo").Get()
    22  
    23  	r.Equal("hello", res.Body.String())
    24  }
    25  
    26  func Test_WrapHandler(t *testing.T) {
    27  	r := require.New(t)
    28  
    29  	a := New(Options{})
    30  	a.GET("/foo", WrapHandler(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
    31  		res.Write([]byte("hello"))
    32  	})))
    33  
    34  	w := httptest.New(a)
    35  	res := w.HTML("/foo").Get()
    36  
    37  	r.Equal("hello", res.Body.String())
    38  }
    39  
    40  func Test_WrapBuffaloHandler(t *testing.T) {
    41  	r := require.New(t)
    42  
    43  	tt := []struct {
    44  		verb   string
    45  		path   string
    46  		status int
    47  	}{
    48  		{"GET", "/", 1},
    49  		{"GET", "/foo", 2},
    50  		{"POST", "/", 3},
    51  		{"POST", "/foo", 4},
    52  	}
    53  	for _, x := range tt {
    54  		bf := func(c Context) error {
    55  			req := c.Request()
    56  			return c.Render(x.status, render.String(req.Method+req.URL.Path))
    57  		}
    58  
    59  		h := WrapBuffaloHandler(bf)
    60  		r.NotNil(h)
    61  
    62  		req := httptest.NewRequest(x.verb, x.path, nil)
    63  		res := httptest.NewRecorder()
    64  
    65  		h.ServeHTTP(res, req)
    66  
    67  		r.Equal(x.status, res.Code)
    68  		r.Contains(res.Body.String(), x.verb+x.path)
    69  	}
    70  }
    71  
    72  func Test_WrapBuffaloHandlerFunc(t *testing.T) {
    73  	r := require.New(t)
    74  
    75  	tt := []struct {
    76  		verb   string
    77  		path   string
    78  		status int
    79  	}{
    80  		{"GET", "/", 1},
    81  		{"GET", "/foo", 2},
    82  		{"POST", "/", 3},
    83  		{"POST", "/foo", 4},
    84  	}
    85  	for _, x := range tt {
    86  		bf := func(c Context) error {
    87  			req := c.Request()
    88  			return c.Render(x.status, render.String(req.Method+req.URL.Path))
    89  		}
    90  
    91  		h := WrapBuffaloHandlerFunc(bf)
    92  		r.NotNil(h)
    93  
    94  		req := httptest.NewRequest(x.verb, x.path, nil)
    95  		res := httptest.NewRecorder()
    96  
    97  		h(res, req)
    98  
    99  		r.Equal(x.status, res.Code)
   100  		r.Contains(res.Body.String(), x.verb+x.path)
   101  	}
   102  }