1
0
Fork 0
mirror of https://codeberg.org/forgejo/forgejo.git synced 2024-11-21 08:31:27 -05:00

Merge pull request 'chore: improve test quality' (#5904) from gusted/forgejo-improve-test into forgejo

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/5904
Reviewed-by: Earl Warren <earl-warren@noreply.codeberg.org>
Reviewed-by: Otto <otto@codeberg.org>
This commit is contained in:
Earl Warren 2024-11-10 20:35:50 +00:00
commit 8f6dfe29da
18 changed files with 620 additions and 784 deletions

View file

@ -14,6 +14,7 @@ import (
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/services/actions"
"code.gitea.io/gitea/services/automerge"
@ -23,7 +24,7 @@ import (
func TestActionsAutomerge(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
assert.True(t, setting.Actions.Enabled, "Actions should be enabled")
defer test.MockVariableValue(&setting.Actions.Enabled, true)()
ctx := db.DefaultContext

View file

@ -5,7 +5,6 @@ package integration
import (
"net/http"
"net/url"
"strings"
"testing"
@ -19,7 +18,7 @@ import (
)
func TestAPIAdminOrgCreate(t *testing.T) {
onGiteaRun(t, func(*testing.T, *url.URL) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user1")
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteAdmin)
@ -50,11 +49,10 @@ func TestAPIAdminOrgCreate(t *testing.T) {
LowerName: strings.ToLower(org.UserName),
FullName: org.FullName,
})
})
}
func TestAPIAdminOrgCreateBadVisibility(t *testing.T) {
onGiteaRun(t, func(*testing.T, *url.URL) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user1")
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteAdmin)
@ -69,7 +67,6 @@ func TestAPIAdminOrgCreateBadVisibility(t *testing.T) {
req := NewRequestWithJSON(t, "POST", "/api/v1/admin/users/user2/orgs", &org).
AddTokenAuth(token)
MakeRequest(t, req, http.StatusUnprocessableEntity)
})
}
func TestAPIAdminOrgCreateNotAdmin(t *testing.T) {

View file

@ -9,14 +9,13 @@ import (
"testing"
auth_model "code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/db"
git_model "code.gitea.io/gitea/models/git"
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/git"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func testAPIGetBranch(t *testing.T, branchName string, exists bool) {
@ -234,35 +233,17 @@ func TestAPIBranchProtection(t *testing.T) {
}
func TestAPICreateBranchWithSyncBranches(t *testing.T) {
defer tests.PrepareTestEnv(t)()
branches, err := db.Find[git_model.Branch](db.DefaultContext, git_model.FindBranchOptions{
RepoID: 1,
})
require.NoError(t, err)
assert.Len(t, branches, 4)
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
unittest.AssertCount(t, &git_model.Branch{RepoID: 1}, 4)
// make a broke repository with no branch on database
_, err = db.DeleteByBean(db.DefaultContext, git_model.Branch{RepoID: 1})
require.NoError(t, err)
unittest.AssertSuccessfulDelete(t, &git_model.Branch{RepoID: 1})
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
ctx := NewAPITestContext(t, "user2", "repo1", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
giteaURL.Path = ctx.GitPath()
testAPICreateBranch(t, ctx.Session, "user2", "repo1", "", "new_branch", http.StatusCreated)
})
branches, err = db.Find[git_model.Branch](db.DefaultContext, git_model.FindBranchOptions{
RepoID: 1,
unittest.AssertExistsIf(t, true, &git_model.Branch{RepoID: 1, Name: "new_branch"})
})
require.NoError(t, err)
assert.Len(t, branches, 5)
branches, err = db.Find[git_model.Branch](db.DefaultContext, git_model.FindBranchOptions{
RepoID: 1,
Keyword: "new_branch",
})
require.NoError(t, err)
assert.Len(t, branches, 1)
}

View file

@ -7,7 +7,6 @@ package integration
import (
"fmt"
"net/http"
"net/url"
"testing"
auth_model "code.gitea.io/gitea/models/auth"
@ -86,9 +85,9 @@ func TestCreateForkNoLogin(t *testing.T) {
}
func TestAPIDisabledForkRepo(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
defer test.MockVariableValue(&setting.Repository.DisableForks, true)()
defer test.MockVariableValue(&testWebRoutes, routers.NormalRoutes())()
defer tests.PrepareTestEnv(t)()
t.Run("fork listing", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
@ -106,5 +105,4 @@ func TestAPIDisabledForkRepo(t *testing.T) {
req := NewRequestWithJSON(t, "POST", "/api/v1/repos/user2/repo1/forks", &api.CreateForkOption{}).AddTokenAuth(token)
session.MakeRequest(t, req, http.StatusNotFound)
})
})
}

View file

@ -5,25 +5,22 @@ package integration
import (
"net/http"
"net/url"
"testing"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/routers"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
)
func TestNodeinfo(t *testing.T) {
setting.Federation.Enabled = true
testWebRoutes = routers.NormalRoutes()
defer func() {
setting.Federation.Enabled = false
testWebRoutes = routers.NormalRoutes()
}()
defer test.MockVariableValue(&setting.Federation.Enabled, true)()
defer test.MockVariableValue(&testWebRoutes, routers.NormalRoutes())()
defer tests.PrepareTestEnv(t)()
onGiteaRun(t, func(*testing.T, *url.URL) {
req := NewRequest(t, "GET", "/api/v1/nodeinfo")
resp := MakeRequest(t, req, http.StatusOK)
VerifyJSONSchema(t, resp, "nodeinfo_2.1.json")
@ -35,5 +32,4 @@ func TestNodeinfo(t *testing.T) {
assert.Equal(t, 29, nodeinfo.Usage.Users.Total)
assert.Equal(t, 22, nodeinfo.Usage.LocalPosts)
assert.Equal(t, 4, nodeinfo.Usage.LocalComments)
})
}

View file

@ -6,7 +6,6 @@ package integration
import (
"fmt"
"net/http"
"net/url"
"strings"
"testing"
@ -19,13 +18,14 @@ import (
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
)
func TestAPIOrgCreate(t *testing.T) {
onGiteaRun(t, func(*testing.T, *url.URL) {
defer tests.PrepareTestEnv(t)()
token := getUserToken(t, "user1", auth_model.AccessTokenScopeWriteOrganization)
org := api.CreateOrgOption{
@ -97,11 +97,10 @@ func TestAPIOrgCreate(t *testing.T) {
DecodeJSON(t, resp, &users)
assert.Len(t, users, 1)
assert.EqualValues(t, "user1", users[0].UserName)
})
}
func TestAPIOrgEdit(t *testing.T) {
onGiteaRun(t, func(*testing.T, *url.URL) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user1")
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteOrganization)
@ -125,11 +124,10 @@ func TestAPIOrgEdit(t *testing.T) {
assert.Equal(t, org.Website, apiOrg.Website)
assert.Equal(t, org.Location, apiOrg.Location)
assert.Equal(t, org.Visibility, apiOrg.Visibility)
})
}
func TestAPIOrgEditBadVisibility(t *testing.T) {
onGiteaRun(t, func(*testing.T, *url.URL) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user1")
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteOrganization)
@ -143,15 +141,11 @@ func TestAPIOrgEditBadVisibility(t *testing.T) {
req := NewRequestWithJSON(t, "PATCH", "/api/v1/orgs/org3", &org).
AddTokenAuth(token)
MakeRequest(t, req, http.StatusUnprocessableEntity)
})
}
func TestAPIOrgDeny(t *testing.T) {
onGiteaRun(t, func(*testing.T, *url.URL) {
setting.Service.RequireSignInView = true
defer func() {
setting.Service.RequireSignInView = false
}()
defer tests.PrepareTestEnv(t)()
defer test.MockVariableValue(&setting.Service.RequireSignInView, true)()
orgName := "user1_org"
req := NewRequestf(t, "GET", "/api/v1/orgs/%s", orgName)
@ -162,7 +156,6 @@ func TestAPIOrgDeny(t *testing.T) {
req = NewRequestf(t, "GET", "/api/v1/orgs/%s/members", orgName)
MakeRequest(t, req, http.StatusNotFound)
})
}
func TestAPIGetAll(t *testing.T) {
@ -192,7 +185,7 @@ func TestAPIGetAll(t *testing.T) {
}
func TestAPIOrgSearchEmptyTeam(t *testing.T) {
onGiteaRun(t, func(*testing.T, *url.URL) {
defer tests.PrepareTestEnv(t)()
token := getUserToken(t, "user1", auth_model.AccessTokenScopeWriteOrganization)
orgName := "org_with_empty_team"
@ -224,5 +217,4 @@ func TestAPIOrgSearchEmptyTeam(t *testing.T) {
if assert.Len(t, data.Data, 1) {
assert.EqualValues(t, "Empty", data.Data[0].Name)
}
})
}

View file

@ -2,17 +2,18 @@ package integration
import (
"net/http"
"net/url"
"path"
"strings"
"testing"
"code.gitea.io/gitea/tests"
"github.com/PuerkitoBio/goquery"
"github.com/stretchr/testify/assert"
)
func TestRepoLastUpdatedTime(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
defer tests.PrepareTestEnv(t)()
user := "user2"
session := loginUser(t, user)
@ -31,11 +32,10 @@ func TestRepoLastUpdatedTime(t *testing.T) {
relativeTime := node.Find("relative-time").Text()
assert.True(t, strings.HasPrefix(relativeTime, "19")) // ~1970, might underflow with timezone
}
})
}
func TestBranchLastUpdatedTime(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
defer tests.PrepareTestEnv(t)()
user := "user2"
repo := "repo1"
session := loginUser(t, user)
@ -55,7 +55,6 @@ func TestBranchLastUpdatedTime(t *testing.T) {
relativeTime := node.Find("relative-time").Text()
assert.True(t, strings.HasPrefix(relativeTime, "2017"))
}
})
}
// Find all text that are direct descendents

View file

@ -5,16 +5,16 @@ package integration
import (
"net/http"
"net/url"
"testing"
pull_service "code.gitea.io/gitea/services/pull"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
)
func TestListPullCommits(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user5")
req := NewRequest(t, "GET", "/user2/repo1/pulls/3/commits/list")
resp := session.MakeRequest(t, req, http.StatusOK)
@ -30,5 +30,4 @@ func TestListPullCommits(t *testing.T) {
assert.Equal(t, "4a357436d925b5c974181ff12a994538ddc5a269", pullCommitList.Commits[1].ID)
}
assert.Equal(t, "4a357436d925b5c974181ff12a994538ddc5a269", pullCommitList.LastReviewCommitSha)
})
}

