Cloudreve/middleware/session_test.go

74 lines
1.4 KiB
Go
Raw Normal View History

2019-11-12 15:34:54 +08:00
package middleware
import (
"net/http"
"net/http/httptest"
2019-11-12 15:34:54 +08:00
"testing"
"github.com/cloudreve/Cloudreve/v3/pkg/conf"
"github.com/cloudreve/Cloudreve/v3/pkg/util"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
2019-11-12 15:34:54 +08:00
)
func TestSession(t *testing.T) {
asserts := assert.New(t)
2019-12-04 13:49:28 +08:00
{
handler := Session("2333")
asserts.NotNil(handler)
asserts.NotNil(Store)
asserts.IsType(emptyFunc(), handler)
}
{
conf.RedisConfig.Server = "123"
asserts.Panics(func() {
Session("2333")
})
2020-03-18 09:47:06 +08:00
conf.RedisConfig.Server = ""
2019-12-04 13:49:28 +08:00
}
2019-11-12 15:34:54 +08:00
}
func emptyFunc() gin.HandlerFunc {
return func(c *gin.Context) {}
}
func TestCSRFInit(t *testing.T) {
asserts := assert.New(t)
rec := httptest.NewRecorder()
sessionFunc := Session("233")
{
c, _ := gin.CreateTestContext(rec)
c.Request, _ = http.NewRequest("GET", "/test", nil)
sessionFunc(c)
CSRFInit()(c)
asserts.True(util.GetSession(c, "CSRF").(bool))
}
}
func TestCSRFCheck(t *testing.T) {
asserts := assert.New(t)
rec := httptest.NewRecorder()
sessionFunc := Session("233")
// 通过检查
{
c, _ := gin.CreateTestContext(rec)
c.Request, _ = http.NewRequest("GET", "/test", nil)
sessionFunc(c)
CSRFInit()(c)
CSRFCheck()(c)
asserts.False(c.IsAborted())
}
// 未通过检查
{
c, _ := gin.CreateTestContext(rec)
c.Request, _ = http.NewRequest("GET", "/test", nil)
sessionFunc(c)
CSRFCheck()(c)
asserts.True(c.IsAborted())
}
}