1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
package gin
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/rs/cors"
)
func init() {
gin.SetMode(gin.ReleaseMode)
}
func TestAllowAllNotNil(t *testing.T) {
handler := AllowAll()
if handler == nil {
t.Error("Should not return nil Gin handler")
}
}
func TestDefaultNotNil(t *testing.T) {
handler := Default()
if handler == nil {
t.Error("Should not return nil Gin handler")
}
}
func TestNewNotNil(t *testing.T) {
handler := New(Options{})
if handler == nil {
t.Error("Should not return nil Gin handler")
}
}
func TestCorsWrapper_buildAbortsWhenPreflight(t *testing.T) {
res := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(res)
ctx.Request, _ = http.NewRequest("OPTIONS", "http://example.com/foo", nil)
ctx.Request.Header.Add("Origin", "http://example.com/")
ctx.Request.Header.Add("Access-Control-Request-Method", "POST")
ctx.Status(http.StatusAccepted)
res.Code = http.StatusAccepted
handler := corsWrapper{Cors: cors.New(Options{
// Intentionally left blank.
})}.build()
handler(ctx)
if !ctx.IsAborted() {
t.Error("Should abort on preflight requests")
}
if res.Code != http.StatusOK {
t.Error("Should abort with 200 OK status")
}
}
func TestCorsWrapper_buildNotAbortsWhenPassthrough(t *testing.T) {
res := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(res)
ctx.Request, _ = http.NewRequest("OPTIONS", "http://example.com/foo", nil)
ctx.Request.Header.Add("Origin", "http://example.com/")
ctx.Request.Header.Add("Access-Control-Request-Method", "POST")
handler := corsWrapper{cors.New(Options{
OptionsPassthrough: true,
}), true}.build()
handler(ctx)
if ctx.IsAborted() {
t.Error("Should not abort when OPTIONS passthrough enabled")
}
}
|