sessions icon indicating copy to clipboard operation
sessions copied to clipboard

panic: Key "github.com/gin-contrib/sessions" does not exist in unit test

Open DeNatur opened this issue 3 months ago • 0 comments

Hi,

I try to use sessions in a unit test, but I'm facing a problem when trying to test a class, which uses "github.com/gin-contrib/sessions".

This is a stripped down version of a code which I'm trying to test:

import (
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

const VALUE_KEY = "value"

func GetValueFromStore(c *gin.Context) int {
	session := sessions.Default(c)
	value := session.Get(VALUE_KEY)

	if value != nil {
		currentValue := value.(int)
		return currentValue
	}
	newValue := 0
	session.Set(VALUE_KEY, newValue)
	session.Save()
	return newValue
}

And the unit test:

import (
	"testing"

	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/memstore"
	"github.com/gin-gonic/gin"
)

func getMockContext() *gin.Context {
	gin.SetMode(gin.TestMode)
	router := gin.New()

	// Set up session store
	store := memstore.NewStore([]byte("secret"))
	router.Use(sessions.Sessions("mysession", store))
	c, _ := gin.CreateTestContext(nil)
	return c
}

func TestGetValueFromStore_NewValue(t *testing.T) {
	c := getMockContext()
	newValue := GetValueFromStore(c)
	if newValue != 0 {
		t.Error("New value is not 0")
	}
}

When running the go test -v ./... I get failure

--- FAIL: TestGetValueFromStore_NewValue (0.00s)
panic: Key "github.com/gin-contrib/sessions" does not exist [recovered]
        panic: Key "github.com/gin-contrib/sessions" does not exist

DeNatur avatar Mar 22 '24 21:03 DeNatur