Skip to content

Commit ec2d159

Browse files
authored
Refactor tests to prevent from unnecessary preparations (#32398)
1 parent 66971e5 commit ec2d159

File tree

6 files changed

+89
-55
lines changed

6 files changed

+89
-55
lines changed

modules/testlogger/testlogger.go

+2-4
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import (
1515

1616
"code.gitea.io/gitea/modules/log"
1717
"code.gitea.io/gitea/modules/queue"
18+
"code.gitea.io/gitea/modules/util"
1819
)
1920

2021
var (
@@ -92,10 +93,7 @@ func (w *testLoggerWriterCloser) Reset() {
9293
func PrintCurrentTest(t testing.TB, skip ...int) func() {
9394
t.Helper()
9495
start := time.Now()
95-
actualSkip := 1
96-
if len(skip) > 0 {
97-
actualSkip = skip[0] + 1
98-
}
96+
actualSkip := util.OptionalArg(skip) + 1
9997
_, filename, line, _ := runtime.Caller(actualSkip)
10098

10199
if log.CanColorStdout {

modules/util/util.go

+19
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,25 @@ func IfZero[T comparable](v, def T) T {
230230
return v
231231
}
232232

233+
// OptionalArg helps the "optional argument" in Golang:
234+
//
235+
// func foo(optArg ...int) { return OptionalArg(optArg) }
236+
// calling `foo()` gets zero value 0, calling `foo(100)` gets 100
237+
// func bar(optArg ...int) { return OptionalArg(optArg, 42) }
238+
// calling `bar()` gets default value 42, calling `bar(100)` gets 100
239+
//
240+
// Passing more than 1 item to `optArg` or `defaultValue` is undefined behavior.
241+
// At the moment only the first item is used.
242+
func OptionalArg[T any](optArg []T, defaultValue ...T) (ret T) {
243+
if len(optArg) >= 1 {
244+
return optArg[0]
245+
}
246+
if len(defaultValue) >= 1 {
247+
return defaultValue[0]
248+
}
249+
return ret
250+
}
251+
233252
func ReserveLineBreakForTextarea(input string) string {
234253
// Since the content is from a form which is a textarea, the line endings are \r\n.
235254
// It's a standard behavior of HTML.

modules/util/util_test.go

+13
Original file line numberDiff line numberDiff line change
@@ -240,3 +240,16 @@ func TestReserveLineBreakForTextarea(t *testing.T) {
240240
assert.Equal(t, ReserveLineBreakForTextarea("test\r\ndata"), "test\ndata")
241241
assert.Equal(t, ReserveLineBreakForTextarea("test\r\ndata\r\n"), "test\ndata\n")
242242
}
243+
244+
func TestOptionalArg(t *testing.T) {
245+
foo := func(other any, optArg ...int) int {
246+
return OptionalArg(optArg)
247+
}
248+
bar := func(other any, optArg ...int) int {
249+
return OptionalArg(optArg, 42)
250+
}
251+
assert.Equal(t, 0, foo(nil))
252+
assert.Equal(t, 100, foo(nil, 100))
253+
assert.Equal(t, 42, bar(nil))
254+
assert.Equal(t, 100, bar(nil, 100))
255+
}

tests/integration/api_actions_artifact_test.go

+16-9
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,15 @@ type getUploadArtifactRequest struct {
2323
RetentionDays int64
2424
}
2525

26+
func prepareTestEnvActionsArtifacts(t *testing.T) func() {
27+
t.Helper()
28+
f := tests.PrepareTestEnv(t, 1)
29+
tests.PrepareArtifactsStorage(t)
30+
return f
31+
}
32+
2633
func TestActionsArtifactUploadSingleFile(t *testing.T) {
27-
defer tests.PrepareTestEnv(t)()
34+
defer prepareTestEnvActionsArtifacts(t)()
2835

2936
// acquire artifact upload url
3037
req := NewRequestWithJSON(t, "POST", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts", getUploadArtifactRequest{
@@ -58,7 +65,7 @@ func TestActionsArtifactUploadSingleFile(t *testing.T) {
5865
}
5966

6067
func TestActionsArtifactUploadInvalidHash(t *testing.T) {
61-
defer tests.PrepareTestEnv(t)()
68+
defer prepareTestEnvActionsArtifacts(t)()
6269

6370
// artifact id 54321 not exist
6471
url := "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts/8e5b948a454515dbabfc7eb718ddddddd/upload?itemPath=artifact/abc.txt"
@@ -73,7 +80,7 @@ func TestActionsArtifactUploadInvalidHash(t *testing.T) {
7380
}
7481

7582
func TestActionsArtifactConfirmUploadWithoutName(t *testing.T) {
76-
defer tests.PrepareTestEnv(t)()
83+
defer prepareTestEnvActionsArtifacts(t)()
7784

7885
req := NewRequest(t, "PATCH", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts").
7986
AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a")
@@ -82,7 +89,7 @@ func TestActionsArtifactConfirmUploadWithoutName(t *testing.T) {
8289
}
8390

8491
func TestActionsArtifactUploadWithoutToken(t *testing.T) {
85-
defer tests.PrepareTestEnv(t)()
92+
defer prepareTestEnvActionsArtifacts(t)()
8693

8794
req := NewRequestWithJSON(t, "POST", "/api/actions_pipeline/_apis/pipelines/workflows/1/artifacts", nil)
8895
MakeRequest(t, req, http.StatusUnauthorized)
@@ -108,7 +115,7 @@ type (
108115
)
109116

110117
func TestActionsArtifactDownload(t *testing.T) {
111-
defer tests.PrepareTestEnv(t)()
118+
defer prepareTestEnvActionsArtifacts(t)()
112119

113120
req := NewRequest(t, "GET", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts").
114121
AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a")
@@ -152,7 +159,7 @@ func TestActionsArtifactDownload(t *testing.T) {
152159
}
153160

154161
func TestActionsArtifactUploadMultipleFile(t *testing.T) {
155-
defer tests.PrepareTestEnv(t)()
162+
defer prepareTestEnvActionsArtifacts(t)()
156163

157164
const testArtifactName = "multi-files"
158165

@@ -208,7 +215,7 @@ func TestActionsArtifactUploadMultipleFile(t *testing.T) {
208215
}
209216

210217
func TestActionsArtifactDownloadMultiFiles(t *testing.T) {
211-
defer tests.PrepareTestEnv(t)()
218+
defer prepareTestEnvActionsArtifacts(t)()
212219

213220
const testArtifactName = "multi-file-download"
214221

@@ -263,7 +270,7 @@ func TestActionsArtifactDownloadMultiFiles(t *testing.T) {
263270
}
264271

265272
func TestActionsArtifactUploadWithRetentionDays(t *testing.T) {
266-
defer tests.PrepareTestEnv(t)()
273+
defer prepareTestEnvActionsArtifacts(t)()
267274

268275
// acquire artifact upload url
269276
req := NewRequestWithJSON(t, "POST", "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts", getUploadArtifactRequest{
@@ -299,7 +306,7 @@ func TestActionsArtifactUploadWithRetentionDays(t *testing.T) {
299306
}
300307

301308
func TestActionsArtifactOverwrite(t *testing.T) {
302-
defer tests.PrepareTestEnv(t)()
309+
defer prepareTestEnvActionsArtifacts(t)()
303310

304311
{
305312
// download old artifact uploaded by tests above, it should 1024 A

tests/integration/api_actions_artifact_v4_test.go

+7-8
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ import (
1717
"code.gitea.io/gitea/modules/storage"
1818
"code.gitea.io/gitea/routers/api/actions"
1919
actions_service "code.gitea.io/gitea/services/actions"
20-
"code.gitea.io/gitea/tests"
2120

2221
"github.com/stretchr/testify/assert"
2322
"google.golang.org/protobuf/encoding/protojson"
@@ -34,7 +33,7 @@ func toProtoJSON(m protoreflect.ProtoMessage) io.Reader {
3433
}
3534

3635
func TestActionsArtifactV4UploadSingleFile(t *testing.T) {
37-
defer tests.PrepareTestEnv(t)()
36+
defer prepareTestEnvActionsArtifacts(t)()
3837

3938
token, err := actions_service.CreateAuthorizationToken(48, 792, 193)
4039
assert.NoError(t, err)
@@ -81,7 +80,7 @@ func TestActionsArtifactV4UploadSingleFile(t *testing.T) {
8180
}
8281

8382
func TestActionsArtifactV4UploadSingleFileWrongChecksum(t *testing.T) {
84-
defer tests.PrepareTestEnv(t)()
83+
defer prepareTestEnvActionsArtifacts(t)()
8584

8685
token, err := actions_service.CreateAuthorizationToken(48, 792, 193)
8786
assert.NoError(t, err)
@@ -125,7 +124,7 @@ func TestActionsArtifactV4UploadSingleFileWrongChecksum(t *testing.T) {
125124
}
126125

127126
func TestActionsArtifactV4UploadSingleFileWithRetentionDays(t *testing.T) {
128-
defer tests.PrepareTestEnv(t)()
127+
defer prepareTestEnvActionsArtifacts(t)()
129128

130129
token, err := actions_service.CreateAuthorizationToken(48, 792, 193)
131130
assert.NoError(t, err)
@@ -173,7 +172,7 @@ func TestActionsArtifactV4UploadSingleFileWithRetentionDays(t *testing.T) {
173172
}
174173

175174
func TestActionsArtifactV4UploadSingleFileWithPotentialHarmfulBlockID(t *testing.T) {
176-
defer tests.PrepareTestEnv(t)()
175+
defer prepareTestEnvActionsArtifacts(t)()
177176

178177
token, err := actions_service.CreateAuthorizationToken(48, 792, 193)
179178
assert.NoError(t, err)
@@ -236,7 +235,7 @@ func TestActionsArtifactV4UploadSingleFileWithPotentialHarmfulBlockID(t *testing
236235
}
237236

238237
func TestActionsArtifactV4UploadSingleFileWithChunksOutOfOrder(t *testing.T) {
239-
defer tests.PrepareTestEnv(t)()
238+
defer prepareTestEnvActionsArtifacts(t)()
240239

241240
token, err := actions_service.CreateAuthorizationToken(48, 792, 193)
242241
assert.NoError(t, err)
@@ -301,7 +300,7 @@ func TestActionsArtifactV4UploadSingleFileWithChunksOutOfOrder(t *testing.T) {
301300
}
302301

303302
func TestActionsArtifactV4DownloadSingle(t *testing.T) {
304-
defer tests.PrepareTestEnv(t)()
303+
defer prepareTestEnvActionsArtifacts(t)()
305304

306305
token, err := actions_service.CreateAuthorizationToken(48, 792, 193)
307306
assert.NoError(t, err)
@@ -336,7 +335,7 @@ func TestActionsArtifactV4DownloadSingle(t *testing.T) {
336335
}
337336

338337
func TestActionsArtifactV4Delete(t *testing.T) {
339-
defer tests.PrepareTestEnv(t)()
338+
defer prepareTestEnvActionsArtifacts(t)()
340339

341340
token, err := actions_service.CreateAuthorizationToken(48, 792, 193)
342341
assert.NoError(t, err)

tests/test_utils.go

+32-34
Original file line numberDiff line numberDiff line change
@@ -192,32 +192,7 @@ func PrepareAttachmentsStorage(t testing.TB) {
192192
}))
193193
}
194194

195-
func PrepareArtifactsStorage(t testing.TB) {
196-
// prepare actions artifacts directory and files
197-
assert.NoError(t, storage.Clean(storage.ActionsArtifacts))
198-
199-
s, err := storage.NewStorage(setting.LocalStorageType, &setting.Storage{
200-
Path: filepath.Join(filepath.Dir(setting.AppPath), "tests", "testdata", "data", "artifacts"),
201-
})
202-
assert.NoError(t, err)
203-
assert.NoError(t, s.IterateObjects("", func(p string, obj storage.Object) error {
204-
_, err = storage.Copy(storage.ActionsArtifacts, p, s, p)
205-
return err
206-
}))
207-
}
208-
209-
func PrepareTestEnv(t testing.TB, skip ...int) func() {
210-
t.Helper()
211-
ourSkip := 1
212-
if len(skip) > 0 {
213-
ourSkip += skip[0]
214-
}
215-
deferFn := PrintCurrentTest(t, ourSkip)
216-
217-
// load database fixtures
218-
assert.NoError(t, unittest.LoadFixtures())
219-
220-
// load git repo fixtures
195+
func PrepareGitRepoDirectory(t testing.TB) {
221196
assert.NoError(t, util.RemoveAll(setting.RepoRootPath))
222197
assert.NoError(t, unittest.CopyDir(path.Join(filepath.Dir(setting.AppPath), "tests/gitea-repositories-meta"), setting.RepoRootPath))
223198

@@ -241,12 +216,25 @@ func PrepareTestEnv(t testing.TB, skip ...int) func() {
241216
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "refs", "pull"), 0o755)
242217
}
243218
}
219+
}
244220

245-
// Initialize actions artifact data
246-
PrepareArtifactsStorage(t)
221+
func PrepareArtifactsStorage(t testing.TB) {
222+
// prepare actions artifacts directory and files
223+
assert.NoError(t, storage.Clean(storage.ActionsArtifacts))
224+
225+
s, err := storage.NewStorage(setting.LocalStorageType, &setting.Storage{
226+
Path: filepath.Join(filepath.Dir(setting.AppPath), "tests", "testdata", "data", "artifacts"),
227+
})
228+
assert.NoError(t, err)
229+
assert.NoError(t, s.IterateObjects("", func(p string, obj storage.Object) error {
230+
_, err = storage.Copy(storage.ActionsArtifacts, p, s, p)
231+
return err
232+
}))
233+
}
247234

235+
func PrepareLFSStorage(t testing.TB) {
248236
// load LFS object fixtures
249-
// (LFS storage can be on any of several backends, including remote servers, so we init it with the storage API)
237+
// (LFS storage can be on any of several backends, including remote servers, so init it with the storage API)
250238
lfsFixtures, err := storage.NewStorage(setting.LocalStorageType, &setting.Storage{
251239
Path: filepath.Join(filepath.Dir(setting.AppPath), "tests/gitea-lfs-meta"),
252240
})
@@ -256,7 +244,9 @@ func PrepareTestEnv(t testing.TB, skip ...int) func() {
256244
_, err := storage.Copy(storage.LFS, path, lfsFixtures, path)
257245
return err
258246
}))
247+
}
259248

249+
func PrepareCleanPackageData(t testing.TB) {
260250
// clear all package data
261251
assert.NoError(t, db.TruncateBeans(db.DefaultContext,
262252
&packages_model.Package{},
@@ -268,17 +258,25 @@ func PrepareTestEnv(t testing.TB, skip ...int) func() {
268258
&packages_model.PackageCleanupRule{},
269259
))
270260
assert.NoError(t, storage.Clean(storage.Packages))
261+
}
271262

263+
func PrepareTestEnv(t testing.TB, skip ...int) func() {
264+
t.Helper()
265+
deferFn := PrintCurrentTest(t, util.OptionalArg(skip)+1)
266+
267+
// load database fixtures
268+
assert.NoError(t, unittest.LoadFixtures())
269+
270+
// do not add more Prepare* functions here, only call necessary ones in the related test functions
271+
PrepareGitRepoDirectory(t)
272+
PrepareLFSStorage(t)
273+
PrepareCleanPackageData(t)
272274
return deferFn
273275
}
274276

275277
func PrintCurrentTest(t testing.TB, skip ...int) func() {
276278
t.Helper()
277-
actualSkip := 1
278-
if len(skip) > 0 {
279-
actualSkip = skip[0] + 1
280-
}
281-
return testlogger.PrintCurrentTest(t, actualSkip)
279+
return testlogger.PrintCurrentTest(t, util.OptionalArg(skip)+1)
282280
}
283281

284282
// Printf takes a format and args and prints the string to os.Stdout

0 commit comments

Comments
 (0)