tests/integration: simplify code (#37249)

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: wxiaoguang <2114189+wxiaoguang@users.noreply.github.com>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: silverwind <me@silverwind.io>
Co-authored-by: Claude (Opus 4.7) <noreply@anthropic.com>
This commit is contained in:
Copilot
2026-04-17 20:33:49 +08:00
committed by GitHub
parent dc974715e9
commit eb334e3738
23 changed files with 168 additions and 279 deletions

View File

@@ -5,6 +5,7 @@ package test
import (
"archive/tar"
"archive/zip"
"bytes"
"compress/gzip"
"io"
@@ -97,6 +98,17 @@ func WriteTarArchive(files map[string]string) *bytes.Buffer {
return WriteTarCompression(func(w io.Writer) io.WriteCloser { return util.NopCloser{Writer: w} }, files)
}
func WriteZipArchive(files map[string]string) *bytes.Buffer {
buf := &bytes.Buffer{}
zw := zip.NewWriter(buf)
for name, content := range files {
w, _ := zw.Create(name)
_, _ = w.Write([]byte(content))
}
_ = zw.Close()
return buf
}
func WriteTarCompression[F func(io.Writer) io.WriteCloser | func(io.Writer) (io.WriteCloser, error)](compression F, files map[string]string) *bytes.Buffer {
buf := &bytes.Buffer{}
var cw io.WriteCloser

View File

@@ -40,8 +40,7 @@ func testAPICreateOAuth2Application(t *testing.T) {
AddBasicAuth(user.Name)
resp := MakeRequest(t, req, http.StatusCreated)
var createdApp *api.OAuth2Application
DecodeJSON(t, resp, &createdApp)
createdApp := DecodeJSON(t, resp, &api.OAuth2Application{})
assert.Equal(t, appBody.Name, createdApp.Name)
assert.Len(t, createdApp.ClientSecret, 56)

View File

@@ -4,7 +4,6 @@
package integration
import (
"archive/zip"
"bytes"
"fmt"
"net/http"
@@ -17,6 +16,7 @@ import (
user_model "code.gitea.io/gitea/models/user"
composer_module "code.gitea.io/gitea/modules/packages/composer"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/routers/api/packages/composer"
"code.gitea.io/gitea/tests"
@@ -38,10 +38,8 @@ func TestPackageComposer(t *testing.T) {
packageLicense := "MIT"
packageBin := "./bin/script"
var buf bytes.Buffer
archive := zip.NewWriter(&buf)
w, _ := archive.Create("composer.json")
w.Write([]byte(`{
content := test.WriteZipArchive(map[string]string{
"composer.json": `{
"name": "` + packageName + `",
"description": "` + packageDescription + `",
"type": "` + packageType + `",
@@ -54,9 +52,8 @@ func TestPackageComposer(t *testing.T) {
"bin": [
"` + packageBin + `"
]
}`))
archive.Close()
content := buf.Bytes()
}`,
}).Bytes()
url := fmt.Sprintf("%sapi/packages/%s/composer", setting.AppURL, user.Name)

View File

@@ -158,6 +158,10 @@ func uploadConanPackageV1(t *testing.T, baseURL, token, name, version, user, cha
}
func uploadConanPackageV2(t *testing.T, baseURL, token, name, version, user, channel, recipeRevision, packageRevision string) {
type fileList struct {
Files map[string]any `json:"files"`
}
contentConanfile := buildConanfileContent(name, version)
recipeURL := fmt.Sprintf("%s/v2/conans/%s/%s/%s/%s/revisions/%s", baseURL, name, version, user, channel, recipeRevision)
@@ -170,10 +174,7 @@ func uploadConanPackageV2(t *testing.T, baseURL, token, name, version, user, cha
AddTokenAuth(token)
resp := MakeRequest(t, req, http.StatusOK)
var list *struct {
Files map[string]any `json:"files"`
}
DecodeJSON(t, resp, &list)
list := DecodeJSON(t, resp, &fileList{})
assert.Len(t, list.Files, 1)
assert.Contains(t, list.Files, conanfileName)
@@ -191,8 +192,7 @@ func uploadConanPackageV2(t *testing.T, baseURL, token, name, version, user, cha
AddTokenAuth(token)
resp = MakeRequest(t, req, http.StatusOK)
list = nil
DecodeJSON(t, resp, &list)
list = DecodeJSON(t, resp, &fileList{})
assert.Len(t, list.Files, 1)
assert.Contains(t, list.Files, conaninfoName)
}
@@ -458,8 +458,7 @@ func TestPackageConan(t *testing.T) {
req := NewRequest(t, "GET", fmt.Sprintf("%s/v1/conans/search?q=%s", url, stdurl.QueryEscape(c.Query)))
resp := MakeRequest(t, req, http.StatusOK)
var result *conan_router.SearchResult
DecodeJSON(t, resp, &result)
result := DecodeJSON(t, resp, &conan_router.SearchResult{})
assert.ElementsMatch(t, c.Expected, result.Results, "case %d: unexpected result", i)
}
@@ -702,8 +701,7 @@ func TestPackageConan(t *testing.T) {
Revisions []*RevisionInfo `json:"revisions"`
}
var list *RevisionList
DecodeJSON(t, resp, &list)
list := DecodeJSON(t, resp, &RevisionList{})
assert.Len(t, list.Revisions, 2)
revs := make([]string, 0, len(list.Revisions))
for _, rev := range list.Revisions {
@@ -714,7 +712,7 @@ func TestPackageConan(t *testing.T) {
req = NewRequest(t, "GET", fmt.Sprintf("%s/%s/packages/%s/revisions", recipeURL, revision1, conanPackageReference))
resp = MakeRequest(t, req, http.StatusOK)
DecodeJSON(t, resp, &list)
list = DecodeJSON(t, resp, &RevisionList{})
assert.Len(t, list.Revisions, 2)
revs = make([]string, 0, len(list.Revisions))
for _, rev := range list.Revisions {
@@ -754,8 +752,7 @@ func TestPackageConan(t *testing.T) {
req := NewRequest(t, "GET", fmt.Sprintf("%s/v2/conans/search?q=%s", url, stdurl.QueryEscape(c.Query)))
resp := MakeRequest(t, req, http.StatusOK)
var result *conan_router.SearchResult
DecodeJSON(t, resp, &result)
result := DecodeJSON(t, resp, &conan_router.SearchResult{})
assert.ElementsMatch(t, c.Expected, result.Results, "case %d: unexpected result", i)
}

View File

@@ -5,7 +5,6 @@ package integration
import (
"archive/tar"
"archive/zip"
"bytes"
"fmt"
"io"
@@ -16,6 +15,7 @@ import (
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
conda_module "code.gitea.io/gitea/modules/packages/conda"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/modules/zstd"
"code.gitea.io/gitea/tests"
@@ -94,11 +94,9 @@ func TestPackageConda(t *testing.T) {
io.Copy(zsw, bytes.NewReader(tarContent))
zsw.Close()
var buf bytes.Buffer
zpw := zip.NewWriter(&buf)
w, _ := zpw.Create("info-x.tar.zst")
w.Write(infoBuf.Bytes())
zpw.Close()
buf := test.WriteZipArchive(map[string]string{
"info-x.tar.zst": infoBuf.String(),
})
fullName := channel + "/" + packageName
filename := fmt.Sprintf("%s-%s.conda", packageName, packageVersion)

View File

@@ -5,7 +5,6 @@ package integration
import (
"archive/tar"
"archive/zip"
"bytes"
"compress/gzip"
"fmt"
@@ -16,6 +15,7 @@ import (
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
cran_module "code.gitea.io/gitea/modules/packages/cran"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
@@ -144,15 +144,6 @@ func TestPackageCran(t *testing.T) {
})
t.Run("Binary", func(t *testing.T) {
createArchive := func(filename string, content []byte) *bytes.Buffer {
var buf bytes.Buffer
archive := zip.NewWriter(&buf)
w, _ := archive.Create(filename)
w.Write(content)
archive.Close()
return &buf
}
t.Run("Upload", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
@@ -161,24 +152,21 @@ func TestPackageCran(t *testing.T) {
req := NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader([]byte{}))
MakeRequest(t, req, http.StatusUnauthorized)
req = NewRequestWithBody(t, "PUT", uploadURL, createArchive(
"dummy.txt",
[]byte{},
)).AddBasicAuth(user.Name)
req = NewRequestWithBody(t, "PUT", uploadURL, test.WriteZipArchive(map[string]string{
"dummy.txt": "",
})).AddBasicAuth(user.Name)
MakeRequest(t, req, http.StatusBadRequest)
req = NewRequestWithBody(t, "PUT", uploadURL+"?platform=&rversion=", createArchive(
"package/DESCRIPTION",
createDescription(packageName, packageVersion),
)).AddBasicAuth(user.Name)
req = NewRequestWithBody(t, "PUT", uploadURL+"?platform=&rversion=", test.WriteZipArchive(map[string]string{
"package/DESCRIPTION": string(createDescription(packageName, packageVersion)),
})).AddBasicAuth(user.Name)
MakeRequest(t, req, http.StatusBadRequest)
uploadURL += "?platform=windows&rversion=4.2"
req = NewRequestWithBody(t, "PUT", uploadURL, createArchive(
"package/DESCRIPTION",
createDescription(packageName, packageVersion),
)).AddBasicAuth(user.Name)
req = NewRequestWithBody(t, "PUT", uploadURL, test.WriteZipArchive(map[string]string{
"package/DESCRIPTION": string(createDescription(packageName, packageVersion)),
})).AddBasicAuth(user.Name)
MakeRequest(t, req, http.StatusCreated)
pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeCran)
@@ -189,10 +177,9 @@ func TestPackageCran(t *testing.T) {
assert.NoError(t, err)
assert.Len(t, pfs, 2)
req = NewRequestWithBody(t, "PUT", uploadURL, createArchive(
"package/DESCRIPTION",
createDescription(packageName, packageVersion),
)).AddBasicAuth(user.Name)
req = NewRequestWithBody(t, "PUT", uploadURL, test.WriteZipArchive(map[string]string{
"package/DESCRIPTION": string(createDescription(packageName, packageVersion)),
})).AddBasicAuth(user.Name)
MakeRequest(t, req, http.StatusConflict)
})

View File

@@ -4,7 +4,6 @@
package integration
import (
"archive/zip"
"bytes"
"fmt"
"net/http"
@@ -14,6 +13,7 @@ import (
"code.gitea.io/gitea/models/packages"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
@@ -29,23 +29,12 @@ func TestPackageGo(t *testing.T) {
packageVersion2 := "v0.0.2"
goModContent := `module "gitea.com/go-gitea/gitea"`
createArchive := func(files map[string][]byte) []byte {
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for name, content := range files {
w, _ := zw.Create(name)
w.Write(content)
}
zw.Close()
return buf.Bytes()
}
url := fmt.Sprintf("/api/packages/%s/go", user.Name)
t.Run("Upload", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
content := createArchive(nil)
content := test.WriteZipArchive(nil).Bytes()
req := NewRequestWithBody(t, "PUT", url+"/upload", bytes.NewReader(content))
MakeRequest(t, req, http.StatusUnauthorized)
@@ -54,9 +43,9 @@ func TestPackageGo(t *testing.T) {
AddBasicAuth(user.Name)
MakeRequest(t, req, http.StatusBadRequest)
content = createArchive(map[string][]byte{
packageName + "@" + packageVersion + "/go.mod": []byte(goModContent),
})
content = test.WriteZipArchive(map[string]string{
packageName + "@" + packageVersion + "/go.mod": goModContent,
}).Bytes()
req = NewRequestWithBody(t, "PUT", url+"/upload", bytes.NewReader(content)).
AddBasicAuth(user.Name)
@@ -88,9 +77,9 @@ func TestPackageGo(t *testing.T) {
time.Sleep(time.Second) // Ensure the timestamp is different, then the "list" below can have stable order
content = createArchive(map[string][]byte{
packageName + "@" + packageVersion2 + "/go.mod": []byte(goModContent),
})
content = test.WriteZipArchive(map[string]string{
packageName + "@" + packageVersion2 + "/go.mod": goModContent,
}).Bytes()
req = NewRequestWithBody(t, "PUT", url+"/upload", bytes.NewReader(content)).
AddBasicAuth(user.Name)

View File

@@ -4,7 +4,6 @@
package integration
import (
"archive/zip"
"bytes"
"encoding/base64"
"encoding/xml"
@@ -26,6 +25,7 @@ import (
nuget_module "code.gitea.io/gitea/modules/packages/nuget"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/routers/api/packages/nuget"
packageService "code.gitea.io/gitea/services/packages"
"code.gitea.io/gitea/tests"
@@ -155,12 +155,9 @@ func TestPackageNuGet(t *testing.T) {
}
createPackage := func(id, version string) *bytes.Buffer {
var buf bytes.Buffer
archive := zip.NewWriter(&buf)
w, _ := archive.Create("package.nuspec")
w.Write([]byte(createNuspec(id, version)))
archive.Close()
return &buf
return test.WriteZipArchive(map[string]string{
"package.nuspec": createNuspec(id, version),
})
}
content := createPackage(packageName, packageVersion).Bytes()
@@ -379,11 +376,11 @@ func TestPackageNuGet(t *testing.T) {
defer tests.PrintCurrentTest(t)()
createSymbolPackage := func(id, packageType string) io.Reader {
var buf bytes.Buffer
archive := zip.NewWriter(&buf)
w, _ := archive.Create("package.nuspec")
w.Write([]byte(`<?xml version="1.0" encoding="utf-8"?>
symbolData, _ := base64.StdEncoding.DecodeString(`QlNKQgEAAQAAAAAADAAAAFBEQiB2MS4wAAAAAAAABgB8AAAAWAAAACNQZGIAAAAA1AAAAAgBAAAj
fgAA3AEAAAQAAAAjU3RyaW5ncwAAAADgAQAABAAAACNVUwDkAQAAMAAAACNHVUlEAAAAFAIAACgB
AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`)
return test.WriteZipArchive(map[string]string{
"package.nuspec": `<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd">
<metadata>
<id>` + id + `</id>
@@ -392,16 +389,9 @@ func TestPackageNuGet(t *testing.T) {
<description>` + packageDescription + `</description>
<packageTypes><packageType name="` + packageType + `" /></packageTypes>
</metadata>
</package>`))
w, _ = archive.Create(symbolFilename)
b, _ := base64.StdEncoding.DecodeString(`QlNKQgEAAQAAAAAADAAAAFBEQiB2MS4wAAAAAAAABgB8AAAAWAAAACNQZGIAAAAA1AAAAAgBAAAj
fgAA3AEAAAQAAAAjU3RyaW5ncwAAAADgAQAABAAAACNVUwDkAQAAMAAAACNHVUlEAAAAFAIAACgB
AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`)
w.Write(b)
archive.Close()
return &buf
</package>`,
symbolFilename: string(symbolData),
})
}
req := NewRequestWithBody(t, "PUT", url+"/symbolpackage", createSymbolPackage("unknown-package", "SymbolsPackage")).

View File

@@ -4,7 +4,6 @@
package integration
import (
"archive/zip"
"bytes"
"fmt"
"io"
@@ -18,6 +17,7 @@ import (
user_model "code.gitea.io/gitea/models/user"
swift_module "code.gitea.io/gitea/modules/packages/swift"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
swift_router "code.gitea.io/gitea/routers/api/packages/swift"
"code.gitea.io/gitea/tests"
@@ -113,17 +113,6 @@ func TestPackageSwift(t *testing.T) {
MakeRequest(t, req, expectedStatus)
}
createArchive := func(files map[string]string) *bytes.Buffer {
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for filename, content := range files {
w, _ := zw.Create(filename)
w.Write([]byte(content))
}
zw.Close()
return &buf
}
for _, triple := range []string{"/sc_ope/package/1.0.0", "/scope/pack~age/1.0.0", "/scope/package/1_0.0"} {
req := NewRequestWithBody(t, "PUT", url+triple, bytes.NewReader([]byte{})).
AddBasicAuth(user.Name)
@@ -142,7 +131,7 @@ func TestPackageSwift(t *testing.T) {
t,
uploadURL,
http.StatusCreated,
createArchive(map[string]string{
test.WriteZipArchive(map[string]string{
"Package.swift": contentManifest1,
"Package@swift-5.6.swift": contentManifest2,
}),
@@ -177,7 +166,7 @@ func TestPackageSwift(t *testing.T) {
t,
uploadURL,
http.StatusConflict,
createArchive(map[string]string{
test.WriteZipArchive(map[string]string{
"Package.swift": contentManifest1,
}),
"",
@@ -209,17 +198,6 @@ func TestPackageSwift(t *testing.T) {
MakeRequest(t, req, expectedStatus)
}
createArchive := func(files map[string]string) *bytes.Buffer {
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for filename, content := range files {
w, _ := zw.Create(filename)
w.Write([]byte(content))
}
zw.Close()
return &buf
}
uploadURL := fmt.Sprintf("%s/%s/%s/%s", url, packageScope, packageName, packageVersion2)
req := NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader([]byte{}))
@@ -230,7 +208,7 @@ func TestPackageSwift(t *testing.T) {
t,
uploadURL,
http.StatusCreated,
createArchive(map[string]string{
test.WriteZipArchive(map[string]string{
"Package.swift": contentManifest1,
"Package@swift-5.6.swift": contentManifest2,
}),
@@ -265,7 +243,7 @@ func TestPackageSwift(t *testing.T) {
t,
uploadURL,
http.StatusConflict,
createArchive(map[string]string{
test.WriteZipArchive(map[string]string{
"Package.swift": contentManifest1,
}),
"",
@@ -307,8 +285,7 @@ func TestPackageSwift(t *testing.T) {
body := resp.Body.String()
var result *swift_router.EnumeratePackageVersionsResponse
DecodeJSON(t, resp, &result)
result := DecodeJSON(t, resp, &swift_router.EnumeratePackageVersionsResponse{})
assert.Len(t, result.Releases, 2)
assert.Contains(t, result.Releases, packageVersion2)
@@ -333,8 +310,7 @@ func TestPackageSwift(t *testing.T) {
body := resp.Body.String()
var result *swift_router.PackageVersionMetadataResponse
DecodeJSON(t, resp, &result)
result := DecodeJSON(t, resp, &swift_router.PackageVersionMetadataResponse{})
pv, err := packages.GetVersionByNameAndVersion(t.Context(), user.ID, packages.TypeSwift, packageID, packageVersion)
assert.NotNil(t, pv)
@@ -425,8 +401,7 @@ func TestPackageSwift(t *testing.T) {
SetHeader("Accept", swift_router.AcceptJSON)
resp = MakeRequest(t, req, http.StatusOK)
var result *swift_router.LookupPackageIdentifiersResponse
DecodeJSON(t, resp, &result)
result := DecodeJSON(t, resp, &swift_router.LookupPackageIdentifiersResponse{})
assert.Len(t, result.Identifiers, 1)
assert.Equal(t, packageID, result.Identifiers[0])

View File

@@ -75,8 +75,7 @@ func TestPackageAPI(t *testing.T) {
AddTokenAuth(tokenReadPackage)
resp := MakeRequest(t, req, http.StatusOK)
var p *api.Package
DecodeJSON(t, resp, &p)
p := DecodeJSON(t, resp, &api.Package{})
assert.Equal(t, string(packages_model.TypeGeneric), p.Type)
assert.Equal(t, packageName, p.Name)
@@ -152,8 +151,7 @@ func TestPackageAPI(t *testing.T) {
AddTokenAuth(tokenReadPackage)
resp := MakeRequest(t, req, http.StatusOK)
var apiPackage *api.Package
DecodeJSON(t, resp, &apiPackage)
apiPackage := DecodeJSON(t, resp, &api.Package{})
assert.Equal(t, string(packages_model.TypeGeneric), apiPackage.Type)
assert.Equal(t, packageName, apiPackage.Name)
@@ -171,8 +169,7 @@ func TestPackageAPI(t *testing.T) {
AddTokenAuth(tokenReadPackage)
resp := MakeRequest(t, req, http.StatusOK)
var ap1 *api.Package
DecodeJSON(t, resp, &ap1)
ap1 := DecodeJSON(t, resp, &api.Package{})
assert.Nil(t, ap1.Repository)
// create a repository
@@ -189,8 +186,7 @@ func TestPackageAPI(t *testing.T) {
AddTokenAuth(tokenReadPackage)
resp = MakeRequest(t, req, http.StatusOK)
var ap2 *api.Package
DecodeJSON(t, resp, &ap2)
ap2 := DecodeJSON(t, resp, &api.Package{})
assert.NotNil(t, ap2.Repository)
assert.Equal(t, newRepo.ID, ap2.Repository.ID)
@@ -206,8 +202,7 @@ func TestPackageAPI(t *testing.T) {
AddTokenAuth(tokenReadPackage)
resp = MakeRequest(t, req, http.StatusOK)
var ap3 *api.Package
DecodeJSON(t, resp, &ap3)
ap3 := DecodeJSON(t, resp, &api.Package{})
assert.Nil(t, ap3.Repository)
// force link to a repository the currently logged-in user doesn't have access to
@@ -217,8 +212,7 @@ func TestPackageAPI(t *testing.T) {
req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s", user.Name, packageName, packageVersion)).AddTokenAuth(tokenReadPackage)
resp = MakeRequest(t, req, http.StatusOK)
var ap4 *api.Package
DecodeJSON(t, resp, &ap4)
ap4 := DecodeJSON(t, resp, &api.Package{})
assert.Nil(t, ap4.Repository)
assert.NoError(t, packages_model.UnlinkRepositoryFromAllPackages(t.Context(), privateRepoID))

View File

@@ -313,8 +313,7 @@ func testAPIGetLatestRelease(t *testing.T) {
req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/latest", owner.Name, repo.Name))
resp := MakeRequest(t, req, http.StatusOK)
var release *api.Release
DecodeJSON(t, resp, &release)
release := DecodeJSON(t, resp, &api.Release{})
assert.Equal(t, "testing-release", release.Title)
}
@@ -328,8 +327,7 @@ func testAPIGetReleaseByTag(t *testing.T) {
req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", owner.Name, repo.Name, tag))
resp := MakeRequest(t, req, http.StatusOK)
var release *api.Release
DecodeJSON(t, resp, &release)
release := DecodeJSON(t, resp, &api.Release{})
assert.Equal(t, "testing-release", release.Title)
@@ -338,8 +336,7 @@ func testAPIGetReleaseByTag(t *testing.T) {
req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", owner.Name, repo.Name, nonexistingtag))
resp = MakeRequest(t, req, http.StatusNotFound)
var err *api.APIError
DecodeJSON(t, resp, &err)
err := DecodeJSON(t, resp, &api.APIError{})
assert.NotEmpty(t, err.Message)
}

View File

@@ -100,8 +100,7 @@ echo "TestGitHookScript"
req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive", owner.Name, repo.Name).
AddTokenAuth(token)
resp := MakeRequest(t, req, http.StatusOK)
var apiGitHook *api.GitHook
DecodeJSON(t, resp, &apiGitHook)
apiGitHook := DecodeJSON(t, resp, &api.GitHook{})
assert.True(t, apiGitHook.IsActive)
assert.Equal(t, testHookContent, apiGitHook.Content)
})
@@ -134,16 +133,14 @@ echo "TestGitHookScript"
Content: testHookContent,
}).AddTokenAuth(token)
resp := MakeRequest(t, req, http.StatusOK)
var apiGitHook *api.GitHook
DecodeJSON(t, resp, &apiGitHook)
apiGitHook := DecodeJSON(t, resp, &api.GitHook{})
assert.True(t, apiGitHook.IsActive)
assert.Equal(t, testHookContent, apiGitHook.Content)
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive", owner.Name, repo.Name).
AddTokenAuth(token)
resp = MakeRequest(t, req, http.StatusOK)
var apiGitHook2 *api.GitHook
DecodeJSON(t, resp, &apiGitHook2)
apiGitHook2 := DecodeJSON(t, resp, &api.GitHook{})
assert.True(t, apiGitHook2.IsActive)
assert.Equal(t, testHookContent, apiGitHook2.Content)
})
@@ -180,8 +177,7 @@ echo "TestGitHookScript"
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/hooks/git/pre-receive", owner.Name, repo.Name).
AddTokenAuth(token)
resp := MakeRequest(t, req, http.StatusOK)
var apiGitHook2 *api.GitHook
DecodeJSON(t, resp, &apiGitHook2)
apiGitHook2 := DecodeJSON(t, resp, &api.GitHook{})
assert.False(t, apiGitHook2.IsActive)
assert.Empty(t, apiGitHook2.Content)
})

View File

@@ -48,8 +48,7 @@ func TestAPIGitTags(t *testing.T) {
AddTokenAuth(token)
res := MakeRequest(t, req, http.StatusOK)
var tag *api.AnnotatedTag
DecodeJSON(t, res, &tag)
tag := DecodeJSON(t, res, &api.AnnotatedTag{})
assert.Equal(t, aTagName, tag.Tag)
assert.Equal(t, aTag.ID.String(), tag.SHA)

View File

@@ -38,8 +38,7 @@ func TestAPICreateHook(t *testing.T) {
}).AddTokenAuth(token)
resp := MakeRequest(t, req, http.StatusCreated)
var apiHook *api.Hook
DecodeJSON(t, resp, &apiHook)
apiHook := DecodeJSON(t, resp, &api.Hook{})
assert.Equal(t, "http://example.com/", apiHook.Config["url"])
assert.Equal(t, "Bearer s3cr3t", apiHook.AuthorizationHeader)
assert.Equal(t, "CI notifications", apiHook.Name)
@@ -49,8 +48,7 @@ func TestAPICreateHook(t *testing.T) {
Name: &newName,
}).AddTokenAuth(token)
patchResp := MakeRequest(t, patchReq, http.StatusOK)
var patched *api.Hook
DecodeJSON(t, patchResp, &patched)
patched := DecodeJSON(t, patchResp, &api.Hook{})
assert.Equal(t, newName, patched.Name)
hooksURL := fmt.Sprintf("/api/v1/repos/%s/%s/hooks", owner.Name, repo.Name)
@@ -64,8 +62,7 @@ func TestAPICreateHook(t *testing.T) {
},
}).AddTokenAuth(token)
resp2 := MakeRequest(t, req2, http.StatusCreated)
var created *api.Hook
DecodeJSON(t, resp2, &created)
created := DecodeJSON(t, resp2, &api.Hook{})
assert.Empty(t, created.Name)
hookURL := fmt.Sprintf("/api/v1/repos/%s/%s/hooks/%d", owner.Name, repo.Name, created.ID)
@@ -80,8 +77,7 @@ func TestAPICreateHook(t *testing.T) {
// PATCH without Name field: name must remain "original"
patchReq2 := NewRequestWithJSON(t, "PATCH", hookURL, api.EditHookOption{}).AddTokenAuth(token)
patchResp2 := MakeRequest(t, patchReq2, http.StatusOK)
var notCleared *api.Hook
DecodeJSON(t, patchResp2, &notCleared)
notCleared := DecodeJSON(t, patchResp2, &api.Hook{})
assert.Equal(t, "original", notCleared.Name)
// PATCH with Name: "" explicitly: Name should be cleared to ""
@@ -89,7 +85,6 @@ func TestAPICreateHook(t *testing.T) {
Name: new(""),
}).AddTokenAuth(token)
clearResp := MakeRequest(t, clearReq, http.StatusOK)
var cleared *api.Hook
DecodeJSON(t, clearResp, &cleared)
cleared := DecodeJSON(t, clearResp, &api.Hook{})
assert.Empty(t, cleared.Name)
}

View File

@@ -77,8 +77,7 @@ func TestAPILFSBatch(t *testing.T) {
repo := createLFSTestRepository(t, "lfs-batch-repo")
content := []byte("dummy1")
oid := storeObjectInRepo(t, repo.ID, &content)
oid := storeObjectInRepo(t, repo.ID, "dummy1")
defer git_model.RemoveLFSMetaObjectByOid(t.Context(), repo.ID, oid)
session := loginUser(t, "user2")
@@ -255,8 +254,7 @@ func TestAPILFSBatch(t *testing.T) {
assert.True(t, exist)
repo2 := createLFSTestRepository(t, "lfs-batch2-repo")
content := []byte("dummy0")
storeObjectInRepo(t, repo2.ID, &content)
storeObjectInRepo(t, repo2.ID, "dummy0")
meta, err := git_model.GetLFSMetaObjectByOid(t.Context(), repo.ID, p.Oid)
assert.Nil(t, meta)
@@ -332,9 +330,7 @@ func TestAPILFSUpload(t *testing.T) {
setting.LFS.StartServer = true
repo := createLFSTestRepository(t, "lfs-upload-repo")
content := []byte("dummy3")
oid := storeObjectInRepo(t, repo.ID, &content)
oid := storeObjectInRepo(t, repo.ID, "dummy3")
defer git_model.RemoveLFSMetaObjectByOid(t.Context(), repo.ID, oid)
session := loginUser(t, "user2")
@@ -436,9 +432,7 @@ func TestAPILFSVerify(t *testing.T) {
setting.LFS.StartServer = true
repo := createLFSTestRepository(t, "lfs-verify-repo")
content := []byte("dummy3")
oid := storeObjectInRepo(t, repo.ID, &content)
oid := storeObjectInRepo(t, repo.ID, "dummy3")
defer git_model.RemoveLFSMetaObjectByOid(t.Context(), repo.ID, oid)
session := loginUser(t, "user2")

View File

@@ -59,8 +59,7 @@ func TestAPIRepoTags(t *testing.T) {
req = NewRequestf(t, "GET", "/api/v1/repos/%s/%s/tags/%s", user.Name, repoName, newTag.Name).
AddTokenAuth(token)
resp = MakeRequest(t, req, http.StatusOK)
var tag *api.Tag
DecodeJSON(t, resp, &tag)
tag := DecodeJSON(t, resp, &api.Tag{})
assert.Equal(t, newTag, tag)
// delete tag

View File

@@ -52,8 +52,7 @@ func TestAPIRepoTeams(t *testing.T) {
req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/teams/%s", publicOrgRepo.FullName(), "Test_Team")).
AddTokenAuth(token)
res = MakeRequest(t, req, http.StatusOK)
var team *api.Team
DecodeJSON(t, res, &team)
team := DecodeJSON(t, res, &api.Team{})
assert.Equal(t, teams[1], team)
req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/teams/%s", publicOrgRepo.FullName(), "NonExistingTeam")).

View File

@@ -86,8 +86,7 @@ func TestAPIRepoTopic(t *testing.T) {
req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/topics", user2.Name, repo2.Name)).
AddTokenAuth(token2)
res := MakeRequest(t, req, http.StatusOK)
var topics *api.TopicName
DecodeJSON(t, res, &topics)
topics := DecodeJSON(t, res, &api.TopicName{})
assert.ElementsMatch(t, []string{"topicname1", "topicname2"}, topics.TopicNames)
// Test delete a topic

View File

@@ -32,8 +32,7 @@ func TestAPITeamUser(t *testing.T) {
// read self user
req := NewRequest(t, "GET", "/api/v1/teams/1/members/user2").AddTokenAuth(user2Token)
resp := MakeRequest(t, req, http.StatusOK)
var user2 *api.User
DecodeJSON(t, resp, &user2)
user2 := DecodeJSON(t, resp, &api.User{})
user2.Created = user2.Created.In(time.Local)
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user2"})

View File

@@ -25,8 +25,7 @@ func TestAPIGetWikiPage(t *testing.T) {
req := NewRequest(t, "GET", urlStr)
resp := MakeRequest(t, req, http.StatusOK)
var page *api.WikiPage
DecodeJSON(t, resp, &page)
page := DecodeJSON(t, resp, &api.WikiPage{})
assert.Equal(t, &api.WikiPage{
WikiPageMetaData: &api.WikiPageMetaData{
@@ -222,8 +221,7 @@ func TestAPIListPageRevisions(t *testing.T) {
req := NewRequest(t, "GET", urlStr)
resp := MakeRequest(t, req, http.StatusOK)
var revisions *api.WikiCommitList
DecodeJSON(t, resp, &revisions)
revisions := DecodeJSON(t, resp, &api.WikiCommitList{})
dummyrevisions := &api.WikiCommitList{
WikiCommits: []*api.WikiCommit{

View File

@@ -4,11 +4,11 @@
package integration
import (
"archive/zip"
"bytes"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"code.gitea.io/gitea/models/auth"
@@ -17,6 +17,7 @@ import (
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/lfs"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/routers/web"
"code.gitea.io/gitea/tests"
@@ -24,8 +25,8 @@ import (
"github.com/stretchr/testify/assert"
)
func storeObjectInRepo(t *testing.T, repositoryID int64, content *[]byte) string {
pointer, err := lfs.GeneratePointer(bytes.NewReader(*content))
func storeObjectInRepo(t *testing.T, repositoryID int64, content string) string {
pointer, err := lfs.GeneratePointer(strings.NewReader(content))
assert.NoError(t, err)
_, err = git_model.NewLFSMetaObject(t.Context(), repositoryID, pointer)
@@ -34,13 +35,13 @@ func storeObjectInRepo(t *testing.T, repositoryID int64, content *[]byte) string
exist, err := contentStore.Exists(pointer)
assert.NoError(t, err)
if !exist {
err := contentStore.Put(pointer, bytes.NewReader(*content))
err := contentStore.Put(pointer, strings.NewReader(content))
assert.NoError(t, err)
}
return pointer.Oid
}
func storeAndGetLfsToken(t *testing.T, content *[]byte, extraHeader *http.Header, expectedStatus int, ts ...auth.AccessTokenScope) *httptest.ResponseRecorder {
func storeAndGetLfsToken(t *testing.T, content string, extraHeader *http.Header, expectedStatus int, ts ...auth.AccessTokenScope) *httptest.ResponseRecorder {
repo, err := repo_model.GetRepositoryByOwnerAndName(t.Context(), "user2", "repo1")
assert.NoError(t, err)
oid := storeObjectInRepo(t, repo.ID, content)
@@ -65,7 +66,7 @@ func storeAndGetLfsToken(t *testing.T, content *[]byte, extraHeader *http.Header
return resp
}
func storeAndGetLfs(t *testing.T, content *[]byte, extraHeader *http.Header, expectedStatus int) *httptest.ResponseRecorder {
func storeAndGetLfs(t *testing.T, content string, extraHeader *http.Header, expectedStatus int) *httptest.ResponseRecorder {
repo, err := repo_model.GetRepositoryByOwnerAndName(t.Context(), "user2", "repo1")
assert.NoError(t, err)
oid := storeObjectInRepo(t, repo.ID, content)
@@ -89,104 +90,84 @@ func storeAndGetLfs(t *testing.T, content *[]byte, extraHeader *http.Header, exp
return resp
}
func checkResponseTestContentEncoding(t *testing.T, content *[]byte, resp *httptest.ResponseRecorder, expectGzip bool) {
func checkResponseTestContentEncoding(t *testing.T, content string, resp *httptest.ResponseRecorder, expectGzip bool) {
contentEncoding := resp.Header().Get("Content-Encoding")
if !expectGzip || !setting.EnableGzip {
assert.NotContains(t, contentEncoding, "gzip")
result := resp.Body.Bytes()
assert.Equal(t, *content, result)
assert.Equal(t, content, resp.Body.String())
} else {
assert.Contains(t, contentEncoding, "gzip")
gzippReader, err := gzipp.NewReader(resp.Body)
gzipReader, err := gzipp.NewReader(resp.Body)
assert.NoError(t, err)
result, err := io.ReadAll(gzippReader)
result, err := io.ReadAll(gzipReader)
assert.NoError(t, err)
assert.Equal(t, *content, result)
assert.Equal(t, content, string(result))
}
}
func TestGetLFSSmall(t *testing.T) {
func TestLFSGetObject(t *testing.T) {
defer tests.PrepareTestEnv(t)()
content := []byte("A very small file\n")
resp := storeAndGetLfs(t, &content, nil, http.StatusOK)
checkResponseTestContentEncoding(t, &content, resp, false)
t.Run("GetLFSSmall", testGetLFSSmall)
t.Run("GetLFSSmallToken", testGetLFSSmallToken)
t.Run("GetLFSSmallTokenFail", testGetLFSSmallTokenFail)
t.Run("GetLFSLarge", testGetLFSLarge)
t.Run("GetLFSGzip", testGetLFSGzip)
t.Run("GetLFSZip", testGetLFSZip)
t.Run("GetLFSRangeNo", testGetLFSRangeNo)
t.Run("GetLFSRange", testGetLFSRange)
}
func TestGetLFSSmallToken(t *testing.T) {
defer tests.PrepareTestEnv(t)()
content := []byte("A very small file\n")
resp := storeAndGetLfsToken(t, &content, nil, http.StatusOK, auth.AccessTokenScopePublicOnly, auth.AccessTokenScopeReadRepository)
checkResponseTestContentEncoding(t, &content, resp, false)
func testGetLFSSmall(t *testing.T) {
content := "A very small file\n"
resp := storeAndGetLfs(t, content, nil, http.StatusOK)
checkResponseTestContentEncoding(t, content, resp, false)
}
func TestGetLFSSmallTokenFail(t *testing.T) {
defer tests.PrepareTestEnv(t)()
content := []byte("A very small file\n")
storeAndGetLfsToken(t, &content, nil, http.StatusForbidden, auth.AccessTokenScopeReadNotification)
func testGetLFSSmallToken(t *testing.T) {
content := "A very small file\n"
resp := storeAndGetLfsToken(t, content, nil, http.StatusOK, auth.AccessTokenScopePublicOnly, auth.AccessTokenScopeReadRepository)
checkResponseTestContentEncoding(t, content, resp, false)
}
func TestGetLFSLarge(t *testing.T) {
defer tests.PrepareTestEnv(t)()
content := make([]byte, web.GzipMinSize*10)
for i := range content {
content[i] = byte(i % 256)
}
resp := storeAndGetLfs(t, &content, nil, http.StatusOK)
checkResponseTestContentEncoding(t, &content, resp, true)
func testGetLFSSmallTokenFail(t *testing.T) {
content := "A very small file\n"
storeAndGetLfsToken(t, content, nil, http.StatusForbidden, auth.AccessTokenScopeReadNotification)
}
func TestGetLFSGzip(t *testing.T) {
defer tests.PrepareTestEnv(t)()
b := make([]byte, web.GzipMinSize*10)
for i := range b {
b[i] = byte(i % 256)
}
outputBuffer := bytes.NewBuffer([]byte{})
gzippWriter := gzipp.NewWriter(outputBuffer)
gzippWriter.Write(b)
gzippWriter.Close()
content := outputBuffer.Bytes()
resp := storeAndGetLfs(t, &content, nil, http.StatusOK)
checkResponseTestContentEncoding(t, &content, resp, false)
func testGetLFSLarge(t *testing.T) {
content := strings.Repeat("a", web.GzipMinSize*10)
resp := storeAndGetLfs(t, content, nil, http.StatusOK)
checkResponseTestContentEncoding(t, content, resp, true)
}
func TestGetLFSZip(t *testing.T) {
defer tests.PrepareTestEnv(t)()
b := make([]byte, web.GzipMinSize*10)
for i := range b {
b[i] = byte(i % 256)
}
outputBuffer := bytes.NewBuffer([]byte{})
zipWriter := zip.NewWriter(outputBuffer)
fileWriter, err := zipWriter.Create("default")
assert.NoError(t, err)
fileWriter.Write(b)
zipWriter.Close()
content := outputBuffer.Bytes()
resp := storeAndGetLfs(t, &content, nil, http.StatusOK)
checkResponseTestContentEncoding(t, &content, resp, false)
func testGetLFSGzip(t *testing.T) {
s := strings.Repeat("a", web.GzipMinSize*10)
outputBuffer := &bytes.Buffer{}
gzipWriter := gzipp.NewWriter(outputBuffer)
_, _ = gzipWriter.Write([]byte(s))
_ = gzipWriter.Close()
content := outputBuffer.String()
resp := storeAndGetLfs(t, content, nil, http.StatusOK)
checkResponseTestContentEncoding(t, content, resp, false)
}
func TestGetLFSRangeNo(t *testing.T) {
defer tests.PrepareTestEnv(t)()
content := []byte("123456789\n")
resp := storeAndGetLfs(t, &content, nil, http.StatusOK)
assert.Equal(t, content, resp.Body.Bytes())
func testGetLFSZip(t *testing.T) {
b := strings.Repeat("a", web.GzipMinSize*10)
content := test.WriteZipArchive(map[string]string{"default": b}).String()
resp := storeAndGetLfs(t, content, nil, http.StatusOK)
checkResponseTestContentEncoding(t, content, resp, false)
}
func TestGetLFSRange(t *testing.T) {
defer tests.PrepareTestEnv(t)()
content := []byte("123456789\n")
func testGetLFSRangeNo(t *testing.T) {
content := "123456789\n"
resp := storeAndGetLfs(t, content, nil, http.StatusOK)
assert.Equal(t, content, resp.Body.String())
}
tests := []struct {
func testGetLFSRange(t *testing.T) {
content := "123456789\n"
cases := []struct {
in string
out string
status int
@@ -207,12 +188,12 @@ func TestGetLFSRange(t *testing.T) {
{"foobar", "123456789\n", http.StatusOK},
}
for _, tt := range tests {
for _, tt := range cases {
t.Run(tt.in, func(t *testing.T) {
h := http.Header{
"Range": []string{tt.in},
}
resp := storeAndGetLfs(t, &content, &h, tt.status)
resp := storeAndGetLfs(t, content, &h, tt.status)
if tt.status == http.StatusPartialContent || tt.status == http.StatusOK {
assert.Equal(t, tt.out, resp.Body.String())
} else {

View File

@@ -555,8 +555,7 @@ func TestOAuth_GrantScopesReadUserFailRepos(t *testing.T) {
AddBasicAuth(user.Name)
resp := MakeRequest(t, req, http.StatusCreated)
var app *api.OAuth2Application
DecodeJSON(t, resp, &app)
app := DecodeJSON(t, resp, &api.OAuth2Application{})
grant := &auth_model.OAuth2Grant{
ApplicationID: app.ID,
@@ -636,8 +635,7 @@ func TestOAuth_GrantScopesReadRepositoryFailOrganization(t *testing.T) {
AddBasicAuth(user.Name)
resp := MakeRequest(t, req, http.StatusCreated)
var app *api.OAuth2Application
DecodeJSON(t, resp, &app)
app := DecodeJSON(t, resp, &api.OAuth2Application{})
grant := &auth_model.OAuth2Grant{
ApplicationID: app.ID,
@@ -776,8 +774,7 @@ func TestOAuth_GrantScopesClaimPublicOnlyGroups(t *testing.T) {
AddBasicAuth(user.Name)
appResp := MakeRequest(t, appReq, http.StatusCreated)
var app *api.OAuth2Application
DecodeJSON(t, appResp, &app)
app := DecodeJSON(t, appResp, &api.OAuth2Application{})
grant := &auth_model.OAuth2Grant{
ApplicationID: app.ID,
@@ -877,8 +874,7 @@ func TestOAuth_GrantScopesClaimAllGroups(t *testing.T) {
AddBasicAuth(user.Name)
appResp := MakeRequest(t, appReq, http.StatusCreated)
var app *api.OAuth2Application
DecodeJSON(t, appResp, &app)
app := DecodeJSON(t, appResp, &api.OAuth2Application{})
grant := &auth_model.OAuth2Grant{
ApplicationID: app.ID,

View File

@@ -157,8 +157,7 @@ func TestRepushTag(t *testing.T) {
// query the release by API and it should be a draft
req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/releases/tags/%s", owner.Name, repo.Name, "v2.0")).AddTokenAuth(token)
resp := MakeRequest(t, req, http.StatusOK)
var respRelease *api.Release
DecodeJSON(t, resp, &respRelease)
respRelease := DecodeJSON(t, resp, &api.Release{})
assert.True(t, respRelease.IsDraft)
// re-push the tag