Support getting scoped token in integration tests

This commit is contained in:
harryzcy 2022-10-29 03:36:19 -04:00
parent fafc36d7ff
commit 06e9c81b64
No known key found for this signature in database
GPG key ID: CC2953E050C19686

View file

@ -18,7 +18,6 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"sync/atomic"
"testing" "testing"
"time" "time"
@ -219,8 +218,8 @@ func emptyTestSession(t testing.TB) *TestSession {
return &TestSession{jar: jar} return &TestSession{jar: jar}
} }
func getUserToken(t testing.TB, userName string) string { func getUserToken(t testing.TB, userName string, scope ...string) string {
return getTokenForLoggedInUser(t, loginUser(t, userName)) return getTokenForLoggedInUser(t, loginUser(t, userName), scope...)
} }
func loginUser(t testing.TB, userName string) *TestSession { func loginUser(t testing.TB, userName string) *TestSession {
@ -262,15 +261,23 @@ func loginUserWithPassword(t testing.TB, userName, password string) *TestSession
// token has to be unique this counter take care of // token has to be unique this counter take care of
var tokenCounter int64 var tokenCounter int64
func getTokenForLoggedInUser(t testing.TB, session *TestSession) string { // getTokenForLoggedInUser returns a token for a logged in user.
// The scope is an optional list of snake_case strings like the frontend form fields,
// but without the "scope_" prefix.
func getTokenForLoggedInUser(t testing.TB, session *TestSession, scopes ...string) string {
t.Helper() t.Helper()
tokenCounter++
req := NewRequest(t, "GET", "/user/settings/applications") req := NewRequest(t, "GET", "/user/settings/applications")
resp := session.MakeRequest(t, req, http.StatusOK) resp := session.MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body) doc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", "/user/settings/applications", map[string]string{ values := map[string]string{
"_csrf": doc.GetCSRF(), "_csrf": doc.GetCSRF(),
"name": fmt.Sprintf("api-testing-token-%d", atomic.AddInt64(&tokenCounter, 1)), "name": fmt.Sprintf("api-testing-token-%d", tokenCounter),
}) }
for _, scope := range scopes {
values[fmt.Sprintf("scope_%s", scope)] = "on"
}
req = NewRequestWithValues(t, "POST", "/user/settings/applications", values)
session.MakeRequest(t, req, http.StatusSeeOther) session.MakeRequest(t, req, http.StatusSeeOther)
req = NewRequest(t, "GET", "/user/settings/applications") req = NewRequest(t, "GET", "/user/settings/applications")
resp = session.MakeRequest(t, req, http.StatusOK) resp = session.MakeRequest(t, req, http.StatusOK)