1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
package middleware
import (
"net/http"
"testing"
"github.com/stretchr/testify/require"
"github.com/xlgmokha/x/pkg/test"
"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/cfg"
"gitlab.com/gitlab-org/software-supply-chain-security/authorization/sparkled/app/domain"
)
func TestRequireUser(t *testing.T) {
middleware := RequireUser()
t.Run("when a user is not logged in", func(t *testing.T) {
t.Run("returns a 404 status", func(t *testing.T) {
r, w := test.RequestResponse("GET", "/example")
server := middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
require.Fail(t, "unexpected call to handler")
}))
server.ServeHTTP(w, r)
require.Equal(t, http.StatusNotFound, w.Code)
})
})
t.Run("when a user is logged in", func(t *testing.T) {
t.Run("forwards the request", func(t *testing.T) {
user := &domain.User{ID: domain.ID("1")}
r, w := test.RequestResponse("GET", "/example", test.WithContextKeyValue(t.Context(), cfg.CurrentUser, user))
server := middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusTeapot)
}))
server.ServeHTTP(w, r)
require.Equal(t, http.StatusTeapot, w.Code)
})
})
}
|