From 2a02734f93c0091275c77e370b7eed03b2c5f18e Mon Sep 17 00:00:00 2001 From: TheFox0x7 Date: Thu, 9 Jan 2025 02:21:47 +0100 Subject: [PATCH] Refactor older tests to use testify (#33140) Refactor checks to use assert/require Use require.Eventually for waiting in elastic and meilisearch tests Use require to exit early instead of assert --- models/asymkey/gpg_key_test.go | 6 +- models/db/engine_test.go | 9 +-- models/organization/org_test.go | 6 +- models/user/openid_test.go | 24 +++---- modules/analyze/vendor_test.go | 11 +-- modules/auth/openid/discovery_cache_test.go | 21 +++--- modules/emoji/emoji_test.go | 33 +++------ modules/eventsource/event_test.go | 17 ++--- modules/git/blob_test.go | 4 +- modules/git/commit_sha256_test.go | 5 +- modules/git/commit_test.go | 9 +-- modules/git/repo_language_stats_test.go | 10 ++- modules/git/repo_tag_test.go | 1 - modules/gitgraph/graph_test.go | 10 ++- modules/httplib/serve_test.go | 5 +- .../elasticsearch/elasticsearch_test.go | 18 ++--- modules/indexer/issues/indexer_test.go | 55 ++++----------- .../issues/meilisearch/meilisearch_test.go | 17 ++--- modules/issue/template/template_test.go | 5 +- modules/markup/markdown/renderconfig_test.go | 24 +++---- modules/nosql/redis_test.go | 9 ++- modules/queue/base_levelqueue_test.go | 5 +- modules/queue/base_redis_test.go | 5 +- modules/structs/commit_status_test.go | 6 +- modules/user/user_test.go | 22 +++--- modules/util/shellquote_test.go | 10 +-- modules/web/routing/funcinfo_test.go | 12 ++-- routers/utils/utils_test.go | 7 +- routers/web/repo/pull_review_test.go | 16 ++--- routers/web/repo/wiki_test.go | 10 ++- services/auth/auth_test.go | 22 +++--- services/doctor/dbconsistency_test.go | 5 +- services/gitdiff/csv_test.go | 13 ++-- services/gitdiff/gitdiff_test.go | 6 +- services/mailer/mail_test.go | 4 +- services/migrations/gitea_downloader_test.go | 9 +-- services/wiki/wiki_test.go | 21 +++--- tests/integration/api_pull_commits_test.go | 5 +- tests/integration/api_pull_review_test.go | 6 +- tests/integration/git_general_test.go | 68 +++++++------------ tests/integration/gpg_git_test.go | 5 +- tests/integration/nonascii_branches_test.go | 10 +-- 42 files changed, 218 insertions(+), 348 deletions(-) diff --git a/models/asymkey/gpg_key_test.go b/models/asymkey/gpg_key_test.go index d3fbb01d82..0bccbb51b5 100644 --- a/models/asymkey/gpg_key_test.go +++ b/models/asymkey/gpg_key_test.go @@ -15,6 +15,7 @@ import ( "github.com/keybase/go-crypto/openpgp/packet" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCheckArmoredGPGKeyString(t *testing.T) { @@ -107,9 +108,8 @@ MkM/fdpyc2hY7Dl/+qFmN5MG5yGmMpQcX+RNNR222ibNC1D3wg== =i9b7 -----END PGP PUBLIC KEY BLOCK-----` keys, err := checkArmoredGPGKeyString(testGPGArmor) - if !assert.NotEmpty(t, keys) { - return - } + require.NotEmpty(t, keys) + ekey := keys[0] assert.NoError(t, err, "Could not parse a valid GPG armored key", ekey) diff --git a/models/db/engine_test.go b/models/db/engine_test.go index e3dbfbdc24..10a1a33ff0 100644 --- a/models/db/engine_test.go +++ b/models/db/engine_test.go @@ -15,6 +15,7 @@ import ( _ "code.gitea.io/gitea/cmd" // for TestPrimaryKeys "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestDumpDatabase(t *testing.T) { @@ -62,9 +63,7 @@ func TestPrimaryKeys(t *testing.T) { // Import "code.gitea.io/gitea/cmd" to make sure each db.RegisterModel in init functions has been called. beans, err := db.NamesToBean() - if err != nil { - t.Fatal(err) - } + require.NoError(t, err) whitelist := map[string]string{ "the_table_name_to_skip_checking": "Write a note here to explain why", @@ -79,8 +78,6 @@ func TestPrimaryKeys(t *testing.T) { t.Logf("ignore %q because %q", table.Name, why) continue } - if len(table.PrimaryKeys) == 0 { - t.Errorf("table %q has no primary key", table.Name) - } + assert.NotEmpty(t, table.PrimaryKeys, "table %q has no primary key", table.Name) } } diff --git a/models/organization/org_test.go b/models/organization/org_test.go index 2c5b4090df..b882a25be3 100644 --- a/models/organization/org_test.go +++ b/models/organization/org_test.go @@ -16,6 +16,7 @@ import ( "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestUser_IsOwnedBy(t *testing.T) { @@ -180,9 +181,8 @@ func TestRestrictedUserOrgMembers(t *testing.T) { ID: 29, IsRestricted: true, }) - if !assert.True(t, restrictedUser.IsRestricted) { - return // ensure fixtures return restricted user - } + // ensure fixtures return restricted user + require.True(t, restrictedUser.IsRestricted) testCases := []struct { name string diff --git a/models/user/openid_test.go b/models/user/openid_test.go index 27e6edd1e0..708af9e653 100644 --- a/models/user/openid_test.go +++ b/models/user/openid_test.go @@ -11,6 +11,7 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetUserOpenIDs(t *testing.T) { @@ -34,30 +35,23 @@ func TestGetUserOpenIDs(t *testing.T) { func TestToggleUserOpenIDVisibility(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) oids, err := user_model.GetUserOpenIDs(db.DefaultContext, int64(2)) - if !assert.NoError(t, err) || !assert.Len(t, oids, 1) { - return - } + require.NoError(t, err) + require.Len(t, oids, 1) assert.True(t, oids[0].Show) err = user_model.ToggleUserOpenIDVisibility(db.DefaultContext, oids[0].ID) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) oids, err = user_model.GetUserOpenIDs(db.DefaultContext, int64(2)) - if !assert.NoError(t, err) || !assert.Len(t, oids, 1) { - return - } + require.NoError(t, err) + require.Len(t, oids, 1) + assert.False(t, oids[0].Show) err = user_model.ToggleUserOpenIDVisibility(db.DefaultContext, oids[0].ID) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) oids, err = user_model.GetUserOpenIDs(db.DefaultContext, int64(2)) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) if assert.Len(t, oids, 1) { assert.True(t, oids[0].Show) } diff --git a/modules/analyze/vendor_test.go b/modules/analyze/vendor_test.go index aafd3c431b..02a51d4c8f 100644 --- a/modules/analyze/vendor_test.go +++ b/modules/analyze/vendor_test.go @@ -3,7 +3,11 @@ package analyze -import "testing" +import ( + "testing" + + "github.com/stretchr/testify/assert" +) func TestIsVendor(t *testing.T) { tests := []struct { @@ -33,9 +37,8 @@ func TestIsVendor(t *testing.T) { } for _, tt := range tests { t.Run(tt.path, func(t *testing.T) { - if got := IsVendor(tt.path); got != tt.want { - t.Errorf("IsVendor() = %v, want %v", got, tt.want) - } + got := IsVendor(tt.path) + assert.Equal(t, tt.want, got) }) } } diff --git a/modules/auth/openid/discovery_cache_test.go b/modules/auth/openid/discovery_cache_test.go index 5a7f450937..7d4b27c5df 100644 --- a/modules/auth/openid/discovery_cache_test.go +++ b/modules/auth/openid/discovery_cache_test.go @@ -6,6 +6,9 @@ package openid import ( "testing" "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type testDiscoveredInfo struct{} @@ -29,21 +32,17 @@ func TestTimedDiscoveryCache(t *testing.T) { dc.Put("foo", &testDiscoveredInfo{}) // openid.opEndpoint: "a", openid.opLocalID: "b", openid.claimedID: "c"}) // Make sure we can retrieve them - if di := dc.Get("foo"); di == nil { - t.Errorf("Expected a result, got nil") - } else if di.OpEndpoint() != "opEndpoint" || di.OpLocalID() != "opLocalID" || di.ClaimedID() != "claimedID" { - t.Errorf("Expected opEndpoint opLocalID claimedID, got %v %v %v", di.OpEndpoint(), di.OpLocalID(), di.ClaimedID()) - } + di := dc.Get("foo") + require.NotNil(t, di) + assert.Equal(t, "opEndpoint", di.OpEndpoint()) + assert.Equal(t, "opLocalID", di.OpLocalID()) + assert.Equal(t, "claimedID", di.ClaimedID()) // Attempt to get a non-existent value - if di := dc.Get("bar"); di != nil { - t.Errorf("Expected nil, got %v", di) - } + assert.Nil(t, dc.Get("bar")) // Sleep one second and try retrieve again time.Sleep(1 * time.Second) - if di := dc.Get("foo"); di != nil { - t.Errorf("Expected a nil, got a result") - } + assert.Nil(t, dc.Get("foo")) } diff --git a/modules/emoji/emoji_test.go b/modules/emoji/emoji_test.go index 2526cd121e..fbf80fe41a 100644 --- a/modules/emoji/emoji_test.go +++ b/modules/emoji/emoji_test.go @@ -5,7 +5,6 @@ package emoji import ( - "reflect" "testing" "github.com/stretchr/testify/assert" @@ -22,32 +21,18 @@ func TestLookup(t *testing.T) { c := FromAlias(":beer:") d := FromAlias("beer") - if !reflect.DeepEqual(a, b) { - t.Errorf("a and b should equal") - } - if !reflect.DeepEqual(b, c) { - t.Errorf("b and c should equal") - } - if !reflect.DeepEqual(c, d) { - t.Errorf("c and d should equal") - } - if !reflect.DeepEqual(a, d) { - t.Errorf("a and d should equal") - } + assert.Equal(t, a, b) + assert.Equal(t, b, c) + assert.Equal(t, c, d) + assert.Equal(t, a, d) m := FromCode("\U0001f44d") n := FromAlias(":thumbsup:") o := FromAlias("+1") - if !reflect.DeepEqual(m, n) { - t.Errorf("m and n should equal") - } - if !reflect.DeepEqual(n, o) { - t.Errorf("n and o should equal") - } - if !reflect.DeepEqual(m, o) { - t.Errorf("m and o should equal") - } + assert.Equal(t, m, n) + assert.Equal(t, m, o) + assert.Equal(t, n, o) } func TestReplacers(t *testing.T) { @@ -61,9 +46,7 @@ func TestReplacers(t *testing.T) { for i, x := range tests { s := x.f(x.v) - if s != x.exp { - t.Errorf("test %d `%s` expected `%s`, got: `%s`", i, x.v, x.exp, s) - } + assert.Equalf(t, x.exp, s, "test %d `%s` expected `%s`, got: `%s`", i, x.v, x.exp, s) } } diff --git a/modules/eventsource/event_test.go b/modules/eventsource/event_test.go index 4c4272880d..a1c3e5c7a8 100644 --- a/modules/eventsource/event_test.go +++ b/modules/eventsource/event_test.go @@ -6,6 +6,9 @@ package eventsource import ( "bytes" "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_wrapNewlines(t *testing.T) { @@ -38,16 +41,10 @@ func Test_wrapNewlines(t *testing.T) { t.Run(tt.name, func(t *testing.T) { w := &bytes.Buffer{} gotSum, err := wrapNewlines(w, []byte(tt.prefix), []byte(tt.value)) - if err != nil { - t.Errorf("wrapNewlines() error = %v", err) - return - } - if gotSum != int64(len(tt.output)) { - t.Errorf("wrapNewlines() = %v, want %v", gotSum, int64(len(tt.output))) - } - if gotW := w.String(); gotW != tt.output { - t.Errorf("wrapNewlines() = %v, want %v", gotW, tt.output) - } + require.NoError(t, err) + + assert.EqualValues(t, len(tt.output), gotSum) + assert.Equal(t, tt.output, w.String()) }) } } diff --git a/modules/git/blob_test.go b/modules/git/blob_test.go index 63374384f6..d0804350ed 100644 --- a/modules/git/blob_test.go +++ b/modules/git/blob_test.go @@ -17,9 +17,7 @@ func TestBlob_Data(t *testing.T) { output := "file2\n" bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") repo, err := openRepositoryWithDefaultContext(bareRepo1Path) - if !assert.NoError(t, err) { - t.Fatal() - } + require.NoError(t, err) defer repo.Close() testBlob, err := repo.GetBlob("6c493ff740f9380390d5c9ddef4af18697ac9375") diff --git a/modules/git/commit_sha256_test.go b/modules/git/commit_sha256_test.go index 2184a9c47c..f6ca83c9ed 100644 --- a/modules/git/commit_sha256_test.go +++ b/modules/git/commit_sha256_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCommitsCountSha256(t *testing.T) { @@ -94,9 +95,7 @@ signed commit` commitFromReader, err := CommitFromReader(gitRepo, sha, strings.NewReader(commitString)) assert.NoError(t, err) - if !assert.NotNil(t, commitFromReader) { - return - } + require.NotNil(t, commitFromReader) assert.EqualValues(t, sha, commitFromReader.ID) assert.EqualValues(t, `-----BEGIN PGP SIGNATURE----- diff --git a/modules/git/commit_test.go b/modules/git/commit_test.go index 6ac65564dc..9560c2cd94 100644 --- a/modules/git/commit_test.go +++ b/modules/git/commit_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCommitsCount(t *testing.T) { @@ -91,9 +92,7 @@ empty commit` commitFromReader, err := CommitFromReader(gitRepo, sha, strings.NewReader(commitString)) assert.NoError(t, err) - if !assert.NotNil(t, commitFromReader) { - return - } + require.NotNil(t, commitFromReader) assert.EqualValues(t, sha, commitFromReader.ID) assert.EqualValues(t, `-----BEGIN PGP SIGNATURE----- @@ -159,9 +158,7 @@ ISO-8859-1` commitFromReader, err := CommitFromReader(gitRepo, sha, strings.NewReader(commitString)) assert.NoError(t, err) - if !assert.NotNil(t, commitFromReader) { - return - } + require.NotNil(t, commitFromReader) assert.EqualValues(t, sha, commitFromReader.ID) assert.EqualValues(t, `-----BEGIN PGP SIGNATURE----- diff --git a/modules/git/repo_language_stats_test.go b/modules/git/repo_language_stats_test.go index da3871e909..1ee5f4c3af 100644 --- a/modules/git/repo_language_stats_test.go +++ b/modules/git/repo_language_stats_test.go @@ -10,20 +10,18 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRepository_GetLanguageStats(t *testing.T) { repoPath := filepath.Join(testReposDir, "language_stats_repo") gitRepo, err := openRepositoryWithDefaultContext(repoPath) - if !assert.NoError(t, err) { - t.Fatal() - } + require.NoError(t, err) + defer gitRepo.Close() stats, err := gitRepo.GetLanguageStats("8fee858da5796dfb37704761701bb8e800ad9ef3") - if !assert.NoError(t, err) { - t.Fatal() - } + require.NoError(t, err) assert.EqualValues(t, map[string]int64{ "Python": 134, diff --git a/modules/git/repo_tag_test.go b/modules/git/repo_tag_test.go index 0117cb902d..f1f081680a 100644 --- a/modules/git/repo_tag_test.go +++ b/modules/git/repo_tag_test.go @@ -182,7 +182,6 @@ func TestRepository_GetAnnotatedTag(t *testing.T) { // Annotated tag's name should fail tag3, err := bareRepo1.GetAnnotatedTag(aTagName) - assert.Error(t, err) assert.Errorf(t, err, "Length must be 40: %d", len(aTagName)) assert.Nil(t, tag3) diff --git a/modules/gitgraph/graph_test.go b/modules/gitgraph/graph_test.go index 18d427acd9..2f647aaf83 100644 --- a/modules/gitgraph/graph_test.go +++ b/modules/gitgraph/graph_test.go @@ -10,6 +10,8 @@ import ( "testing" "code.gitea.io/gitea/modules/git" + + "github.com/stretchr/testify/assert" ) func BenchmarkGetCommitGraph(b *testing.B) { @@ -235,9 +237,7 @@ func TestParseGlyphs(t *testing.T) { } row++ } - if len(parser.availableColors) != 9 { - t.Errorf("Expected 9 colors but have %d", len(parser.availableColors)) - } + assert.Len(t, parser.availableColors, 9) } func TestCommitStringParsing(t *testing.T) { @@ -262,9 +262,7 @@ func TestCommitStringParsing(t *testing.T) { return } - if test.commitMessage != commit.Subject { - t.Errorf("%s does not match %s", test.commitMessage, commit.Subject) - } + assert.Equal(t, test.commitMessage, commit.Subject) }) } } diff --git a/modules/httplib/serve_test.go b/modules/httplib/serve_test.go index c2229dffe9..e53f38b697 100644 --- a/modules/httplib/serve_test.go +++ b/modules/httplib/serve_test.go @@ -13,6 +13,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestServeContentByReader(t *testing.T) { @@ -71,9 +72,7 @@ func TestServeContentByReadSeeker(t *testing.T) { } seekReader, err := os.OpenFile(tmpFile, os.O_RDONLY, 0o644) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) defer seekReader.Close() w := httptest.NewRecorder() diff --git a/modules/indexer/issues/elasticsearch/elasticsearch_test.go b/modules/indexer/issues/elasticsearch/elasticsearch_test.go index ffd85b1aa1..dc329c07dd 100644 --- a/modules/indexer/issues/elasticsearch/elasticsearch_test.go +++ b/modules/indexer/issues/elasticsearch/elasticsearch_test.go @@ -11,6 +11,8 @@ import ( "time" "code.gitea.io/gitea/modules/indexer/issues/internal/tests" + + "github.com/stretchr/testify/require" ) func TestElasticsearchIndexer(t *testing.T) { @@ -26,20 +28,10 @@ func TestElasticsearchIndexer(t *testing.T) { } } - ok := false - for i := 0; i < 60; i++ { + require.Eventually(t, func() bool { resp, err := http.Get(url) - if err == nil && resp.StatusCode == http.StatusOK { - ok = true - break - } - t.Logf("Waiting for elasticsearch to be up: %v", err) - time.Sleep(time.Second) - } - if !ok { - t.Fatalf("Failed to wait for elasticsearch to be up") - return - } + return err == nil && resp.StatusCode == http.StatusOK + }, time.Minute, time.Second, "Expected elasticsearch to be up") indexer := NewIndexer(url, fmt.Sprintf("test_elasticsearch_indexer_%d", time.Now().Unix())) defer indexer.Close() diff --git a/modules/indexer/issues/indexer_test.go b/modules/indexer/issues/indexer_test.go index 06a6a46c23..8043d33eeb 100644 --- a/modules/indexer/issues/indexer_test.go +++ b/modules/indexer/issues/indexer_test.go @@ -19,6 +19,7 @@ import ( _ "code.gitea.io/gitea/models/activities" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { @@ -26,7 +27,7 @@ func TestMain(m *testing.M) { } func TestDBSearchIssues(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) setting.Indexer.IssueType = "db" InitIssueIndexer(true) @@ -83,9 +84,7 @@ func searchIssueWithKeyword(t *testing.T) { for _, test := range tests { issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, test.expectedIDs, issueIDs) } } @@ -120,9 +119,7 @@ func searchIssueByIndex(t *testing.T) { for _, test := range tests { issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, test.expectedIDs, issueIDs) } } @@ -166,9 +163,7 @@ func searchIssueInRepo(t *testing.T) { for _, test := range tests { issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, test.expectedIDs, issueIDs) } } @@ -238,9 +233,7 @@ func searchIssueByID(t *testing.T) { for _, test := range tests { issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, test.expectedIDs, issueIDs) } } @@ -265,9 +258,7 @@ func searchIssueIsPull(t *testing.T) { } for _, test := range tests { issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, test.expectedIDs, issueIDs) } } @@ -292,9 +283,7 @@ func searchIssueIsClosed(t *testing.T) { } for _, test := range tests { issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, test.expectedIDs, issueIDs) } } @@ -319,9 +308,7 @@ func searchIssueIsArchived(t *testing.T) { } for _, test := range tests { issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, test.expectedIDs, issueIDs) } } @@ -346,9 +333,7 @@ func searchIssueByMilestoneID(t *testing.T) { } for _, test := range tests { issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, test.expectedIDs, issueIDs) } } @@ -379,9 +364,7 @@ func searchIssueByLabelID(t *testing.T) { } for _, test := range tests { issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, test.expectedIDs, issueIDs) } } @@ -400,9 +383,7 @@ func searchIssueByTime(t *testing.T) { } for _, test := range tests { issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, test.expectedIDs, issueIDs) } } @@ -421,9 +402,7 @@ func searchIssueWithOrder(t *testing.T) { } for _, test := range tests { issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, test.expectedIDs, issueIDs) } } @@ -454,9 +433,7 @@ func searchIssueInProject(t *testing.T) { } for _, test := range tests { issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, test.expectedIDs, issueIDs) } } @@ -479,9 +456,7 @@ func searchIssueWithPaginator(t *testing.T) { } for _, test := range tests { issueIDs, total, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, test.expectedIDs, issueIDs) assert.Equal(t, test.expectedTotal, total) } diff --git a/modules/indexer/issues/meilisearch/meilisearch_test.go b/modules/indexer/issues/meilisearch/meilisearch_test.go index 4666df136a..a3a332554a 100644 --- a/modules/indexer/issues/meilisearch/meilisearch_test.go +++ b/modules/indexer/issues/meilisearch/meilisearch_test.go @@ -15,6 +15,7 @@ import ( "github.com/meilisearch/meilisearch-go" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMeilisearchIndexer(t *testing.T) { @@ -32,20 +33,10 @@ func TestMeilisearchIndexer(t *testing.T) { key = os.Getenv("TEST_MEILISEARCH_KEY") } - ok := false - for i := 0; i < 60; i++ { + require.Eventually(t, func() bool { resp, err := http.Get(url) - if err == nil && resp.StatusCode == http.StatusOK { - ok = true - break - } - t.Logf("Waiting for meilisearch to be up: %v", err) - time.Sleep(time.Second) - } - if !ok { - t.Fatalf("Failed to wait for meilisearch to be up") - return - } + return err == nil && resp.StatusCode == http.StatusOK + }, time.Minute, time.Second, "Expected meilisearch to be up") indexer := NewIndexer(url, key, fmt.Sprintf("test_meilisearch_indexer_%d", time.Now().Unix())) defer indexer.Close() diff --git a/modules/issue/template/template_test.go b/modules/issue/template/template_test.go index 689a285b47..575e23def9 100644 --- a/modules/issue/template/template_test.go +++ b/modules/issue/template/template_test.go @@ -957,9 +957,8 @@ func Test_minQuotes(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := minQuotes(tt.args.value); got != tt.want { - t.Errorf("minQuotes() = %v, want %v", got, tt.want) - } + got := minQuotes(tt.args.value) + assert.Equal(t, tt.want, got) }) } } diff --git a/modules/markup/markdown/renderconfig_test.go b/modules/markup/markdown/renderconfig_test.go index c53acdc77a..13346570fa 100644 --- a/modules/markup/markdown/renderconfig_test.go +++ b/modules/markup/markdown/renderconfig_test.go @@ -7,6 +7,8 @@ import ( "strings" "testing" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "gopkg.in/yaml.v3" ) @@ -140,23 +142,13 @@ func TestRenderConfig_UnmarshalYAML(t *testing.T) { Icon: "table", Lang: "", } - if err := yaml.Unmarshal([]byte(strings.ReplaceAll(tt.args, "\t", " ")), got); err != nil { - t.Errorf("RenderConfig.UnmarshalYAML() error = %v\n%q", err, tt.args) - return - } + err := yaml.Unmarshal([]byte(strings.ReplaceAll(tt.args, "\t", " ")), got) + require.NoError(t, err) - if got.Meta != tt.expected.Meta { - t.Errorf("Meta Expected %s Got %s", tt.expected.Meta, got.Meta) - } - if got.Icon != tt.expected.Icon { - t.Errorf("Icon Expected %s Got %s", tt.expected.Icon, got.Icon) - } - if got.Lang != tt.expected.Lang { - t.Errorf("Lang Expected %s Got %s", tt.expected.Lang, got.Lang) - } - if got.TOC != tt.expected.TOC { - t.Errorf("TOC Expected %q Got %q", tt.expected.TOC, got.TOC) - } + assert.Equal(t, tt.expected.Meta, got.Meta) + assert.Equal(t, tt.expected.Icon, got.Icon) + assert.Equal(t, tt.expected.Lang, got.Lang) + assert.Equal(t, tt.expected.TOC, got.TOC) }) } } diff --git a/modules/nosql/redis_test.go b/modules/nosql/redis_test.go index 43652e314c..93276ca793 100644 --- a/modules/nosql/redis_test.go +++ b/modules/nosql/redis_test.go @@ -5,6 +5,9 @@ package nosql import ( "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestToRedisURI(t *testing.T) { @@ -26,9 +29,9 @@ func TestToRedisURI(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := ToRedisURI(tt.connection); got == nil || got.String() != tt.want { - t.Errorf(`ToRedisURI(%q) = %s, want %s`, tt.connection, got.String(), tt.want) - } + got := ToRedisURI(tt.connection) + require.NotNil(t, got) + assert.Equal(t, tt.want, got.String()) }) } } diff --git a/modules/queue/base_levelqueue_test.go b/modules/queue/base_levelqueue_test.go index b881802ca2..05d8208560 100644 --- a/modules/queue/base_levelqueue_test.go +++ b/modules/queue/base_levelqueue_test.go @@ -11,6 +11,7 @@ import ( "gitea.com/lunny/levelqueue" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/syndtr/goleveldb/leveldb" ) @@ -29,9 +30,7 @@ func TestCorruptedLevelQueue(t *testing.T) { // sometimes the levelqueue could be in a corrupted state, this test is to make sure it can recover from it dbDir := t.TempDir() + "/levelqueue-test" db, err := leveldb.OpenFile(dbDir, nil) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) defer db.Close() assert.NoError(t, db.Put([]byte("other-key"), []byte("other-value"), nil)) diff --git a/modules/queue/base_redis_test.go b/modules/queue/base_redis_test.go index 19fbccbc8f..6478988d7f 100644 --- a/modules/queue/base_redis_test.go +++ b/modules/queue/base_redis_test.go @@ -14,6 +14,7 @@ import ( "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func waitRedisReady(conn string, dur time.Duration) (ready bool) { @@ -61,9 +62,7 @@ func TestBaseRedis(t *testing.T) { return } assert.NoError(t, redisServer.Start()) - if !assert.True(t, waitRedisReady("redis://127.0.0.1:6379/0", 5*time.Second), "start redis-server") { - return - } + require.True(t, waitRedisReady("redis://127.0.0.1:6379/0", 5*time.Second), "start redis-server") } testQueueBasic(t, newBaseRedisSimple, toBaseConfig("baseRedis", setting.QueueSettings{Length: 10}), false) diff --git a/modules/structs/commit_status_test.go b/modules/structs/commit_status_test.go index f06808534c..88e09aadc1 100644 --- a/modules/structs/commit_status_test.go +++ b/modules/structs/commit_status_test.go @@ -5,6 +5,8 @@ package structs import ( "testing" + + "github.com/stretchr/testify/assert" ) func TestNoBetterThan(t *testing.T) { @@ -166,9 +168,7 @@ func TestNoBetterThan(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := tt.args.css.NoBetterThan(tt.args.css2) - if result != tt.want { - t.Errorf("NoBetterThan() = %v, want %v", result, tt.want) - } + assert.Equal(t, tt.want, result) }) } } diff --git a/modules/user/user_test.go b/modules/user/user_test.go index 372a675d34..d6b3911ca6 100644 --- a/modules/user/user_test.go +++ b/modules/user/user_test.go @@ -8,6 +8,9 @@ import ( "runtime" "strings" "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func getWhoamiOutput() (string, error) { @@ -20,24 +23,19 @@ func getWhoamiOutput() (string, error) { func TestCurrentUsername(t *testing.T) { user := CurrentUsername() - if len(user) == 0 { - t.Errorf("expected non-empty user, got: %s", user) - } + require.NotEmpty(t, user) + // Windows whoami is weird, so just skip remaining tests if runtime.GOOS == "windows" { t.Skip("skipped test because of weird whoami on Windows") } whoami, err := getWhoamiOutput() - if err != nil { - t.Errorf("failed to run whoami to test current user: %f", err) - } + require.NoError(t, err) + user = CurrentUsername() - if user != whoami { - t.Errorf("expected %s as user, got: %s", whoami, user) - } + assert.Equal(t, whoami, user) + t.Setenv("USER", "spoofed") user = CurrentUsername() - if user != whoami { - t.Errorf("expected %s as user, got: %s", whoami, user) - } + assert.Equal(t, whoami, user) } diff --git a/modules/util/shellquote_test.go b/modules/util/shellquote_test.go index 969998c592..4ef5ce6980 100644 --- a/modules/util/shellquote_test.go +++ b/modules/util/shellquote_test.go @@ -3,7 +3,11 @@ package util -import "testing" +import ( + "testing" + + "github.com/stretchr/testify/assert" +) func TestShellEscape(t *testing.T) { tests := []struct { @@ -83,9 +87,7 @@ func TestShellEscape(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := ShellEscape(tt.toEscape); got != tt.want { - t.Errorf("ShellEscape(%q):\nGot: %s\nWanted: %s", tt.toEscape, got, tt.want) - } + assert.Equal(t, tt.want, ShellEscape(tt.toEscape)) }) } } diff --git a/modules/web/routing/funcinfo_test.go b/modules/web/routing/funcinfo_test.go index 2ab5960373..974af58931 100644 --- a/modules/web/routing/funcinfo_test.go +++ b/modules/web/routing/funcinfo_test.go @@ -6,6 +6,8 @@ package routing import ( "fmt" "testing" + + "github.com/stretchr/testify/assert" ) func Test_shortenFilename(t *testing.T) { @@ -37,9 +39,8 @@ func Test_shortenFilename(t *testing.T) { } for _, tt := range tests { t.Run(fmt.Sprintf("shortenFilename('%s')", tt.filename), func(t *testing.T) { - if gotShort := shortenFilename(tt.filename, tt.fallback); gotShort != tt.expected { - t.Errorf("shortenFilename('%s'), expect '%s', but get '%s'", tt.filename, tt.expected, gotShort) - } + gotShort := shortenFilename(tt.filename, tt.fallback) + assert.Equal(t, tt.expected, gotShort) }) } } @@ -72,9 +73,8 @@ func Test_trimAnonymousFunctionSuffix(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := trimAnonymousFunctionSuffix(tt.name); got != tt.want { - t.Errorf("trimAnonymousFunctionSuffix() = %v, want %v", got, tt.want) - } + got := trimAnonymousFunctionSuffix(tt.name) + assert.Equal(t, tt.want, got) }) } } diff --git a/routers/utils/utils_test.go b/routers/utils/utils_test.go index 6e7f3c33cd..cc7c888a75 100644 --- a/routers/utils/utils_test.go +++ b/routers/utils/utils_test.go @@ -5,6 +5,8 @@ package utils import ( "testing" + + "github.com/stretchr/testify/assert" ) func TestSanitizeFlashErrorString(t *testing.T) { @@ -32,9 +34,8 @@ func TestSanitizeFlashErrorString(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := SanitizeFlashErrorString(tt.arg); got != tt.want { - t.Errorf("SanitizeFlashErrorString() = '%v', want '%v'", got, tt.want) - } + got := SanitizeFlashErrorString(tt.arg) + assert.Equal(t, tt.want, got) }) } } diff --git a/routers/web/repo/pull_review_test.go b/routers/web/repo/pull_review_test.go index 8344ff4091..3d0997ab4d 100644 --- a/routers/web/repo/pull_review_test.go +++ b/routers/web/repo/pull_review_test.go @@ -17,6 +17,7 @@ import ( "code.gitea.io/gitea/services/pull" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRenderConversation(t *testing.T) { @@ -41,19 +42,16 @@ func TestRenderConversation(t *testing.T) { var preparedComment *issues_model.Comment run("prepare", func(t *testing.T, ctx *context.Context, resp *httptest.ResponseRecorder) { comment, err := pull.CreateCodeComment(ctx, pr.Issue.Poster, ctx.Repo.GitRepo, pr.Issue, 1, "content", "", false, 0, pr.HeadCommitID, nil) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + comment.Invalidated = true err = issues_model.UpdateCommentInvalidate(ctx, comment) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + preparedComment = comment }) - if !assert.NotNil(t, preparedComment) { - return - } + require.NotNil(t, preparedComment) + run("diff with outdated", func(t *testing.T, ctx *context.Context, resp *httptest.ResponseRecorder) { ctx.Data["ShowOutdatedComments"] = true renderConversation(ctx, preparedComment, "diff") diff --git a/routers/web/repo/wiki_test.go b/routers/web/repo/wiki_test.go index 958ff802d4..c31f29164b 100644 --- a/routers/web/repo/wiki_test.go +++ b/routers/web/repo/wiki_test.go @@ -20,6 +20,7 @@ import ( wiki_service "code.gitea.io/gitea/services/wiki" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -66,12 +67,9 @@ func assertWikiNotExists(t *testing.T, repo *repo_model.Repository, wikiName wik func assertPagesMetas(t *testing.T, expectedNames []string, metas any) { pageMetas, ok := metas.([]PageMeta) - if !assert.True(t, ok) { - return - } - if !assert.Len(t, pageMetas, len(expectedNames)) { - return - } + require.True(t, ok) + require.Len(t, pageMetas, len(expectedNames)) + for i, pageMeta := range pageMetas { assert.EqualValues(t, expectedNames[i], pageMeta.Name) } diff --git a/services/auth/auth_test.go b/services/auth/auth_test.go index 3adaa28664..f1e9e6753f 100644 --- a/services/auth/auth_test.go +++ b/services/auth/auth_test.go @@ -9,6 +9,8 @@ import ( "testing" "code.gitea.io/gitea/modules/setting" + + "github.com/stretchr/testify/assert" ) func Test_isGitRawOrLFSPath(t *testing.T) { @@ -108,26 +110,22 @@ func Test_isGitRawOrLFSPath(t *testing.T) { t.Run(tt.path, func(t *testing.T) { req, _ := http.NewRequest("POST", "http://localhost"+tt.path, nil) setting.LFS.StartServer = false - if got := isGitRawOrAttachOrLFSPath(req); got != tt.want { - t.Errorf("isGitOrLFSPath() = %v, want %v", got, tt.want) - } + assert.Equal(t, tt.want, isGitRawOrAttachOrLFSPath(req)) + setting.LFS.StartServer = true - if got := isGitRawOrAttachOrLFSPath(req); got != tt.want { - t.Errorf("isGitOrLFSPath() = %v, want %v", got, tt.want) - } + assert.Equal(t, tt.want, isGitRawOrAttachOrLFSPath(req)) }) } for _, tt := range lfsTests { t.Run(tt, func(t *testing.T) { req, _ := http.NewRequest("POST", tt, nil) setting.LFS.StartServer = false - if got := isGitRawOrAttachOrLFSPath(req); got != setting.LFS.StartServer { - t.Errorf("isGitOrLFSPath(%q) = %v, want %v, %v", tt, got, setting.LFS.StartServer, gitRawOrAttachPathRe.MatchString(tt)) - } + got := isGitRawOrAttachOrLFSPath(req) + assert.Equalf(t, setting.LFS.StartServer, got, "isGitOrLFSPath(%q) = %v, want %v, %v", tt, got, setting.LFS.StartServer, gitRawOrAttachPathRe.MatchString(tt)) + setting.LFS.StartServer = true - if got := isGitRawOrAttachOrLFSPath(req); got != setting.LFS.StartServer { - t.Errorf("isGitOrLFSPath(%q) = %v, want %v", tt, got, setting.LFS.StartServer) - } + got = isGitRawOrAttachOrLFSPath(req) + assert.Equalf(t, setting.LFS.StartServer, got, "isGitOrLFSPath(%q) = %v, want %v", tt, got, setting.LFS.StartServer) }) } setting.LFS.StartServer = origLFSStartServer diff --git a/services/doctor/dbconsistency_test.go b/services/doctor/dbconsistency_test.go index 4e4ac535b7..eb427dee73 100644 --- a/services/doctor/dbconsistency_test.go +++ b/services/doctor/dbconsistency_test.go @@ -14,6 +14,7 @@ import ( "code.gitea.io/gitea/modules/log" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestConsistencyCheck(t *testing.T) { @@ -21,9 +22,7 @@ func TestConsistencyCheck(t *testing.T) { idx := slices.IndexFunc(checks, func(check consistencyCheck) bool { return check.Name == "Orphaned OAuth2Application without existing User" }) - if !assert.NotEqual(t, -1, idx) { - return - } + require.NotEqual(t, -1, idx) _ = db.TruncateBeans(db.DefaultContext, &auth.OAuth2Application{}, &user.User{}) _ = db.TruncateBeans(db.DefaultContext, &auth.OAuth2Application{}, &auth.OAuth2Application{}) diff --git a/services/gitdiff/csv_test.go b/services/gitdiff/csv_test.go index c006a7c2bd..f91e0e9aa7 100644 --- a/services/gitdiff/csv_test.go +++ b/services/gitdiff/csv_test.go @@ -192,23 +192,18 @@ c,d,e`, for n, c := range cases { diff, err := ParsePatch(db.DefaultContext, setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(c.diff), "") - if err != nil { - t.Errorf("ParsePatch failed: %s", err) - } + assert.NoError(t, err) var baseReader *csv.Reader if len(c.base) > 0 { baseReader, err = csv_module.CreateReaderAndDetermineDelimiter(nil, strings.NewReader(c.base)) - if err != nil { - t.Errorf("CreateReaderAndDetermineDelimiter failed: %s", err) - } + assert.NoError(t, err) } + var headReader *csv.Reader if len(c.head) > 0 { headReader, err = csv_module.CreateReaderAndDetermineDelimiter(nil, strings.NewReader(c.head)) - if err != nil { - t.Errorf("CreateReaderAndDetermineDelimiter failed: %s", err) - } + assert.NoError(t, err) } result, err := CreateCsvDiff(diff.Files[0], baseReader, headReader) diff --git a/services/gitdiff/gitdiff_test.go b/services/gitdiff/gitdiff_test.go index 2351c5da87..1017d188dd 100644 --- a/services/gitdiff/gitdiff_test.go +++ b/services/gitdiff/gitdiff_test.go @@ -19,6 +19,7 @@ import ( dmp "github.com/sergi/go-diff/diffmatchpatch" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestDiffToHTML(t *testing.T) { @@ -628,9 +629,8 @@ func TestDiffLine_GetCommentSide(t *testing.T) { func TestGetDiffRangeWithWhitespaceBehavior(t *testing.T) { gitRepo, err := git.OpenRepository(git.DefaultContext, "./testdata/academic-module") - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + defer gitRepo.Close() for _, behavior := range []git.TrustedCmdArgs{{"-w"}, {"--ignore-space-at-eol"}, {"-b"}, nil} { diffs, err := GetDiff(db.DefaultContext, gitRepo, diff --git a/services/mailer/mail_test.go b/services/mailer/mail_test.go index 185b72f069..36cef486c9 100644 --- a/services/mailer/mail_test.go +++ b/services/mailer/mail_test.go @@ -390,9 +390,7 @@ func TestGenerateMessageIDForIssue(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := generateMessageIDForIssue(tt.args.issue, tt.args.comment, tt.args.actionType) - if !strings.HasPrefix(got, tt.prefix) { - t.Errorf("generateMessageIDForIssue() = %v, want %v", got, tt.prefix) - } + assert.True(t, strings.HasPrefix(got, tt.prefix), "%v, want %v", got, tt.prefix) }) } } diff --git a/services/migrations/gitea_downloader_test.go b/services/migrations/gitea_downloader_test.go index d04e12abdb..6f6ef99d96 100644 --- a/services/migrations/gitea_downloader_test.go +++ b/services/migrations/gitea_downloader_test.go @@ -14,6 +14,7 @@ import ( base "code.gitea.io/gitea/modules/migration" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGiteaDownloadRepo(t *testing.T) { @@ -29,12 +30,8 @@ func TestGiteaDownloadRepo(t *testing.T) { } downloader, err := NewGiteaDownloader(context.Background(), "https://gitea.com", "gitea/test_repo", "", "", giteaToken) - if downloader == nil { - t.Fatal("NewGiteaDownloader is nil") - } - if !assert.NoError(t, err) { - t.Fatal("NewGiteaDownloader error occur") - } + require.NoError(t, err, "NewGiteaDownloader error occur") + require.NotNil(t, downloader, "NewGiteaDownloader is nil") repo, err := downloader.GetRepoInfo() assert.NoError(t, err) diff --git a/services/wiki/wiki_test.go b/services/wiki/wiki_test.go index 0a18cffa25..e8b89f5e97 100644 --- a/services/wiki/wiki_test.go +++ b/services/wiki/wiki_test.go @@ -17,6 +17,7 @@ import ( _ "code.gitea.io/gitea/models/actions" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { @@ -166,9 +167,8 @@ func TestRepository_AddWikiPage(t *testing.T) { assert.NoError(t, AddWikiPage(git.DefaultContext, doer, repo, webPath, wikiContent, commitMsg)) // Now need to show that the page has been added: gitRepo, err := gitrepo.OpenWikiRepository(git.DefaultContext, repo) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + defer gitRepo.Close() masterTree, err := gitRepo.GetTree(repo.DefaultWikiBranch) assert.NoError(t, err) @@ -238,9 +238,8 @@ func TestRepository_DeleteWikiPage(t *testing.T) { // Now need to show that the page has been added: gitRepo, err := gitrepo.OpenWikiRepository(git.DefaultContext, repo) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + defer gitRepo.Close() masterTree, err := gitRepo.GetTree(repo.DefaultWikiBranch) assert.NoError(t, err) @@ -253,9 +252,8 @@ func TestPrepareWikiFileName(t *testing.T) { unittest.PrepareTestEnv(t) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) gitRepo, err := gitrepo.OpenWikiRepository(git.DefaultContext, repo) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + defer gitRepo.Close() tests := []struct { @@ -307,9 +305,8 @@ func TestPrepareWikiFileName_FirstPage(t *testing.T) { assert.NoError(t, err) gitRepo, err := git.OpenRepository(git.DefaultContext, tmpDir) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + defer gitRepo.Close() existence, newWikiPath, err := prepareGitPath(gitRepo, "master", "Home") diff --git a/tests/integration/api_pull_commits_test.go b/tests/integration/api_pull_commits_test.go index 5ffc8158f3..f43ad7d3be 100644 --- a/tests/integration/api_pull_commits_test.go +++ b/tests/integration/api_pull_commits_test.go @@ -15,6 +15,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIPullCommits(t *testing.T) { @@ -29,9 +30,7 @@ func TestAPIPullCommits(t *testing.T) { var commits []*api.Commit DecodeJSON(t, resp, &commits) - if !assert.Len(t, commits, 2) { - return - } + require.Len(t, commits, 2) assert.Equal(t, "985f0301dba5e7b34be866819cd15ad3d8f508ee", commits[0].SHA) assert.Equal(t, "5c050d3b6d2db231ab1f64e324f1b6b9a0b181c2", commits[1].SHA) diff --git a/tests/integration/api_pull_review_test.go b/tests/integration/api_pull_review_test.go index ba6b62d0d7..b85882a510 100644 --- a/tests/integration/api_pull_review_test.go +++ b/tests/integration/api_pull_review_test.go @@ -21,6 +21,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "xorm.io/builder" ) @@ -39,9 +40,8 @@ func TestAPIPullReview(t *testing.T) { var reviews []*api.PullReview DecodeJSON(t, resp, &reviews) - if !assert.Len(t, reviews, 8) { - return - } + require.Len(t, reviews, 8) + for _, r := range reviews { assert.EqualValues(t, pullIssue.HTMLURL(), r.HTMLPullURL) } diff --git a/tests/integration/git_general_test.go b/tests/integration/git_general_test.go index a47cb75196..5d915d8a51 100644 --- a/tests/integration/git_general_test.go +++ b/tests/integration/git_general_test.go @@ -32,6 +32,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -726,9 +727,8 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string } gitRepo, err := git.OpenRepository(git.DefaultContext, dstPath) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + defer gitRepo.Close() var ( @@ -736,9 +736,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string commit string ) repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, ctx.Username, ctx.Reponame) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) pullNum := unittest.GetCount(t, &issues_model.PullRequest{}) @@ -746,9 +744,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string t.Run("AddCommit", func(t *testing.T) { err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content"), 0o666) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) err = git.AddChanges(dstPath, true) assert.NoError(t, err) @@ -773,43 +769,37 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string t.Run("Push", func(t *testing.T) { err := git.NewCommand(git.DefaultContext, "push", "origin", "HEAD:refs/for/master", "-o").AddDynamicArguments("topic=" + headBranch).Run(&git.RunOpts{Dir: dstPath}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + unittest.AssertCount(t, &issues_model.PullRequest{}, pullNum+1) pr1 = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ HeadRepoID: repo.ID, Flow: issues_model.PullRequestFlowAGit, }) - if !assert.NotEmpty(t, pr1) { - return - } + require.NotEmpty(t, pr1) + prMsg, err := doAPIGetPullRequest(*ctx, ctx.Username, ctx.Reponame, pr1.Index)(t) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + assert.Equal(t, "user2/"+headBranch, pr1.HeadBranch) assert.False(t, prMsg.HasMerged) assert.Contains(t, "Testing commit 1", prMsg.Body) assert.Equal(t, commit, prMsg.Head.Sha) _, _, err = git.NewCommand(git.DefaultContext, "push", "origin").AddDynamicArguments("HEAD:refs/for/master/test/" + headBranch).RunStdString(&git.RunOpts{Dir: dstPath}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + unittest.AssertCount(t, &issues_model.PullRequest{}, pullNum+2) pr2 = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ HeadRepoID: repo.ID, Index: pr1.Index + 1, Flow: issues_model.PullRequestFlowAGit, }) - if !assert.NotEmpty(t, pr2) { - return - } + require.NotEmpty(t, pr2) + prMsg, err = doAPIGetPullRequest(*ctx, ctx.Username, ctx.Reponame, pr2.Index)(t) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + assert.Equal(t, "user2/test/"+headBranch, pr2.HeadBranch) assert.False(t, prMsg.HasMerged) }) @@ -820,9 +810,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string t.Run("AddCommit2", func(t *testing.T) { err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content \n ## test content 2"), 0o666) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) err = git.AddChanges(dstPath, true) assert.NoError(t, err) @@ -847,26 +835,22 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string t.Run("Push2", func(t *testing.T) { err := git.NewCommand(git.DefaultContext, "push", "origin", "HEAD:refs/for/master", "-o").AddDynamicArguments("topic=" + headBranch).Run(&git.RunOpts{Dir: dstPath}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + unittest.AssertCount(t, &issues_model.PullRequest{}, pullNum+2) prMsg, err := doAPIGetPullRequest(*ctx, ctx.Username, ctx.Reponame, pr1.Index)(t) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + assert.False(t, prMsg.HasMerged) assert.Equal(t, commit, prMsg.Head.Sha) _, _, err = git.NewCommand(git.DefaultContext, "push", "origin").AddDynamicArguments("HEAD:refs/for/master/test/" + headBranch).RunStdString(&git.RunOpts{Dir: dstPath}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + unittest.AssertCount(t, &issues_model.PullRequest{}, pullNum+2) prMsg, err = doAPIGetPullRequest(*ctx, ctx.Username, ctx.Reponame, pr2.Index)(t) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + assert.False(t, prMsg.HasMerged) assert.Equal(t, commit, prMsg.Head.Sha) }) diff --git a/tests/integration/gpg_git_test.go b/tests/integration/gpg_git_test.go index acfe70026e..31695fb2e1 100644 --- a/tests/integration/gpg_git_test.go +++ b/tests/integration/gpg_git_test.go @@ -22,6 +22,7 @@ import ( "github.com/ProtonMail/go-crypto/openpgp" "github.com/ProtonMail/go-crypto/openpgp/armor" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGPGGit(t *testing.T) { @@ -33,9 +34,7 @@ func TestGPGGit(t *testing.T) { // Need to create a root key rootKeyPair, err := importTestingKey() - if !assert.NoError(t, err, "importTestingKey") { - return - } + require.NoError(t, err, "importTestingKey") defer test.MockVariableValue(&setting.Repository.Signing.SigningKey, rootKeyPair.PrimaryKey.KeyIdShortString())() defer test.MockVariableValue(&setting.Repository.Signing.SigningName, "gitea")() diff --git a/tests/integration/nonascii_branches_test.go b/tests/integration/nonascii_branches_test.go index e5934a148d..ae348d8173 100644 --- a/tests/integration/nonascii_branches_test.go +++ b/tests/integration/nonascii_branches_test.go @@ -12,7 +12,7 @@ import ( "code.gitea.io/gitea/tests" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func setDefaultBranch(t *testing.T, session *TestSession, user, repo, branch string) { @@ -199,14 +199,10 @@ func TestNonAsciiBranches(t *testing.T) { t.Run(test.from, func(t *testing.T) { req := NewRequest(t, "GET", fmt.Sprintf("/%s/%s/src/%s", user, repo, test.from)) resp := session.MakeRequest(t, req, http.StatusSeeOther) - if resp.Code != http.StatusSeeOther { - return - } + require.Equal(t, http.StatusSeeOther, resp.Code) redirectLocation := resp.Header().Get("Location") - if !assert.Equal(t, fmt.Sprintf("/%s/%s/src/%s", user, repo, test.to), redirectLocation) { - return - } + require.Equal(t, fmt.Sprintf("/%s/%s/src/%s", user, repo, test.to), redirectLocation) req = NewRequest(t, "GET", redirectLocation) session.MakeRequest(t, req, test.status)