Skip to content

Commit 7099b86

Browse files
committed
Added test case for session middleware
Signed-off-by: Vishal Rana <[email protected]>
1 parent bcde4c7 commit 7099b86

File tree

3 files changed

+58
-4
lines changed

3 files changed

+58
-4
lines changed

Gopkg.lock

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

session/session.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@ type (
1818
}
1919
)
2020

21+
const (
22+
key = "_session_store"
23+
)
24+
2125
var (
2226
// DefaultConfig is the default Session middleware config.
2327
DefaultConfig = Config{
@@ -27,7 +31,7 @@ var (
2731

2832
// Get returns a named session.
2933
func Get(name string, c echo.Context) (*sessions.Session, error) {
30-
store := c.Get("_session_store").(sessions.Store)
34+
store := c.Get(key).(sessions.Store)
3135
return store.Get(c.Request(), name)
3236
}
3337

@@ -54,7 +58,7 @@ func MiddlewareWithConfig(config Config) echo.MiddlewareFunc {
5458
if config.Skipper(c) {
5559
return next(c)
5660
}
57-
c.Set("_session_store", config.Store)
61+
c.Set(key, config.Store)
5862
return next(c)
5963
}
6064
}

session/session_test.go

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,51 @@
11
package session
2+
3+
import (
4+
"net/http"
5+
"net/http/httptest"
6+
"testing"
7+
8+
"github.com/gorilla/sessions"
9+
"github.com/labstack/echo"
10+
"github.com/stretchr/testify/assert"
11+
)
12+
13+
func TestMiddleware(t *testing.T) {
14+
e := echo.New()
15+
req := httptest.NewRequest(echo.GET, "/", nil)
16+
rec := httptest.NewRecorder()
17+
c := e.NewContext(req, rec)
18+
handler := func(c echo.Context) error {
19+
sess, _ := Get("test", c)
20+
sess.Options.Domain = "labstack.com"
21+
sess.Values["foo"] = "bar"
22+
sess.Save(c.Request(), c.Response())
23+
return c.String(http.StatusOK, "test")
24+
}
25+
store := sessions.NewCookieStore([]byte("secret"))
26+
config := Config{
27+
Skipper: func(c echo.Context) bool {
28+
return true
29+
},
30+
Store: store,
31+
}
32+
33+
// Skipper
34+
mw := MiddlewareWithConfig(config)
35+
h := mw(echo.NotFoundHandler)
36+
h(c)
37+
assert.Nil(t, c.Get(key))
38+
39+
// Panic
40+
config.Skipper = nil
41+
config.Store = nil
42+
assert.Panics(t, func() {
43+
MiddlewareWithConfig(config)
44+
})
45+
46+
// Core
47+
mw = Middleware(store)
48+
h = mw(handler)
49+
h(c)
50+
assert.Contains(t, rec.Header().Get(echo.HeaderSetCookie), "labstack.com")
51+
}

0 commit comments

Comments
 (0)