Skip to content

Commit

Permalink
Add CORS test
Browse files Browse the repository at this point in the history
  • Loading branch information
khlieng committed Jul 5, 2015
1 parent 7ec978d commit f31eb2e
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 6 deletions.
10 changes: 4 additions & 6 deletions api/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@ import (
"os"
"testing"

"github.com/Castcloud/castcloud-go-server/Godeps/_workspace/src/github.com/labstack/echo"

. "github.com/Castcloud/castcloud-go-server/api/schema"
)

Expand Down Expand Up @@ -101,21 +99,21 @@ func testHandler(w http.ResponseWriter, r *http.Request) {
}

type testReq struct {
r *echo.Echo
h http.Handler
*http.Request
}

func testRequest(r *echo.Echo, method, url string, body io.Reader) testReq {
func testRequest(h http.Handler, method, url string, body io.Reader) testReq {
req, _ := http.NewRequest(method, url, body)
if method == "POST" {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
return testReq{r: r, Request: req}
return testReq{h: h, Request: req}
}

func (t testReq) send() *httptest.ResponseRecorder {
w := httptest.NewRecorder()
t.r.ServeHTTP(w, t.Request)
t.h.ServeHTTP(w, t.Request)
return w
}

Expand Down
49 changes: 49 additions & 0 deletions api/cors_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package api

import (
"net/http/httptest"
"testing"

"github.com/Castcloud/castcloud-go-server/Godeps/_workspace/src/github.com/labstack/echo"
"github.com/Castcloud/castcloud-go-server/Godeps/_workspace/src/github.com/stretchr/testify/assert"
)

func TestCORS(t *testing.T) {
mw := cors()
req := testRequest(nil, "GET", "/", nil)
res := httptest.NewRecorder()
c := echo.NewContext(req.Request, echo.NewResponse(res), echo.New())
called := false

next := func(c *echo.Context) error {
called = true
return nil
}

// It calls the next middleware when no origin is set
h := mw(next)
h(c)
assert.True(t, called)
assert.Empty(t, res.Header().Get("Access-Control-Allow-Origin"))

// It sets CORS headers and calls the next middleware when the origin is set
req.Header.Set("Origin", "china")
called = false
h(c)
assert.True(t, called)
assert.NotEmpty(t, res.Header().Get("Access-Control-Allow-Origin"))

// It sets CORS headers, ends the middleware chain and
// returns 200 when receiving a preflight request
req.Method = "OPTIONS"
res = httptest.NewRecorder()
c = echo.NewContext(req.Request, echo.NewResponse(res), echo.New())
res.Code = 0
called = false
h(c)
assert.False(t, called)
assert.Equal(t, 200, res.Code)
assert.NotEmpty(t, res.Header().Get("Access-Control-Allow-Origin"))
assert.NotEmpty(t, res.Header().Get("Access-Control-Allow-Methods"))
assert.NotEmpty(t, res.Header().Get("Access-Control-Allow-Headers"))
}

0 comments on commit f31eb2e

Please sign in to comment.