mirror of
https://codeberg.org/forgejo/forgejo.git
synced 2024-11-21 08:31:27 -05:00
e461f0854f
* Make archival asynchronous The prime benefit being sought here is for large archives to not clog up the rendering process and cause unsightly proxy timeouts. As a secondary benefit, archive-in-progress is moved out of the way into a /tmp file so that new archival requests for the same commit will not get fulfilled based on an archive that isn't yet finished. This asynchronous system is fairly primitive; request comes in, we'll spawn off a new goroutine to handle it, then we'll mark it as done. Status requests will see if the file exists in the final location, and report the archival as done when it exists. Fixes #11265 * Archive links: drop initial delay to three-quarters of a second Some, or perhaps even most, archives will not take all that long to archive. The archive process starts as soon as the download button is initially clicked, so in theory they could be done quite quickly. Drop the initial delay down to three-quarters of a second to make it more responsive in the common case of the archive being quickly created. * archiver: restructure a little bit to facilitate testing This introduces two sync.Cond pointers to the archiver package. If they're non-nil when we go to process a request, we'll wait until signalled (at all) to proceed. The tests will then create the sync.Cond so that it can signal at-will and sanity-check the state of the queue at different phases. The author believes that nil-checking these two sync.Cond pointers on every archive processing will introduce minimal overhead with no impact on maintainability. * gofmt nit: no space around binary + operator * services: archiver: appease golangci-lint, lock queueMutex Locking/unlocking the queueMutex is allowed, but not required, for Cond.Signal() and Cond.Broadcast(). The magic at play here is just a little too much for golangci-lint, as we take the address of queueMutex and this is mostly used in archiver.go; the variable still gets flagged as unused. * archiver: tests: fix several timing nits Once we've signaled a cond var, it may take some small amount of time for the goroutines released to hit the spot we're wanting them to be at. Give them an appropriate amount of time. * archiver: tests: no underscore in var name, ungh * archiver: tests: Test* is run in a separate context than TestMain We must setup the mutex/cond variables at the beginning of any test that's going to use it, or else these will be nil when the test is actually ran. * archiver: tests: hopefully final tweak Things got shuffled around such that we carefully build up and release requests from the queue, so we can validate the state of the queue at each step. Fix some assertions that no longer hold true as fallout. * repo: Download: restore some semblance of previous behavior When archival was made async, the GET endpoint was only useful if a previous POST had initiated the download. This commit restores the previous behavior, to an extent; we'll now submit the archive request there and return a "202 Accepted" to indicate that it's processing if we didn't manage to complete the request within ~2 seconds of submission. This lets a client directly GET the archive, and gives them some indication that they may attempt to GET it again at a later time. * archiver: tests: simplify a bit further We don't need to risk failure and use time.ParseDuration to get 2 * time.Second. else if isn't really necessary if the conditions are simple enough and lead to the same result. * archiver: tests: resolve potential source of flakiness Increase all timeouts to 10 seconds; these aren't hard-coded sleeps, so there's no guarantee we'll actually take that long. If we need longer to not have a false-positive, then so be it. While here, various assert.{Not,}Equal arguments are flipped around so that the wording in error output reflects reality, where the expected argument is second and actual third. * archiver: setup infrastructure for notifying consumers of completion This API will *not* allow consumers to subscribe to specific requests being completed, just *any* request being completed. The caller is responsible for determining if their request is satisfied and waiting again if needed. * repo: archive: make GET endpoint synchronous again If the request isn't complete, this endpoint will now submit the request and wait for completion using the new API. This may still be susceptible to timeouts for larger repos, but other endpoints now exist that the web interface will use to negotiate its way through larger archive processes. * archiver: tests: amend test to include WaitForCompletion() This is a trivial one, so go ahead and include it. * archiver: tests: fix test by calling NewContext() The mutex is otherwise uninitialized, so we need to ensure that we're actually initializing it if we plan to test it. * archiver: tests: integrate new WaitForCompletion a little better We can use this to wait for archives to come in, rather than spinning and hoping with a timeout. * archiver: tests: combine numQueued declaration with next-instruction assignment * routers: repo: reap unused archiving flag from DownloadStatus() This had some planned usage before, indicating whether this request initiated the archival process or not. After several rounds of refactoring, this use was deemed not necessary for much of anything and got boiled down to !complete in all cases. * services: archiver: restructure to use a channel We now offer two forms of waiting for a request: - WaitForCompletion: wait for completion with no timeout - TimedWaitForCompletion: wait for completion with timeout In both cases, we wait for the given request's cchan to close; in the latter case, we do so with the caller-provided timeout. This completely removes the need for busy-wait loops in Download/InitiateDownload, as it's fairly clean to wait on a channel with timeout. * services: archiver: use defer to unlock now that we can This previously carried the lock into the goroutine, but an intermediate step just added the request to archiveInProgress outside of the new goroutine and removed the need for the goroutine to start out with it. * Revert "archiver: tests: combine numQueued declaration with next-instruction assignment" This reverts commitbcc5214023
. Revert "archiver: tests: integrate new WaitForCompletion a little better" This reverts commit9fc8bedb56
. Revert "archiver: tests: fix test by calling NewContext()" This reverts commit709c35685e
. Revert "archiver: tests: amend test to include WaitForCompletion()" This reverts commit75261f56bc
. * archiver: tests: first attempt at WaitForCompletion() tests * archiver: tests: slight improvement, less busy-loop Just wait for the requests to complete in order, instead of busy-waiting with a timeout. This is slightly less fragile. While here, reverse the arguments of a nearby assert.Equal() so that expected/actual are correct in any test output. * archiver: address lint nits * services: archiver: only close the channel once * services: archiver: use a struct{} for the wait channel This makes it obvious that the channel is only being used as a signal, rather than anything useful being piped through it. * archiver: tests: fix expectations Move the close of the channel into doArchive() itself; notably, before these goroutines move on to waiting on the Release cond. The tests are adjusted to reflect that we can't WaitForCompletion() after they've already completed, as WaitForCompletion() doesn't indicate that they've been released from the queue yet. * archiver: tests: set cchan to nil for comparison * archiver: move ctx.Error's back into the route handlers We shouldn't be setting this in a service, we should just be validating the request that we were handed. * services: archiver: use regex to match a hash This makes sure we don't try and use refName as a hash when it's clearly not one, e.g. heads/pull/foo. * routers: repo: remove the weird /archive/status endpoint We don't need to do this anymore, we can just continue POSTing to the archive/* endpoint until we're told the download's complete. This avoids a potential naming conflict, where a ref could start with "status/" * archiver: tests: bump reasonable timeout to 15s * archiver: tests: actually release timedReq * archiver: tests: run through inFlight instead of manually checking While we're here, add a test for manually re-processing an archive that's already been complete. Re-open the channel and mark it incomplete, so that doArchive can just mark it complete again. * initArchiveLinks: prevent default behavior from clicking * archiver: alias gitea's context, golang context import pending * archiver: simplify logic, just reconstruct slices While the previous logic was perhaps slightly more efficient, the new variant's readability is much improved. * archiver: don't block shutdown on waiting for archive The technique established launches a goroutine to do the wait, which will close a wait channel upon termination. For the timeout case, we also send back a value indicating whether the timeout was hit or not. The timeouts are expected to be relatively small, but still a multi- second delay to shutdown due to this could be unfortunate. * archiver: simplify shutdown logic We can just grab the shutdown channel from the graceful manager instead of constructing a channel to halt the caller and/or pass a result back. * Style issues * Fix mis-merge Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com> Co-authored-by: Lauris BH <lauris@nix.lv>
479 lines
18 KiB
Go
479 lines
18 KiB
Go
// Copyright 2017 The Gitea Authors. All rights reserved.
|
|
// Use of this source code is governed by a MIT-style
|
|
// license that can be found in the LICENSE file.
|
|
|
|
package integrations
|
|
|
|
import (
|
|
"fmt"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"net/url"
|
|
"testing"
|
|
|
|
"code.gitea.io/gitea/models"
|
|
"code.gitea.io/gitea/modules/setting"
|
|
api "code.gitea.io/gitea/modules/structs"
|
|
"code.gitea.io/gitea/modules/util"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
)
|
|
|
|
func TestAPIUserReposNotLogin(t *testing.T) {
|
|
defer prepareTestEnv(t)()
|
|
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
|
|
|
|
req := NewRequestf(t, "GET", "/api/v1/users/%s/repos", user.Name)
|
|
resp := MakeRequest(t, req, http.StatusOK)
|
|
|
|
var apiRepos []api.Repository
|
|
DecodeJSON(t, resp, &apiRepos)
|
|
expectedLen := models.GetCount(t, models.Repository{OwnerID: user.ID},
|
|
models.Cond("is_private = ?", false))
|
|
assert.Len(t, apiRepos, expectedLen)
|
|
for _, repo := range apiRepos {
|
|
assert.EqualValues(t, user.ID, repo.Owner.ID)
|
|
assert.False(t, repo.Private)
|
|
}
|
|
}
|
|
|
|
func TestAPISearchRepo(t *testing.T) {
|
|
defer prepareTestEnv(t)()
|
|
const keyword = "test"
|
|
|
|
req := NewRequestf(t, "GET", "/api/v1/repos/search?q=%s", keyword)
|
|
resp := MakeRequest(t, req, http.StatusOK)
|
|
|
|
var body api.SearchResults
|
|
DecodeJSON(t, resp, &body)
|
|
assert.NotEmpty(t, body.Data)
|
|
for _, repo := range body.Data {
|
|
assert.Contains(t, repo.Name, keyword)
|
|
assert.False(t, repo.Private)
|
|
}
|
|
|
|
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 15}).(*models.User)
|
|
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 16}).(*models.User)
|
|
user3 := models.AssertExistsAndLoadBean(t, &models.User{ID: 18}).(*models.User)
|
|
user4 := models.AssertExistsAndLoadBean(t, &models.User{ID: 20}).(*models.User)
|
|
orgUser := models.AssertExistsAndLoadBean(t, &models.User{ID: 17}).(*models.User)
|
|
|
|
oldAPIDefaultNum := setting.API.DefaultPagingNum
|
|
defer func() {
|
|
setting.API.DefaultPagingNum = oldAPIDefaultNum
|
|
}()
|
|
setting.API.DefaultPagingNum = 10
|
|
|
|
// Map of expected results, where key is user for login
|
|
type expectedResults map[*models.User]struct {
|
|
count int
|
|
repoOwnerID int64
|
|
repoName string
|
|
includesPrivate bool
|
|
}
|
|
|
|
testCases := []struct {
|
|
name, requestURL string
|
|
expectedResults
|
|
}{
|
|
{name: "RepositoriesMax50", requestURL: "/api/v1/repos/search?limit=50&private=false", expectedResults: expectedResults{
|
|
nil: {count: 28},
|
|
user: {count: 28},
|
|
user2: {count: 28}},
|
|
},
|
|
{name: "RepositoriesMax10", requestURL: "/api/v1/repos/search?limit=10&private=false", expectedResults: expectedResults{
|
|
nil: {count: 10},
|
|
user: {count: 10},
|
|
user2: {count: 10}},
|
|
},
|
|
{name: "RepositoriesDefault", requestURL: "/api/v1/repos/search?default&private=false", expectedResults: expectedResults{
|
|
nil: {count: 10},
|
|
user: {count: 10},
|
|
user2: {count: 10}},
|
|
},
|
|
{name: "RepositoriesByName", requestURL: fmt.Sprintf("/api/v1/repos/search?q=%s&private=false", "big_test_"), expectedResults: expectedResults{
|
|
nil: {count: 7, repoName: "big_test_"},
|
|
user: {count: 7, repoName: "big_test_"},
|
|
user2: {count: 7, repoName: "big_test_"}},
|
|
},
|
|
{name: "RepositoriesAccessibleAndRelatedToUser", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user.ID), expectedResults: expectedResults{
|
|
nil: {count: 5},
|
|
user: {count: 9, includesPrivate: true},
|
|
user2: {count: 6, includesPrivate: true}},
|
|
},
|
|
{name: "RepositoriesAccessibleAndRelatedToUser2", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user2.ID), expectedResults: expectedResults{
|
|
nil: {count: 1},
|
|
user: {count: 2, includesPrivate: true},
|
|
user2: {count: 2, includesPrivate: true},
|
|
user4: {count: 1}},
|
|
},
|
|
{name: "RepositoriesAccessibleAndRelatedToUser3", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user3.ID), expectedResults: expectedResults{
|
|
nil: {count: 1},
|
|
user: {count: 4, includesPrivate: true},
|
|
user2: {count: 3, includesPrivate: true},
|
|
user3: {count: 4, includesPrivate: true}},
|
|
},
|
|
{name: "RepositoriesOwnedByOrganization", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", orgUser.ID), expectedResults: expectedResults{
|
|
nil: {count: 1, repoOwnerID: orgUser.ID},
|
|
user: {count: 2, repoOwnerID: orgUser.ID, includesPrivate: true},
|
|
user2: {count: 1, repoOwnerID: orgUser.ID}},
|
|
},
|
|
{name: "RepositoriesAccessibleAndRelatedToUser4", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d", user4.ID), expectedResults: expectedResults{
|
|
nil: {count: 3},
|
|
user: {count: 4, includesPrivate: true},
|
|
user4: {count: 7, includesPrivate: true}}},
|
|
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeSource", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "source"), expectedResults: expectedResults{
|
|
nil: {count: 0},
|
|
user: {count: 1, includesPrivate: true},
|
|
user4: {count: 1, includesPrivate: true}}},
|
|
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeFork", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "fork"), expectedResults: expectedResults{
|
|
nil: {count: 1},
|
|
user: {count: 1},
|
|
user4: {count: 2, includesPrivate: true}}},
|
|
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeFork/Exclusive", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s&exclusive=1", user4.ID, "fork"), expectedResults: expectedResults{
|
|
nil: {count: 1},
|
|
user: {count: 1},
|
|
user4: {count: 2, includesPrivate: true}}},
|
|
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeMirror", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "mirror"), expectedResults: expectedResults{
|
|
nil: {count: 2},
|
|
user: {count: 2},
|
|
user4: {count: 4, includesPrivate: true}}},
|
|
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeMirror/Exclusive", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s&exclusive=1", user4.ID, "mirror"), expectedResults: expectedResults{
|
|
nil: {count: 1},
|
|
user: {count: 1},
|
|
user4: {count: 2, includesPrivate: true}}},
|
|
{name: "RepositoriesAccessibleAndRelatedToUser4/SearchModeCollaborative", requestURL: fmt.Sprintf("/api/v1/repos/search?uid=%d&mode=%s", user4.ID, "collaborative"), expectedResults: expectedResults{
|
|
nil: {count: 0},
|
|
user: {count: 1, includesPrivate: true},
|
|
user4: {count: 1, includesPrivate: true}}},
|
|
}
|
|
|
|
for _, testCase := range testCases {
|
|
t.Run(testCase.name, func(t *testing.T) {
|
|
for userToLogin, expected := range testCase.expectedResults {
|
|
var session *TestSession
|
|
var testName string
|
|
var userID int64
|
|
var token string
|
|
if userToLogin != nil && userToLogin.ID > 0 {
|
|
testName = fmt.Sprintf("LoggedUser%d", userToLogin.ID)
|
|
session = loginUser(t, userToLogin.Name)
|
|
token = getTokenForLoggedInUser(t, session)
|
|
userID = userToLogin.ID
|
|
} else {
|
|
testName = "AnonymousUser"
|
|
session = emptyTestSession(t)
|
|
}
|
|
|
|
t.Run(testName, func(t *testing.T) {
|
|
request := NewRequest(t, "GET", testCase.requestURL+"&token="+token)
|
|
response := session.MakeRequest(t, request, http.StatusOK)
|
|
|
|
var body api.SearchResults
|
|
DecodeJSON(t, response, &body)
|
|
|
|
repoNames := make([]string, 0, len(body.Data))
|
|
for _, repo := range body.Data {
|
|
repoNames = append(repoNames, fmt.Sprintf("%d:%s:%t", repo.ID, repo.FullName, repo.Private))
|
|
}
|
|
assert.Len(t, repoNames, expected.count)
|
|
for _, repo := range body.Data {
|
|
r := getRepo(t, repo.ID)
|
|
hasAccess, err := models.HasAccess(userID, r)
|
|
assert.NoError(t, err, "Error when checking if User: %d has access to %s: %v", userID, repo.FullName, err)
|
|
assert.True(t, hasAccess, "User: %d does not have access to %s", userID, repo.FullName)
|
|
|
|
assert.NotEmpty(t, repo.Name)
|
|
assert.Equal(t, repo.Name, r.Name)
|
|
|
|
if len(expected.repoName) > 0 {
|
|
assert.Contains(t, repo.Name, expected.repoName)
|
|
}
|
|
|
|
if expected.repoOwnerID > 0 {
|
|
assert.Equal(t, expected.repoOwnerID, repo.Owner.ID)
|
|
}
|
|
|
|
if !expected.includesPrivate {
|
|
assert.False(t, repo.Private, "User: %d not expecting private repository: %s", userID, repo.FullName)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
var repoCache = make(map[int64]*models.Repository)
|
|
|
|
func getRepo(t *testing.T, repoID int64) *models.Repository {
|
|
if _, ok := repoCache[repoID]; !ok {
|
|
repoCache[repoID] = models.AssertExistsAndLoadBean(t, &models.Repository{ID: repoID}).(*models.Repository)
|
|
}
|
|
return repoCache[repoID]
|
|
}
|
|
|
|
func TestAPIViewRepo(t *testing.T) {
|
|
defer prepareTestEnv(t)()
|
|
|
|
var repo api.Repository
|
|
|
|
req := NewRequest(t, "GET", "/api/v1/repos/user2/repo1")
|
|
resp := MakeRequest(t, req, http.StatusOK)
|
|
DecodeJSON(t, resp, &repo)
|
|
assert.EqualValues(t, 1, repo.ID)
|
|
assert.EqualValues(t, "repo1", repo.Name)
|
|
assert.EqualValues(t, 2, repo.Releases)
|
|
assert.EqualValues(t, 1, repo.OpenIssues)
|
|
assert.EqualValues(t, 3, repo.OpenPulls)
|
|
|
|
req = NewRequest(t, "GET", "/api/v1/repos/user12/repo10")
|
|
resp = MakeRequest(t, req, http.StatusOK)
|
|
DecodeJSON(t, resp, &repo)
|
|
assert.EqualValues(t, 10, repo.ID)
|
|
assert.EqualValues(t, "repo10", repo.Name)
|
|
assert.EqualValues(t, 1, repo.OpenPulls)
|
|
assert.EqualValues(t, 1, repo.Forks)
|
|
|
|
req = NewRequest(t, "GET", "/api/v1/repos/user5/repo4")
|
|
resp = MakeRequest(t, req, http.StatusOK)
|
|
DecodeJSON(t, resp, &repo)
|
|
assert.EqualValues(t, 4, repo.ID)
|
|
assert.EqualValues(t, "repo4", repo.Name)
|
|
assert.EqualValues(t, 1, repo.Stars)
|
|
}
|
|
|
|
func TestAPIOrgRepos(t *testing.T) {
|
|
defer prepareTestEnv(t)()
|
|
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
|
|
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
|
|
user3 := models.AssertExistsAndLoadBean(t, &models.User{ID: 5}).(*models.User)
|
|
// User3 is an Org. Check their repos.
|
|
sourceOrg := models.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User)
|
|
|
|
expectedResults := map[*models.User]struct {
|
|
count int
|
|
includesPrivate bool
|
|
}{
|
|
nil: {count: 1},
|
|
user: {count: 3, includesPrivate: true},
|
|
user2: {count: 3, includesPrivate: true},
|
|
user3: {count: 1},
|
|
}
|
|
|
|
for userToLogin, expected := range expectedResults {
|
|
var session *TestSession
|
|
var testName string
|
|
var token string
|
|
if userToLogin != nil && userToLogin.ID > 0 {
|
|
testName = fmt.Sprintf("LoggedUser%d", userToLogin.ID)
|
|
session = loginUser(t, userToLogin.Name)
|
|
token = getTokenForLoggedInUser(t, session)
|
|
} else {
|
|
testName = "AnonymousUser"
|
|
session = emptyTestSession(t)
|
|
}
|
|
t.Run(testName, func(t *testing.T) {
|
|
req := NewRequestf(t, "GET", "/api/v1/orgs/%s/repos?token="+token, sourceOrg.Name)
|
|
resp := session.MakeRequest(t, req, http.StatusOK)
|
|
|
|
var apiRepos []*api.Repository
|
|
DecodeJSON(t, resp, &apiRepos)
|
|
assert.Len(t, apiRepos, expected.count)
|
|
for _, repo := range apiRepos {
|
|
if !expected.includesPrivate {
|
|
assert.False(t, repo.Private)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestAPIGetRepoByIDUnauthorized(t *testing.T) {
|
|
defer prepareTestEnv(t)()
|
|
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User)
|
|
session := loginUser(t, user.Name)
|
|
token := getTokenForLoggedInUser(t, session)
|
|
req := NewRequestf(t, "GET", "/api/v1/repositories/2?token="+token)
|
|
session.MakeRequest(t, req, http.StatusNotFound)
|
|
}
|
|
|
|
func TestAPIRepoMigrate(t *testing.T) {
|
|
testCases := []struct {
|
|
ctxUserID, userID int64
|
|
cloneURL, repoName string
|
|
expectedStatus int
|
|
}{
|
|
{ctxUserID: 1, userID: 2, cloneURL: "https://github.com/go-gitea/test_repo.git", repoName: "git-admin", expectedStatus: http.StatusCreated},
|
|
{ctxUserID: 2, userID: 2, cloneURL: "https://github.com/go-gitea/test_repo.git", repoName: "git-own", expectedStatus: http.StatusCreated},
|
|
{ctxUserID: 2, userID: 1, cloneURL: "https://github.com/go-gitea/test_repo.git", repoName: "git-bad", expectedStatus: http.StatusForbidden},
|
|
{ctxUserID: 2, userID: 3, cloneURL: "https://github.com/go-gitea/test_repo.git", repoName: "git-org", expectedStatus: http.StatusCreated},
|
|
{ctxUserID: 2, userID: 6, cloneURL: "https://github.com/go-gitea/test_repo.git", repoName: "git-bad-org", expectedStatus: http.StatusForbidden},
|
|
}
|
|
|
|
defer prepareTestEnv(t)()
|
|
for _, testCase := range testCases {
|
|
user := models.AssertExistsAndLoadBean(t, &models.User{ID: testCase.ctxUserID}).(*models.User)
|
|
session := loginUser(t, user.Name)
|
|
token := getTokenForLoggedInUser(t, session)
|
|
req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate?token="+token, &api.MigrateRepoOptions{
|
|
CloneAddr: testCase.cloneURL,
|
|
RepoOwnerID: testCase.userID,
|
|
RepoName: testCase.repoName,
|
|
})
|
|
resp := MakeRequest(t, req, NoExpectedStatus)
|
|
if resp.Code == http.StatusUnprocessableEntity {
|
|
respJSON := map[string]string{}
|
|
DecodeJSON(t, resp, &respJSON)
|
|
if assert.Equal(t, respJSON["message"], "Remote visit addressed rate limitation.") {
|
|
t.Log("test hit github rate limitation")
|
|
}
|
|
} else {
|
|
assert.EqualValues(t, testCase.expectedStatus, resp.Code)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestAPIRepoMigrateConflict(t *testing.T) {
|
|
onGiteaRun(t, testAPIRepoMigrateConflict)
|
|
}
|
|
|
|
func testAPIRepoMigrateConflict(t *testing.T, u *url.URL) {
|
|
username := "user2"
|
|
baseAPITestContext := NewAPITestContext(t, username, "repo1")
|
|
|
|
u.Path = baseAPITestContext.GitPath()
|
|
|
|
t.Run("Existing", func(t *testing.T) {
|
|
httpContext := baseAPITestContext
|
|
|
|
httpContext.Reponame = "repo-tmp-17"
|
|
dstPath, err := ioutil.TempDir("", httpContext.Reponame)
|
|
assert.NoError(t, err)
|
|
defer util.RemoveAll(dstPath)
|
|
t.Run("CreateRepo", doAPICreateRepository(httpContext, false))
|
|
|
|
user, err := models.GetUserByName(httpContext.Username)
|
|
assert.NoError(t, err)
|
|
userID := user.ID
|
|
|
|
cloneURL := "https://github.com/go-gitea/test_repo.git"
|
|
|
|
req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate?token="+httpContext.Token,
|
|
&api.MigrateRepoOptions{
|
|
CloneAddr: cloneURL,
|
|
RepoOwnerID: userID,
|
|
RepoName: httpContext.Reponame,
|
|
})
|
|
resp := httpContext.Session.MakeRequest(t, req, http.StatusConflict)
|
|
respJSON := map[string]string{}
|
|
DecodeJSON(t, resp, &respJSON)
|
|
assert.Equal(t, "The repository with the same name already exists.", respJSON["message"])
|
|
})
|
|
}
|
|
|
|
func TestAPIOrgRepoCreate(t *testing.T) {
|
|
testCases := []struct {
|
|
ctxUserID int64
|
|
orgName, repoName string
|
|
expectedStatus int
|
|
}{
|
|
{ctxUserID: 1, orgName: "user3", repoName: "repo-admin", expectedStatus: http.StatusCreated},
|
|
{ctxUserID: 2, orgName: "user3", repoName: "repo-own", expectedStatus: http.StatusCreated},
|
|
{ctxUserID: 2, orgName: "user6", repoName: "repo-bad-org", expectedStatus: http.StatusForbidden},
|
|
{ctxUserID: 28, orgName: "user3", repoName: "repo-creator", expectedStatus: http.StatusCreated},
|
|
{ctxUserID: 28, orgName: "user6", repoName: "repo-not-creator", expectedStatus: http.StatusForbidden},
|
|
}
|
|
|
|
defer prepareTestEnv(t)()
|
|
for _, testCase := range testCases {
|
|
user := models.AssertExistsAndLoadBean(t, &models.User{ID: testCase.ctxUserID}).(*models.User)
|
|
session := loginUser(t, user.Name)
|
|
token := getTokenForLoggedInUser(t, session)
|
|
req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/org/%s/repos?token="+token, testCase.orgName), &api.CreateRepoOption{
|
|
Name: testCase.repoName,
|
|
})
|
|
session.MakeRequest(t, req, testCase.expectedStatus)
|
|
}
|
|
}
|
|
|
|
func TestAPIRepoCreateConflict(t *testing.T) {
|
|
onGiteaRun(t, testAPIRepoCreateConflict)
|
|
}
|
|
|
|
func testAPIRepoCreateConflict(t *testing.T, u *url.URL) {
|
|
username := "user2"
|
|
baseAPITestContext := NewAPITestContext(t, username, "repo1")
|
|
|
|
u.Path = baseAPITestContext.GitPath()
|
|
|
|
t.Run("Existing", func(t *testing.T) {
|
|
httpContext := baseAPITestContext
|
|
|
|
httpContext.Reponame = "repo-tmp-17"
|
|
dstPath, err := ioutil.TempDir("", httpContext.Reponame)
|
|
assert.NoError(t, err)
|
|
defer util.RemoveAll(dstPath)
|
|
t.Run("CreateRepo", doAPICreateRepository(httpContext, false))
|
|
|
|
req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos?token="+httpContext.Token,
|
|
&api.CreateRepoOption{
|
|
Name: httpContext.Reponame,
|
|
})
|
|
resp := httpContext.Session.MakeRequest(t, req, http.StatusConflict)
|
|
respJSON := map[string]string{}
|
|
DecodeJSON(t, resp, &respJSON)
|
|
assert.Equal(t, respJSON["message"], "The repository with the same name already exists.")
|
|
})
|
|
}
|
|
|
|
func TestAPIRepoTransfer(t *testing.T) {
|
|
testCases := []struct {
|
|
ctxUserID int64
|
|
newOwner string
|
|
teams *[]int64
|
|
expectedStatus int
|
|
}{
|
|
{ctxUserID: 1, newOwner: "user2", teams: nil, expectedStatus: http.StatusAccepted},
|
|
{ctxUserID: 2, newOwner: "user1", teams: nil, expectedStatus: http.StatusAccepted},
|
|
{ctxUserID: 2, newOwner: "user6", teams: nil, expectedStatus: http.StatusForbidden},
|
|
{ctxUserID: 1, newOwner: "user2", teams: &[]int64{2}, expectedStatus: http.StatusUnprocessableEntity},
|
|
{ctxUserID: 1, newOwner: "user3", teams: &[]int64{5}, expectedStatus: http.StatusForbidden},
|
|
{ctxUserID: 1, newOwner: "user3", teams: &[]int64{2}, expectedStatus: http.StatusAccepted},
|
|
}
|
|
|
|
defer prepareTestEnv(t)()
|
|
|
|
//create repo to move
|
|
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
|
|
session := loginUser(t, user.Name)
|
|
token := getTokenForLoggedInUser(t, session)
|
|
repoName := "moveME"
|
|
repo := new(models.Repository)
|
|
req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/user/repos?token=%s", token), &api.CreateRepoOption{
|
|
Name: repoName,
|
|
Description: "repo move around",
|
|
Private: false,
|
|
Readme: "Default",
|
|
AutoInit: true,
|
|
})
|
|
resp := session.MakeRequest(t, req, http.StatusCreated)
|
|
DecodeJSON(t, resp, repo)
|
|
|
|
//start testing
|
|
for _, testCase := range testCases {
|
|
user = models.AssertExistsAndLoadBean(t, &models.User{ID: testCase.ctxUserID}).(*models.User)
|
|
repo = models.AssertExistsAndLoadBean(t, &models.Repository{ID: repo.ID}).(*models.Repository)
|
|
session = loginUser(t, user.Name)
|
|
token = getTokenForLoggedInUser(t, session)
|
|
req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer?token=%s", repo.OwnerName, repo.Name, token), &api.TransferRepoOption{
|
|
NewOwner: testCase.newOwner,
|
|
TeamIDs: testCase.teams,
|
|
})
|
|
session.MakeRequest(t, req, testCase.expectedStatus)
|
|
}
|
|
|
|
//cleanup
|
|
repo = models.AssertExistsAndLoadBean(t, &models.Repository{ID: repo.ID}).(*models.Repository)
|
|
_ = models.DeleteRepository(user, repo.OwnerID, repo.ID)
|
|
}
|