View file

@ -18,7 +18,6 @@ import (
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/gitrepo"
"code.gitea.io/gitea/modules/test"
issue_service "code.gitea.io/gitea/services/issue"
@ -283,32 +282,18 @@ func TestPullView_CodeOwner(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
// Create the repo.
repo, err := repo_service.CreateRepositoryDirectly(db.DefaultContext, user2, user2, repo_service.CreateRepoOptions{
Name: "test_codeowner",
Readme: "Default",
AutoInit: true,
ObjectFormatName: git.Sha1ObjectFormat.Name(),
DefaultBranch: "master",
})
require.NoError(t, err)
// add CODEOWNERS to default branch
_, err = files_service.ChangeRepoFiles(db.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{
OldBranch: repo.DefaultBranch,
Files: []*files_service.ChangeRepoFile{
repo, _, f := tests.CreateDeclarativeRepo(t, user2, "test_codeowner", nil, nil, []*files_service.ChangeRepoFile{
{
Operation: "create",
TreePath: "CODEOWNERS",
ContentReader: strings.NewReader("README.md @user5\n"),
},
},
})
require.NoError(t, err)
defer f()
t.Run("First Pull Request", func(t *testing.T) {
// create a new branch to prepare for pull request
_, err = files_service.ChangeRepoFiles(db.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{
_, err := files_service.ChangeRepoFiles(db.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{
NewBranch: "codeowner-basebranch",
Files: []*files_service.ChangeRepoFile{
{
@ -328,7 +313,7 @@ func TestPullView_CodeOwner(t *testing.T) {
unittest.AssertExistsIf(t, true, &issues_model.Review{IssueID: pr.IssueID, Type: issues_model.ReviewTypeRequest, ReviewerID: 5})
require.NoError(t, pr.LoadIssue(db.DefaultContext))
err := issue_service.ChangeTitle(db.DefaultContext, pr.Issue, user2, "[WIP] Test Pull Request")
err = issue_service.ChangeTitle(db.DefaultContext, pr.Issue, user2, "[WIP] Test Pull Request")
require.NoError(t, err)
prUpdated1 := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: pr.ID})
require.NoError(t, prUpdated1.LoadIssue(db.DefaultContext))
@ -342,7 +327,7 @@ func TestPullView_CodeOwner(t *testing.T) {
})
// change the default branch CODEOWNERS file to change README.md's codeowner
_, err = files_service.ChangeRepoFiles(db.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{
_, err := files_service.ChangeRepoFiles(db.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{
Files: []*files_service.ChangeRepoFile{
{
Operation: "update",

View file

@ -22,8 +22,6 @@ func TestRenameBranch(t *testing.T) {
}
func testRenameBranch(t *testing.T, u *url.URL) {
defer tests.PrepareTestEnv(t)()
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
unittest.AssertExistsAndLoadBean(t, &git_model.Branch{RepoID: repo.ID, Name: "master"})

View file

@ -5,17 +5,18 @@ package integration
import (
"net/http"
"net/url"
"strings"
"testing"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
)
// TestRepoCollaborators is a test for contents of Collaborators tab in the repo settings
// It only covers a few elements and can be extended as needed
func TestRepoCollaborators(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user2")
// Visit Collaborators tab of repo settings
@ -33,5 +34,4 @@ func TestRepoCollaborators(t *testing.T) {
placeholder, exists := page.Find("#search-user-box input").Attr("placeholder")
assert.True(t, exists)
assert.EqualValues(t, "Search users...", placeholder)
})
}

View file

@ -5,15 +5,16 @@ package integration
import (
"net/http"
"net/url"
"testing"
"code.gitea.io/gitea/tests"
"github.com/PuerkitoBio/goquery"
"github.com/stretchr/testify/assert"
)
func TestRepoMigrationUI(t *testing.T) {
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
defer tests.PrepareTestEnv(t)()
sessionUser1 := loginUser(t, "user1")
// Nothing is tested in plain Git migration form right now
testRepoMigrationFormGitHub(t, sessionUser1)
@ -24,7 +25,6 @@ func TestRepoMigrationUI(t *testing.T) {
testRepoMigrationFormGitBucket(t, sessionUser1)
testRepoMigrationFormCodebase(t, sessionUser1)
testRepoMigrationFormForgejo(t, sessionUser1)
})
}
func testRepoMigrationFormGitHub(t *testing.T, session *TestSession) {

View file

@ -11,8 +11,6 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
git_model "code.gitea.io/gitea/models/git"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@ -31,20 +29,6 @@ func TestTagViewWithoutRelease(t *testing.T) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID})
defer func() {
releases, err := db.Find[repo_model.Release](db.DefaultContext, repo_model.FindReleasesOptions{
IncludeTags: true,
TagNames: []string{"no-release"},
RepoID: repo.ID,
})
require.NoError(t, err)
for _, release := range releases {
_, err = db.DeleteByID[repo_model.Release](db.DefaultContext, release.ID)
require.NoError(t, err)
}
}()
err := release.CreateNewTag(git.DefaultContext, owner, repo, "master", "no-release", "release-less tag")
require.NoError(t, err)
@ -70,8 +54,7 @@ func TestTagViewWithoutRelease(t *testing.T) {
}
func TestCreateNewTagProtected(t *testing.T) {
defer tests.PrepareTestEnv(t)()
onGiteaRun(t, func(t *testing.T, u *url.URL) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID})
@ -90,7 +73,8 @@ func TestCreateNewTagProtected(t *testing.T) {
})
t.Run("Git", func(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
defer tests.PrintCurrentTest(t)()
httpContext := NewAPITestContext(t, owner.Name, repo.Name)
dstPath := t.TempDir()
@ -107,10 +91,10 @@ func TestCreateNewTagProtected(t *testing.T) {
require.Error(t, err)
assert.Contains(t, err.Error(), "Tag v-2 is protected")
})
})
t.Run("GitTagForce", func(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
defer tests.PrintCurrentTest(t)()
httpContext := NewAPITestContext(t, owner.Name, repo.Name)
dstPath := t.TempDir()
@ -120,13 +104,7 @@ func TestCreateNewTagProtected(t *testing.T) {
doGitClone(dstPath, u)(t)
_, _, err := git.NewCommand(git.DefaultContext, "tag", "v-1.1", "-m", "force update", "--force").RunStdString(&git.RunOpts{Dir: dstPath})
require.NoError(t, err)
_, _, err = git.NewCommand(git.DefaultContext, "push", "--tags").RunStdString(&git.RunOpts{Dir: dstPath})
require.NoError(t, err)
_, _, err = git.NewCommand(git.DefaultContext, "tag", "v-1.1", "-m", "force update v2", "--force").RunStdString(&git.RunOpts{Dir: dstPath})
_, _, err := git.NewCommand(git.DefaultContext, "tag", "v-1.1", "-m", "force update v2", "--force").RunStdString(&git.RunOpts{Dir: dstPath})
require.NoError(t, err)
_, _, err = git.NewCommand(git.DefaultContext, "push", "--tags").RunStdString(&git.RunOpts{Dir: dstPath})
@ -142,27 +120,6 @@ func TestCreateNewTagProtected(t *testing.T) {
assert.Contains(t, tagsTab.Text(), "force update v2")
})
})
// Cleanup
releases, err := db.Find[repo_model.Release](db.DefaultContext, repo_model.FindReleasesOptions{
IncludeTags: true,
TagNames: []string{"v-1", "v-1.1"},
RepoID: repo.ID,
})
require.NoError(t, err)
for _, release := range releases {
_, err = db.DeleteByID[repo_model.Release](db.DefaultContext, release.ID)
require.NoError(t, err)
}
protectedTags, err := git_model.GetProtectedTags(db.DefaultContext, repo.ID)
require.NoError(t, err)
for _, protectedTag := range protectedTags {
err = git_model.DeleteProtectedTag(db.DefaultContext, protectedTag)
require.NoError(t, err)
}
}
func TestSyncRepoTags(t *testing.T) {
@ -200,18 +157,5 @@ func TestSyncRepoTags(t *testing.T) {
require.NoError(t, repo_module.SyncRepoTags(git.DefaultContext, repo.ID))
testTag(t)
})
// Cleanup
releases, err := db.Find[repo_model.Release](db.DefaultContext, repo_model.FindReleasesOptions{
IncludeTags: true,
TagNames: []string{"v2"},
RepoID: repo.ID,
})
require.NoError(t, err)
for _, release := range releases {
_, err = db.DeleteByID[repo_model.Release](db.DefaultContext, release.ID)
require.NoError(t, err)
}
})
}

View file

@ -62,8 +62,9 @@ func createRepoAndGetContext(t *testing.T, files []string, deleteMdReadme bool)
}
func TestRepoView_FindReadme(t *testing.T) {
t.Run("PrioOneLocalizedMdReadme", func(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
t.Run("PrioOneLocalizedMdReadme", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
ctx, f := createRepoAndGetContext(t, []string{"README.en.md", "README.en.org", "README.org", "README.txt", "README.tex"}, false)
defer f()
@ -73,9 +74,8 @@ func TestRepoView_FindReadme(t *testing.T) {
assert.Equal(t, "README.en.md", file.Name())
})
})
t.Run("PrioTwoMdReadme", func(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
defer tests.PrintCurrentTest(t)()
ctx, f := createRepoAndGetContext(t, []string{"README.en.org", "README.org", "README.txt", "README.tex"}, false)
defer f()
@ -85,9 +85,8 @@ func TestRepoView_FindReadme(t *testing.T) {
assert.Equal(t, "README.md", file.Name())
})
})
t.Run("PrioThreeLocalizedOrgReadme", func(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
defer tests.PrintCurrentTest(t)()
ctx, f := createRepoAndGetContext(t, []string{"README.en.org", "README.org", "README.txt", "README.tex"}, true)
defer f()
@ -97,9 +96,8 @@ func TestRepoView_FindReadme(t *testing.T) {
assert.Equal(t, "README.en.org", file.Name())
})
})
t.Run("PrioFourOrgReadme", func(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
defer tests.PrintCurrentTest(t)()
ctx, f := createRepoAndGetContext(t, []string{"README.org", "README.txt", "README.tex"}, true)
defer f()
@ -109,9 +107,8 @@ func TestRepoView_FindReadme(t *testing.T) {
assert.Equal(t, "README.org", file.Name())
})
})
t.Run("PrioFiveTxtReadme", func(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
defer tests.PrintCurrentTest(t)()
ctx, f := createRepoAndGetContext(t, []string{"README.txt", "README", "README.tex"}, true)
defer f()
@ -121,9 +118,8 @@ func TestRepoView_FindReadme(t *testing.T) {
assert.Equal(t, "README.txt", file.Name())
})
})
t.Run("PrioSixWithoutExtensionReadme", func(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
defer tests.PrintCurrentTest(t)()
ctx, f := createRepoAndGetContext(t, []string{"README", "README.tex"}, true)
defer f()
@ -133,9 +129,8 @@ func TestRepoView_FindReadme(t *testing.T) {
assert.Equal(t, "README", file.Name())
})
})
t.Run("PrioSevenAnyReadme", func(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
defer tests.PrintCurrentTest(t)()
ctx, f := createRepoAndGetContext(t, []string{"README.tex"}, true)
defer f()
@ -145,9 +140,8 @@ func TestRepoView_FindReadme(t *testing.T) {
assert.Equal(t, "README.tex", file.Name())
})
})
t.Run("DoNotPickReadmeIfNonPresent", func(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
defer tests.PrintCurrentTest(t)()
ctx, f := createRepoAndGetContext(t, []string{}, true)
defer f()

View file

@ -18,6 +18,7 @@ import (
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
files_service "code.gitea.io/gitea/services/repository/files"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@ -63,8 +64,8 @@ func getDeleteRepoFilesOptions(repo *repo_model.Repository) *files_service.Chang
Files: []*files_service.ChangeRepoFile{
{
Operation: "delete",
TreePath: "README.md",
SHA: "4b4851ad51df6a7d9f25c979345979eaeb5b349f",
TreePath: "README_new.md",
SHA: "dbf8d00e022e05b7e5cf7e535de857de57925647",
},
},
LastCommitID: "",
@ -244,52 +245,43 @@ func getExpectedFileResponseForRepofilesUpdate(commitID, filename, lastCommitSHA
}
}
func TestChangeRepoFilesForCreate(t *testing.T) {
// setup
func TestChangeRepoFiles(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
opts := getCreateRepoFilesOptions(repo)
// test
filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts)
// asserts
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo)
require.NoError(t, err)
gitRepo, _ := gitrepo.OpenRepository(git.DefaultContext, repo)
defer gitRepo.Close()
commitID, _ := gitRepo.GetBranchCommitID(opts.NewBranch)
lastCommit, _ := gitRepo.GetCommitByPath("new/file.txt")
t.Run("Create", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
opts := getCreateRepoFilesOptions(repo)
filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts)
require.NoError(t, err)
commitID, err := gitRepo.GetBranchCommitID(opts.NewBranch)
require.NoError(t, err)
lastCommit, err := gitRepo.GetCommitByPath("new/file.txt")
require.NoError(t, err)
expectedFileResponse := getExpectedFileResponseForRepofilesCreate(commitID, lastCommit.ID.String())
assert.NotNil(t, expectedFileResponse)
if expectedFileResponse != nil {
assert.EqualValues(t, expectedFileResponse.Content, filesResponse.Files[0])
assert.EqualValues(t, expectedFileResponse.Commit.SHA, filesResponse.Commit.SHA)
assert.EqualValues(t, expectedFileResponse.Commit.HTMLURL, filesResponse.Commit.HTMLURL)
assert.EqualValues(t, expectedFileResponse.Commit.Author.Email, filesResponse.Commit.Author.Email)
assert.EqualValues(t, expectedFileResponse.Commit.Author.Name, filesResponse.Commit.Author.Name)
}
})
}
func TestChangeRepoFilesForUpdate(t *testing.T) {
// setup
onGiteaRun(t, func(t *testing.T, u *url.URL) {
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
t.Run("Update", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
opts := getUpdateRepoFilesOptions(repo)
// test
filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts)
// asserts
require.NoError(t, err)
gitRepo, _ := gitrepo.OpenRepository(git.DefaultContext, repo)
defer gitRepo.Close()
commit, _ := gitRepo.GetBranchCommit(opts.NewBranch)
lastCommit, _ := commit.GetCommitByPath(opts.Files[0].TreePath)
commit, err := gitRepo.GetBranchCommit(opts.NewBranch)
require.NoError(t, err)
lastCommit, err := commit.GetCommitByPath(opts.Files[0].TreePath)
require.NoError(t, err)
expectedFileResponse := getExpectedFileResponseForRepofilesUpdate(commit.ID.String(), opts.Files[0].TreePath, lastCommit.ID.String())
assert.EqualValues(t, expectedFileResponse.Content, filesResponse.Files[0])
assert.EqualValues(t, expectedFileResponse.Commit.SHA, filesResponse.Commit.SHA)
@ -297,28 +289,22 @@ func TestChangeRepoFilesForUpdate(t *testing.T) {
assert.EqualValues(t, expectedFileResponse.Commit.Author.Email, filesResponse.Commit.Author.Email)
assert.EqualValues(t, expectedFileResponse.Commit.Author.Name, filesResponse.Commit.Author.Name)
})
}
func TestChangeRepoFilesForUpdateWithFileMove(t *testing.T) {
// setup
onGiteaRun(t, func(t *testing.T, u *url.URL) {
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
t.Run("Update and move", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
opts := getUpdateRepoFilesOptions(repo)
opts.Files[0].SHA = "dbf8d00e022e05b7e5cf7e535de857de57925647"
opts.Files[0].FromTreePath = "README.md"
opts.Files[0].TreePath = "README_new.md" // new file name, README_new.md
// test
filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts)
// asserts
require.NoError(t, err)
gitRepo, _ := gitrepo.OpenRepository(git.DefaultContext, repo)
defer gitRepo.Close()
commit, _ := gitRepo.GetBranchCommit(opts.NewBranch)
lastCommit, _ := commit.GetCommitByPath(opts.Files[0].TreePath)
commit, err := gitRepo.GetBranchCommit(opts.NewBranch)
require.NoError(t, err)
lastCommit, err := commit.GetCommitByPath(opts.Files[0].TreePath)
require.NoError(t, err)
expectedFileResponse := getExpectedFileResponseForRepofilesUpdate(commit.ID.String(), opts.Files[0].TreePath, lastCommit.ID.String())
// assert that the old file no longer exists in the last commit of the branch
fromEntry, err := commit.GetTreeEntryByPath(opts.Files[0].FromTreePath)
switch err.(type) {
@ -339,45 +325,28 @@ func TestChangeRepoFilesForUpdateWithFileMove(t *testing.T) {
assert.EqualValues(t, expectedFileResponse.Commit.SHA, filesResponse.Commit.SHA)
assert.EqualValues(t, expectedFileResponse.Commit.HTMLURL, filesResponse.Commit.HTMLURL)
})
}
// Test opts with branch names removed, should get same results as above test
func TestChangeRepoFilesWithoutBranchNames(t *testing.T) {
// setup
onGiteaRun(t, func(t *testing.T, u *url.URL) {
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
t.Run("Change without branch names", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
opts := getUpdateRepoFilesOptions(repo)
opts.OldBranch = ""
opts.NewBranch = ""
opts.Files[0].TreePath = "README_new.md"
opts.Files[0].SHA = "dbf8d00e022e05b7e5cf7e535de857de57925647"
// test
filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts)
// asserts
require.NoError(t, err)
gitRepo, _ := gitrepo.OpenRepository(git.DefaultContext, repo)
defer gitRepo.Close()
commit, _ := gitRepo.GetBranchCommit(repo.DefaultBranch)
lastCommit, _ := commit.GetCommitByPath(opts.Files[0].TreePath)
expectedFileResponse := getExpectedFileResponseForRepofilesUpdate(commit.ID.String(), opts.Files[0].TreePath, lastCommit.ID.String())
assert.EqualValues(t, expectedFileResponse.Content, filesResponse.Files[0])
})
}
func TestChangeRepoFilesForDelete(t *testing.T) {
onGiteaRun(t, testDeleteRepoFiles)
}
func testDeleteRepoFiles(t *testing.T, u *url.URL) {
// setup
unittest.PrepareTestEnv(t)
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
t.Run("Delete files", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
opts := getDeleteRepoFilesOptions(repo)
t.Run("Delete README.md file", func(t *testing.T) {
filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts)
require.NoError(t, err)
expectedFileResponse := getExpectedFileResponseForRepofilesDelete()
@ -387,32 +356,21 @@ func testDeleteRepoFiles(t *testing.T, u *url.URL) {
assert.EqualValues(t, expectedFileResponse.Commit.Author.Identity, filesResponse.Commit.Author.Identity)
assert.EqualValues(t, expectedFileResponse.Commit.Committer.Identity, filesResponse.Commit.Committer.Identity)
assert.EqualValues(t, expectedFileResponse.Verification, filesResponse.Verification)
})
t.Run("Verify README.md has been deleted", func(t *testing.T) {
filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts)
filesResponse, err = files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts)
assert.Nil(t, filesResponse)
expectedError := "repository file does not exist [path: " + opts.Files[0].TreePath + "]"
assert.EqualError(t, err, expectedError)
})
}
// Test opts with branch names removed, same results
func TestChangeRepoFilesForDeleteWithoutBranchNames(t *testing.T) {
onGiteaRun(t, testDeleteRepoFilesWithoutBranchNames)
}
func testDeleteRepoFilesWithoutBranchNames(t *testing.T, u *url.URL) {
// setup
unittest.PrepareTestEnv(t)
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
t.Run("Delete without branch name", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
opts := getDeleteRepoFilesOptions(repo)
opts.OldBranch = ""
opts.NewBranch = ""
opts.Files[0].SHA = "103ff9234cefeee5ec5361d22b49fbb04d385885"
opts.Files[0].TreePath = "new/file.txt"
t.Run("Delete README.md without Branch Name", func(t *testing.T) {
filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts)
require.NoError(t, err)
expectedFileResponse := getExpectedFileResponseForRepofilesDelete()
@ -423,6 +381,7 @@ func testDeleteRepoFilesWithoutBranchNames(t *testing.T, u *url.URL) {
assert.EqualValues(t, expectedFileResponse.Commit.Committer.Identity, filesResponse.Commit.Committer.Identity)
assert.EqualValues(t, expectedFileResponse.Verification, filesResponse.Verification)
})
})
}
func TestChangeRepoFilesErrors(t *testing.T) {

View file

@ -10,20 +10,20 @@ import (
"io"
"mime/multipart"
"net/http"
"net/url"
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/avatar"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestUserAvatar(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
defer tests.PrepareTestEnv(t)()
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // owner of the repo3, is an org
seed := user2.Email
@ -79,16 +79,9 @@ func TestUserAvatar(t *testing.T) {
req = NewRequest(t, "GET", user2.AvatarLinkWithSize(db.DefaultContext, 0))
_ = session.MakeRequest(t, req, http.StatusOK)
testGetAvatarRedirect(t, user2)
req = NewRequestf(t, "GET", "/%s.png", user2.Name)
resp := MakeRequest(t, req, http.StatusSeeOther)
assert.EqualValues(t, fmt.Sprintf("/avatars/%s", user2.Avatar), resp.Header().Get("location"))
// Can't test if the response matches because the image is re-generated on upload but checking that this at least doesn't give a 404 should be enough.
})
}
func testGetAvatarRedirect(t *testing.T, user *user_model.User) {
t.Run(fmt.Sprintf("getAvatarRedirect_%s", user.Name), func(t *testing.T) {
req := NewRequestf(t, "GET", "/%s.png", user.Name)
resp := MakeRequest(t, req, http.StatusSeeOther)
assert.EqualValues(t, fmt.Sprintf("/avatars/%s", user.Avatar), resp.Header().Get("location"))
})
}

View file

@ -5,11 +5,11 @@ package integration
import (
"net/http"
"net/url"
"strconv"
"testing"
"code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
)
@ -23,7 +23,7 @@ import (
// - Profile visibility
// - Public activity visibility
func TestUserProfileActivity(t *testing.T) {
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
defer tests.PrepareTestEnv(t)()
// This test needs multiple users with different access statuses to check for all possible states
userAdmin := loginUser(t, "user1")
userRegular := loginUser(t, "user2")
@ -86,7 +86,6 @@ func TestUserProfileActivity(t *testing.T) {
// Verify that Configure link is correct
assert.EqualValues(t, "/user/settings#keep-activity-private", hintLink)
})
}
// testChangeUserActivityVisibility allows to easily change visibility of public activity for a user

View file

@ -6,10 +6,11 @@ package integration
import (
"fmt"
"net/http"
"net/url"
"strings"
"testing"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
)
@ -19,7 +20,8 @@ import (
// - Followers and Following lists have correct amounts of items
// - %d followers and %following counters are always present and always have correct numbers and use correct plurals
func TestUserProfileFollows(t *testing.T) {
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
defer tests.PrepareTestEnv(t)()
// This test needs 3 users to check for all possible states
// The accounts of user3 and user4 are not functioning
user1 := loginUser(t, "user1")
@ -104,7 +106,6 @@ func TestUserProfileFollows(t *testing.T) {
testSelectorEquals(t, page, followingLink, "2 following")
testSelectorEquals(t, page, listHeader, "Following")
testListCount(t, page, listItems, followCount)
})
}
// testUserFollowUser simply follows a user `following` by session of user `follower`