I am using gin-contrib sessions and reproduced the tests of this example test file: https://github.com/gin-contrib/sessions/blob/98372e3e8562a0d4b3d319db0d79ffbf5898e360/tester/tester.go
In contrast to the example, I set some session options in my login handler:
func (h *handler) login(c *gin.Context, u model.Participant) {
// [sign in code reduced]
dbuser := u.Login(h.db, c)
// start session
session := sessions.Default(c)
session.Options(sessions.Options{
MaxAge: 3600,
Path: "/",
HttpOnly: true,
Secure: true,
})
session.Set("id", dbuser.ID)
session.Set("name", dbuser.Name)
if err := session.Save(); err != nil {
c.HTML(http.StatusBadRequest, "index.html", gin.H{"error": err.Error()})
return
}
c.Redirect(http.StatusFound, "/dashboard")
}
Now I wrote a test for this handler:
// LoginCookie
// This function is only needed for test purposes
func LoginCookie(router *gin.Engine, t *testing.T) []string {
t.Log("performing login...")
w := httptest.NewRecorder()
req, _ := http.NewRequest("POST", "/login", strings.NewReader("name=bob&password=j"))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
router.ServeHTTP(w, req)
assert.Equal(t, 302, w.Code)
assert.Equal(t, "/dashboard", w.Header().Get("location"))
assert.Equal(t, true, strings.Contains(w.Header().Get("Set-Cookie"), "mysession"))
t.Log("login successful")
return w.Header().Values("Set-Cookie")
}
This function should sign in a user defined in the fixtures. It works locally, but randomly fails as soon as I try to run it in a gitlab ci.
Here is my gitlab ci script:
format:
stage: test
services:
- name: harbor.uni-muenster.de/proxy-docker/library/postgres:16
alias: postgres
variables:
POSTGRES_DB: cvmlsannotationserver_test
POSTGRES_USER: cvmlsannotationserver_test
POSTGRES_PASSWORD: cvmlsannotationserver_test
image: harbor.uni-muenster.de/proxy-docker/library/golang:latest
script:
- go fmt $(go list ./... | grep -v /vendor/)
- go vet $(go list ./... | grep -v /vendor/)
- ANNOTATIONSERVER_DSN=postgres://cvmlsannotationserver_test:cvmlsannotationserver_test@postgres:5432/cvmlsannotationserver_test?sslmode=disable go test -race $(go list ./... | grep -v /vendor/)
The fixtures are being loaded, the user should be able to log in, but the test randomly sometimes passes and sometimes fails.