1
1
mirror of https://github.com/go-gitea/gitea synced 2025-01-25 09:04:29 +00:00

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
This commit is contained in:
TheFox0x7 2025-01-09 02:21:47 +01:00 committed by GitHub
parent fa9191b7b9
commit 2a02734f93
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
42 changed files with 218 additions and 348 deletions

View File

@ -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)

View File

@ -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)
}
}

View File

@ -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

View File

@ -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)
}

View File

@ -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)
})
}
}

View File

@ -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"))
}

View File

@ -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)
}
}

View File

@ -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())
})
}
}

View File

@ -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")

View File

@ -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-----

View File

@ -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-----

View File

@ -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,

View File

@ -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)

View File

@ -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)
})
}
}

View File

@ -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()

View File

@ -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()

View File

@ -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)
}

View File

@ -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()

View File

@ -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)
})
}
}

View File

@ -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)
})
}
}

View File

@ -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())
})
}
}

View File

@ -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))

View File

@ -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)

View File

@ -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)
})
}
}

View File

@ -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)
}

View File

@ -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))
})
}
}

View File

@ -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)
})
}
}

View File

@ -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)
})
}
}

View File

@ -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")

View File

@ -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)
}

View File

@ -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

View File

@ -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{})

View File

@ -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)

View File

@ -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,

View File

@ -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)
})
}
}

View File

@ -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)

View File

@ -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")

View File

@ -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)

View File

@ -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)
}

View File

@ -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)
})

View File

@ -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")()

View File

@ -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)