-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain_test.go
63 lines (49 loc) · 1.63 KB
/
main_test.go
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package main
import (
"flag"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
"github.com/urfave/cli/v2"
"github.com/caido/grafana-auth-proxy/pkg/authtest"
)
func setupTestJWKServer() (string, func()) {
publicKey := authtest.LoadPublicKey()
jwk := authtest.GetRawRS256Jwk(publicKey)
jwkServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(jwk))
}))
return jwkServer.URL, jwkServer.Close
}
func setupTestFlagSet(backendURL string, jwkURL string) *flag.FlagSet {
set := flag.NewFlagSet("test", 0)
set.Int("port", 5000, "")
set.String("url", backendURL, "")
set.String("jwk", jwkURL, "")
set.Bool("cookieAuth", true, "")
set.String("cookie", cookieName, "")
set.Var(cli.NewStringSlice(authtest.Algorithm), "algorithms", "")
set.String("audience", authtest.Audience, "")
set.String("issuer", authtest.Issuer, "")
set.String("claim", authtest.Claim, "")
return set
}
func TestCreateRequestsHandler(t *testing.T) {
backendURL, closeBackend := setupTestBackendServer()
jwkURL, closeJwk := setupTestJWKServer()
defer closeBackend()
defer closeJwk()
set := setupTestFlagSet(backendURL, jwkURL)
context := cli.NewContext(&cli.App{}, set, nil)
requestHandler, err := createRequestsHandler(context)
assert.Nil(t, err)
req, _ := http.NewRequest("GET", "/test", nil)
req.AddCookie(&http.Cookie{Name: cookieName, Value: setupTestToken()})
// Send the request
rr := httptest.NewRecorder()
requestHandler.ServeHTTP(rr, req)
assert.Equal(t, rr.Code, http.StatusOK)
assert.Equal(t, rr.Body.String(), "[email protected]")
}