Skip to content

Commit

Permalink
fix tests
Browse files Browse the repository at this point in the history
  • Loading branch information
wxiaoguang committed Feb 27, 2025
1 parent f9601ec commit 35aa33d
Show file tree
Hide file tree
Showing 9 changed files with 20 additions and 76 deletions.
2 changes: 1 addition & 1 deletion models/auth/access_token_scope_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ type scopeTestNormalize struct {
}

func TestAccessTokenScope_Normalize(t *testing.T) {
assert.Equal(t, []string([]string{"activitypub", "admin", "issue", "misc", "notification", "organization", "package", "repository", "user"}), GetAccessTokenCategories())
assert.Equal(t, []string{"activitypub", "admin", "issue", "misc", "notification", "organization", "package", "repository", "user"}, GetAccessTokenCategories())
tests := []scopeTestNormalize{
{"", "", nil},
{"write:misc,write:notification,read:package,write:notification,public-only", "public-only,write:misc,write:notification,read:package", nil},
Expand Down
3 changes: 3 additions & 0 deletions services/context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,9 @@ func Contexter() func(next http.Handler) http.Handler {
func (ctx *Context) HasError() bool {
hasErr, _ := ctx.Data["HasError"].(bool)
hasErr = hasErr || ctx.Flash.ErrorMsg != ""
if !hasErr {
return false
}
if ctx.Flash.ErrorMsg == "" {
ctx.Flash.ErrorMsg = ctx.GetErrMsg()
}
Expand Down
27 changes: 0 additions & 27 deletions services/forms/user_form_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,8 @@
package forms

import (
"strconv"
"testing"

auth_model "code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/modules/setting"

"github.com/gobwas/glob"
Expand Down Expand Up @@ -104,28 +102,3 @@ func TestRegisterForm_IsDomainAllowed_BlockedEmail(t *testing.T) {
assert.Equal(t, v.valid, form.IsEmailDomainAllowed())
}
}

func TestNewAccessTokenForm_GetScope(t *testing.T) {
tests := []struct {
form NewAccessTokenForm
scope auth_model.AccessTokenScope
expectedErr error
}{
{
form: NewAccessTokenForm{Name: "test", Scope: []string{"read:repository"}},
scope: "read:repository",
},
{
form: NewAccessTokenForm{Name: "test", Scope: []string{"read:repository", "write:user"}},
scope: "read:repository,write:user",
},
}

for i, test := range tests {
t.Run(strconv.Itoa(i), func(t *testing.T) {
scope, err := test.form.GetScope()
assert.Equal(t, test.expectedErr, err)
assert.Equal(t, test.scope, scope)
})
}
}
2 changes: 1 addition & 1 deletion tests/integration/api_admin_org_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func TestAPIAdminOrgCreateNotAdmin(t *testing.T) {
defer tests.PrepareTestEnv(t)()
nonAdminUsername := "user2"
session := loginUser(t, nonAdminUsername)
token := getTokenForLoggedInUser(t, session)
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeAll)
org := api.CreateOrgOption{
UserName: "user2_org",
FullName: "User2's organization",
Expand Down
4 changes: 2 additions & 2 deletions tests/integration/api_admin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func TestAPIAdminDeleteUnauthorizedKey(t *testing.T) {
var newPublicKey api.PublicKey
DecodeJSON(t, resp, &newPublicKey)

token = getUserToken(t, normalUsername)
token = getUserToken(t, normalUsername, auth_model.AccessTokenScopeAll)
req = NewRequestf(t, "DELETE", "/api/v1/admin/users/%s/keys/%d", adminUsername, newPublicKey.ID).
AddTokenAuth(token)
MakeRequest(t, req, http.StatusForbidden)
Expand Down Expand Up @@ -139,7 +139,7 @@ func TestAPIListUsersNotLoggedIn(t *testing.T) {
func TestAPIListUsersNonAdmin(t *testing.T) {
defer tests.PrepareTestEnv(t)()
nonAdminUsername := "user2"
token := getUserToken(t, nonAdminUsername)
token := getUserToken(t, nonAdminUsername, auth_model.AccessTokenScopeAll)
req := NewRequest(t, "GET", "/api/v1/admin/users").
AddTokenAuth(token)
MakeRequest(t, req, http.StatusForbidden)
Expand Down
4 changes: 4 additions & 0 deletions tests/integration/api_helper_for_declarative_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ type APITestContext struct {

func NewAPITestContext(t *testing.T, username, reponame string, scope ...auth.AccessTokenScope) APITestContext {
session := loginUser(t, username)
if len(scope) == 0 {
// FIXME: legacy logic: no scope means all
scope = []auth.AccessTokenScope{auth.AccessTokenScopeAll}
}
token := getTokenForLoggedInUser(t, session, scope...)
return APITestContext{
Session: session,
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/api_repo_git_blobs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func TestAPIReposGitBlobs(t *testing.T) {

// Login as User4.
session = loginUser(t, user4.Name)
token4 := getTokenForLoggedInUser(t, session)
token4 := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeAll)

// Test using org repo "org3/repo3" where user4 is a NOT collaborator
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/blobs/d56a3073c1dbb7b15963110a049d50cdb5db99fc?access=%s", org3.Name, repo3.Name, token4)
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/api_repo_git_trees_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ func TestAPIReposGitTrees(t *testing.T) {

// Login as User4.
session = loginUser(t, user4.Name)
token4 := getTokenForLoggedInUser(t, session)
token4 := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeAll)

// Test using org repo "org3/repo3" where user4 is a NOT collaborator
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/git/trees/d56a3073c1dbb7b15963110a049d50cdb5db99fc?access=%s", org3.Name, repo3.Name, token4)
Expand Down
50 changes: 7 additions & 43 deletions tests/integration/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,55 +249,19 @@ func loginUserWithPassword(t testing.TB, userName, password string) *TestSession
// token has to be unique this counter take care of
var tokenCounter int64

// 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.
// getTokenForLoggedInUser returns a token for a logged-in user.
func getTokenForLoggedInUser(t testing.TB, session *TestSession, scopes ...auth.AccessTokenScope) string {
t.Helper()
var token string
req := NewRequest(t, "GET", "/user/settings/applications")
resp := session.MakeRequest(t, req, http.StatusOK)
var csrf string
for _, cookie := range resp.Result().Cookies() {
if cookie.Name != "_csrf" {
continue
}
csrf = cookie.Value
break
}
if csrf == "" {
doc := NewHTMLParser(t, resp.Body)
csrf = doc.GetCSRF()
}
assert.NotEmpty(t, csrf)
urlValues := url.Values{}
urlValues.Add("_csrf", csrf)
urlValues.Add("_csrf", GetUserCSRFToken(t, session))
urlValues.Add("name", fmt.Sprintf("api-testing-token-%d", atomic.AddInt64(&tokenCounter, 1)))
for _, scope := range scopes {
urlValues.Add("scope", string(scope))
urlValues.Add("scope-dummy", string(scope)) // it only needs to start with "scope-" to be accepted
}
req = NewRequestWithURLValues(t, "POST", "/user/settings/applications", urlValues)
resp = session.MakeRequest(t, req, http.StatusSeeOther)

// Log the flash values on failure
if !assert.Equal(t, []string{"/user/settings/applications"}, resp.Result().Header["Location"]) {
for _, cookie := range resp.Result().Cookies() {
if cookie.Name != gitea_context.CookieNameFlash {
continue
}
flash, _ := url.ParseQuery(cookie.Value)
for key, value := range flash {
t.Logf("Flash %q: %q", key, value)
}
}
}

req = NewRequest(t, "GET", "/user/settings/applications")
resp = session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
token = htmlDoc.doc.Find(".ui.info p").Text()
assert.NotEmpty(t, token)
return token
req := NewRequestWithURLValues(t, "POST", "/user/settings/applications", urlValues)
session.MakeRequest(t, req, http.StatusSeeOther)
flashes := session.GetCookieFlashMessage()
return flashes.InfoMsg
}

type RequestWrapper struct {
Expand Down

0 comments on commit 35aa33d

Please # to comment.