github.com/gofiber/fiber/v2@v2.47.0/middleware/session/store_test.go (about) 1 package session 2 3 import ( 4 "fmt" 5 "testing" 6 7 "github.com/gofiber/fiber/v2" 8 "github.com/gofiber/fiber/v2/utils" 9 10 "github.com/valyala/fasthttp" 11 ) 12 13 // go test -run TestStore_getSessionID 14 func TestStore_getSessionID(t *testing.T) { 15 t.Parallel() 16 expectedID := "test-session-id" 17 18 // fiber instance 19 app := fiber.New() 20 21 t.Run("from cookie", func(t *testing.T) { 22 t.Parallel() 23 // session store 24 store := New() 25 // fiber context 26 ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) 27 defer app.ReleaseCtx(ctx) 28 // set cookie 29 ctx.Request().Header.SetCookie(store.sessionName, expectedID) 30 31 utils.AssertEqual(t, expectedID, store.getSessionID(ctx)) 32 }) 33 34 t.Run("from header", func(t *testing.T) { 35 t.Parallel() 36 // session store 37 store := New(Config{ 38 KeyLookup: "header:session_id", 39 }) 40 // fiber context 41 ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) 42 defer app.ReleaseCtx(ctx) 43 // set header 44 ctx.Request().Header.Set(store.sessionName, expectedID) 45 46 utils.AssertEqual(t, expectedID, store.getSessionID(ctx)) 47 }) 48 49 t.Run("from url query", func(t *testing.T) { 50 t.Parallel() 51 // session store 52 store := New(Config{ 53 KeyLookup: "query:session_id", 54 }) 55 // fiber context 56 ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) 57 defer app.ReleaseCtx(ctx) 58 // set url parameter 59 ctx.Request().SetRequestURI(fmt.Sprintf("/path?%s=%s", store.sessionName, expectedID)) 60 61 utils.AssertEqual(t, expectedID, store.getSessionID(ctx)) 62 }) 63 } 64 65 // go test -run TestStore_Get 66 // Regression: https://github.com/gofiber/fiber/issues/1408 67 func TestStore_Get(t *testing.T) { 68 t.Parallel() 69 unexpectedID := "test-session-id" 70 // fiber instance 71 app := fiber.New() 72 t.Run("session should persisted even session is invalid", func(t *testing.T) { 73 t.Parallel() 74 // session store 75 store := New() 76 // fiber context 77 ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) 78 defer app.ReleaseCtx(ctx) 79 // set cookie 80 ctx.Request().Header.SetCookie(store.sessionName, unexpectedID) 81 82 acquiredSession, err := store.Get(ctx) 83 utils.AssertEqual(t, err, nil) 84 85 if acquiredSession.ID() != unexpectedID { 86 t.Fatal("server should not accept the unexpectedID which is not in the store") 87 } 88 }) 89 }