somehttphandlers/methodsallowed/methodsallowed_test.go

68 lines
1.2 KiB
Go
Raw Normal View History

2022-01-27 14:23:09 +01:00
package methodsallowed_test
import (
"io"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/require"
"go.xsfx.dev/somehttphandlers/methodsallowed"
)
var handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { //nolint:gochecknoglobals
if _, err := io.WriteString(w, "hello world"); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
})
func TestAllow(t *testing.T) {
t.Parallel()
tables := []struct {
method string
body string
statusCode int
}{
{
http.MethodGet,
"hello world",
http.StatusOK,
},
{
http.MethodDelete,
"Method not allowed\n",
http.StatusMethodNotAllowed,
},
}
// Only allow GET and POST.
allow := methodsallowed.Allow(http.MethodGet, http.MethodPost)(handler)
for _, table := range tables {
table := table
t.Run(table.method, func(t *testing.T) {
t.Parallel()
req := httptest.NewRequest(table.method, "/", nil)
w := httptest.NewRecorder()
allow.ServeHTTP(w, req)
resp := w.Result()
2022-01-31 09:13:28 +01:00
defer resp.Body.Close()
2022-01-27 14:23:09 +01:00
body, _ := io.ReadAll(resp.Body)
require.Equal(t, table.body, string(body))
require.Equal(t, table.statusCode, resp.StatusCode)
})
}
}
func TestNotAllow(t *testing.T) {
t.Parallel()
}