Add testifylint to lint checks (#4535)

go-require lint is ignored for now

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/4535
Reviewed-by: Gusted <gusted@noreply.codeberg.org>
Co-authored-by: TheFox0x7 <thefox0x7@gmail.com>
Co-committed-by: TheFox0x7 <thefox0x7@gmail.com>
This commit is contained in:
TheFox0x7 2024-07-30 19:41:10 +00:00 committed by Earl Warren
parent 94933470cd
commit 4de909747b
504 changed files with 5028 additions and 4680 deletions

View file

@ -7,10 +7,12 @@ import (
"reflect"
"strconv"
"strings"
"testing"
"code.gitea.io/gitea/models/db"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"xorm.io/builder"
)
@ -21,10 +23,10 @@ const (
modelsCommentTypeComment = 0
)
var consistencyCheckMap = make(map[string]func(t assert.TestingT, bean any))
var consistencyCheckMap = make(map[string]func(t *testing.T, bean any))
// CheckConsistencyFor test that all matching database entries are consistent
func CheckConsistencyFor(t assert.TestingT, beansToCheck ...any) {
func CheckConsistencyFor(t *testing.T, beansToCheck ...any) {
for _, bean := range beansToCheck {
sliceType := reflect.SliceOf(reflect.TypeOf(bean))
sliceValue := reflect.MakeSlice(sliceType, 0, 10)
@ -32,7 +34,7 @@ func CheckConsistencyFor(t assert.TestingT, beansToCheck ...any) {
ptrToSliceValue := reflect.New(sliceType)
ptrToSliceValue.Elem().Set(sliceValue)
assert.NoError(t, db.GetEngine(db.DefaultContext).Table(bean).Find(ptrToSliceValue.Interface()))
require.NoError(t, db.GetEngine(db.DefaultContext).Table(bean).Find(ptrToSliceValue.Interface()))
sliceValue = ptrToSliceValue.Elem()
for i := 0; i < sliceValue.Len(); i++ {
@ -42,9 +44,9 @@ func CheckConsistencyFor(t assert.TestingT, beansToCheck ...any) {
}
}
func checkForConsistency(t assert.TestingT, bean any) {
func checkForConsistency(t *testing.T, bean any) {
tb, err := db.TableInfo(bean)
assert.NoError(t, err)
require.NoError(t, err)
f := consistencyCheckMap[tb.Name]
if f == nil {
assert.FailNow(t, "unknown bean type: %#v", bean)
@ -62,7 +64,7 @@ func init() {
return i
}
checkForUserConsistency := func(t assert.TestingT, bean any) {
checkForUserConsistency := func(t *testing.T, bean any) {
user := reflectionWrap(bean)
AssertCountByCond(t, "repository", builder.Eq{"owner_id": user.int("ID")}, user.int("NumRepos"))
AssertCountByCond(t, "star", builder.Eq{"uid": user.int("ID")}, user.int("NumStars"))
@ -76,7 +78,7 @@ func init() {
}
}
checkForRepoConsistency := func(t assert.TestingT, bean any) {
checkForRepoConsistency := func(t *testing.T, bean any) {
repo := reflectionWrap(bean)
assert.Equal(t, repo.str("LowerName"), strings.ToLower(repo.str("Name")), "repo: %+v", repo)
AssertCountByCond(t, "star", builder.Eq{"repo_id": repo.int("ID")}, repo.int("NumStars"))
@ -112,7 +114,7 @@ func init() {
"Unexpected number of closed milestones for repo id: %d", repo.int("ID"))
}
checkForIssueConsistency := func(t assert.TestingT, bean any) {
checkForIssueConsistency := func(t *testing.T, bean any) {
issue := reflectionWrap(bean)
typeComment := modelsCommentTypeComment
actual := GetCountByCond(t, "comment", builder.Eq{"`type`": typeComment, "issue_id": issue.int("ID")})
@ -123,14 +125,14 @@ func init() {
}
}
checkForPullRequestConsistency := func(t assert.TestingT, bean any) {
checkForPullRequestConsistency := func(t *testing.T, bean any) {
pr := reflectionWrap(bean)
issueRow := AssertExistsAndLoadMap(t, "issue", builder.Eq{"id": pr.int("IssueID")})
assert.True(t, parseBool(issueRow["is_pull"]))
assert.EqualValues(t, parseInt(issueRow["index"]), pr.int("Index"), "Unexpected index for pull request id: %d", pr.int("ID"))
}
checkForMilestoneConsistency := func(t assert.TestingT, bean any) {
checkForMilestoneConsistency := func(t *testing.T, bean any) {
milestone := reflectionWrap(bean)
AssertCountByCond(t, "issue", builder.Eq{"milestone_id": milestone.int("ID")}, milestone.int("NumIssues"))
@ -144,12 +146,12 @@ func init() {
assert.Equal(t, completeness, milestone.int("Completeness"))
}
checkForLabelConsistency := func(t assert.TestingT, bean any) {
checkForLabelConsistency := func(t *testing.T, bean any) {
label := reflectionWrap(bean)
issueLabels, err := db.GetEngine(db.DefaultContext).Table("issue_label").
Where(builder.Eq{"label_id": label.int("ID")}).
Query()
assert.NoError(t, err)
require.NoError(t, err)
assert.Len(t, issueLabels, label.int("NumIssues"), "Unexpected number of issue for label id: %d", label.int("ID"))
@ -165,13 +167,13 @@ func init() {
assert.EqualValues(t, expected, label.int("NumClosedIssues"), "Unexpected number of closed issues for label id: %d", label.int("ID"))
}
checkForTeamConsistency := func(t assert.TestingT, bean any) {
checkForTeamConsistency := func(t *testing.T, bean any) {
team := reflectionWrap(bean)
AssertCountByCond(t, "team_user", builder.Eq{"team_id": team.int("ID")}, team.int("NumMembers"))
AssertCountByCond(t, "team_repo", builder.Eq{"team_id": team.int("ID")}, team.int("NumRepos"))
}
checkForActionConsistency := func(t assert.TestingT, bean any) {
checkForActionConsistency := func(t *testing.T, bean any) {
action := reflectionWrap(bean)
if action.int("RepoID") != 1700 { // dangling intentional
repoRow := AssertExistsAndLoadMap(t, "repository", builder.Eq{"id": action.int("RepoID")})

View file

@ -18,6 +18,7 @@ import (
"code.gitea.io/gitea/modules/log"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Mocks HTTP responses of a third-party service (such as GitHub, GitLab…)
@ -39,7 +40,7 @@ func NewMockWebServer(t *testing.T, liveServerBaseURL, testDataDir string, liveM
liveURL := fmt.Sprintf("%s%s", liveServerBaseURL, path)
request, err := http.NewRequest(r.Method, liveURL, nil)
assert.NoError(t, err, "constructing an HTTP request to %s failed", liveURL)
require.NoError(t, err, "constructing an HTTP request to %s failed", liveURL)
for headerName, headerValues := range r.Header {
// do not pass on the encoding: let the Transport of the HTTP client handle that for us
if strings.ToLower(headerName) != "accept-encoding" {
@ -50,11 +51,11 @@ func NewMockWebServer(t *testing.T, liveServerBaseURL, testDataDir string, liveM
}
response, err := http.DefaultClient.Do(request)
assert.NoError(t, err, "HTTP request to %s failed: %s", liveURL)
require.NoError(t, err, "HTTP request to %s failed: %s", liveURL)
assert.Less(t, response.StatusCode, 400, "unexpected status code for %s", liveURL)
fixture, err := os.Create(fixturePath)
assert.NoError(t, err, "failed to open the fixture file %s for writing", fixturePath)
require.NoError(t, err, "failed to open the fixture file %s for writing", fixturePath)
defer fixture.Close()
fixtureWriter := bufio.NewWriter(fixture)
@ -62,24 +63,24 @@ func NewMockWebServer(t *testing.T, liveServerBaseURL, testDataDir string, liveM
for _, headerValue := range headerValues {
if !slices.Contains(ignoredHeaders, strings.ToLower(headerName)) {
_, err := fixtureWriter.WriteString(fmt.Sprintf("%s: %s\n", headerName, headerValue))
assert.NoError(t, err, "writing the header of the HTTP response to the fixture file failed")
require.NoError(t, err, "writing the header of the HTTP response to the fixture file failed")
}
}
}
_, err = fixtureWriter.WriteString("\n")
assert.NoError(t, err, "writing the header of the HTTP response to the fixture file failed")
require.NoError(t, err, "writing the header of the HTTP response to the fixture file failed")
fixtureWriter.Flush()
log.Info("Mock HTTP Server: writing response to %s", fixturePath)
_, err = io.Copy(fixture, response.Body)
assert.NoError(t, err, "writing the body of the HTTP response to %s failed", liveURL)
require.NoError(t, err, "writing the body of the HTTP response to %s failed", liveURL)
err = fixture.Sync()
assert.NoError(t, err, "writing the body of the HTTP response to the fixture file failed")
require.NoError(t, err, "writing the body of the HTTP response to the fixture file failed")
}
fixture, err := os.ReadFile(fixturePath)
assert.NoError(t, err, "missing mock HTTP response: "+fixturePath)
require.NoError(t, err, "missing mock HTTP response: "+fixturePath)
w.WriteHeader(http.StatusOK)
@ -95,7 +96,7 @@ func NewMockWebServer(t *testing.T, liveServerBaseURL, testDataDir string, liveM
// we reached the end of the headers (empty line), so what follows is the body
responseBody := strings.Join(lines[idx+1:], "\n")
_, err := w.Write([]byte(responseBody))
assert.NoError(t, err, "writing the body of the HTTP response failed")
require.NoError(t, err, "writing the body of the HTTP response failed")
break
}
}

View file

@ -22,7 +22,7 @@ import (
"code.gitea.io/gitea/modules/storage"
"code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"xorm.io/xorm"
"xorm.io/xorm/names"
)
@ -243,18 +243,18 @@ func PrepareTestDatabase() error {
// PrepareTestEnv prepares the environment for unit tests. Can only be called
// by tests that use the above MainTest(..) function.
func PrepareTestEnv(t testing.TB) {
assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, util.RemoveAll(setting.RepoRootPath))
require.NoError(t, PrepareTestDatabase())
require.NoError(t, util.RemoveAll(setting.RepoRootPath))
metaPath := filepath.Join(giteaRoot, "tests", "gitea-repositories-meta")
assert.NoError(t, CopyDir(metaPath, setting.RepoRootPath))
require.NoError(t, CopyDir(metaPath, setting.RepoRootPath))
ownerDirs, err := os.ReadDir(setting.RepoRootPath)
assert.NoError(t, err)
require.NoError(t, err)
for _, ownerDir := range ownerDirs {
if !ownerDir.Type().IsDir() {
continue
}
repoDirs, err := os.ReadDir(filepath.Join(setting.RepoRootPath, ownerDir.Name()))
assert.NoError(t, err)
require.NoError(t, err)
for _, repoDir := range repoDirs {
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755)
_ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755)

View file

@ -5,6 +5,7 @@ package unittest
import (
"math"
"testing"
"code.gitea.io/gitea/models/db"
@ -58,16 +59,16 @@ func LoadBeanIfExists(bean any, conditions ...any) (bool, error) {
}
// BeanExists for testing, check if a bean exists
func BeanExists(t assert.TestingT, bean any, conditions ...any) bool {
func BeanExists(t testing.TB, bean any, conditions ...any) bool {
exists, err := LoadBeanIfExists(bean, conditions...)
assert.NoError(t, err)
require.NoError(t, err)
return exists
}
// AssertExistsAndLoadBean assert that a bean exists and load it from the test database
func AssertExistsAndLoadBean[T any](t assert.TestingT, bean T, conditions ...any) T {
func AssertExistsAndLoadBean[T any](t testing.TB, bean T, conditions ...any) T {
exists, err := LoadBeanIfExists(bean, conditions...)
assert.NoError(t, err)
require.NoError(t, err)
assert.True(t, exists,
"Expected to find %+v (of type %T, with conditions %+v), but did not",
bean, bean, conditions)
@ -75,11 +76,11 @@ func AssertExistsAndLoadBean[T any](t assert.TestingT, bean T, conditions ...any
}
// AssertExistsAndLoadMap assert that a row exists and load it from the test database
func AssertExistsAndLoadMap(t assert.TestingT, table string, conditions ...any) map[string]string {
func AssertExistsAndLoadMap(t testing.TB, table string, conditions ...any) map[string]string {
e := db.GetEngine(db.DefaultContext).Table(table)
res, err := whereOrderConditions(e, conditions).Query()
assert.NoError(t, err)
assert.True(t, len(res) == 1,
require.NoError(t, err)
assert.Len(t, res, 1,
"Expected to find one row in %s (with conditions %+v), but found %d",
table, conditions, len(res),
)
@ -95,7 +96,7 @@ func AssertExistsAndLoadMap(t assert.TestingT, table string, conditions ...any)
}
// GetCount get the count of a bean
func GetCount(t assert.TestingT, bean any, conditions ...any) int {
func GetCount(t testing.TB, bean any, conditions ...any) int {
e := db.GetEngine(db.DefaultContext)
for _, condition := range conditions {
switch cond := condition.(type) {
@ -106,29 +107,29 @@ func GetCount(t assert.TestingT, bean any, conditions ...any) int {
}
}
count, err := e.Count(bean)
assert.NoError(t, err)
require.NoError(t, err)
return int(count)
}
// AssertNotExistsBean assert that a bean does not exist in the test database
func AssertNotExistsBean(t assert.TestingT, bean any, conditions ...any) {
func AssertNotExistsBean(t testing.TB, bean any, conditions ...any) {
exists, err := LoadBeanIfExists(bean, conditions...)
assert.NoError(t, err)
require.NoError(t, err)
assert.False(t, exists)
}
// AssertExistsIf asserts that a bean exists or does not exist, depending on
// what is expected.
func AssertExistsIf(t assert.TestingT, expected bool, bean any, conditions ...any) {
func AssertExistsIf(t testing.TB, expected bool, bean any, conditions ...any) {
exists, err := LoadBeanIfExists(bean, conditions...)
assert.NoError(t, err)
require.NoError(t, err)
assert.Equal(t, expected, exists)
}
// AssertSuccessfulInsert assert that beans is successfully inserted
func AssertSuccessfulInsert(t assert.TestingT, beans ...any) {
func AssertSuccessfulInsert(t testing.TB, beans ...any) {
err := db.Insert(db.DefaultContext, beans...)
assert.NoError(t, err)
require.NoError(t, err)
}
// AssertSuccessfulDelete assert that beans is successfully deleted
@ -138,26 +139,26 @@ func AssertSuccessfulDelete(t require.TestingT, beans ...any) {
}
// AssertCount assert the count of a bean
func AssertCount(t assert.TestingT, bean, expected any) bool {
func AssertCount(t testing.TB, bean, expected any) bool {
return assert.EqualValues(t, expected, GetCount(t, bean))
}
// AssertInt64InRange assert value is in range [low, high]
func AssertInt64InRange(t assert.TestingT, low, high, value int64) {
func AssertInt64InRange(t testing.TB, low, high, value int64) {
assert.True(t, value >= low && value <= high,
"Expected value in range [%d, %d], found %d", low, high, value)
}
// GetCountByCond get the count of database entries matching bean
func GetCountByCond(t assert.TestingT, tableName string, cond builder.Cond) int64 {
func GetCountByCond(t testing.TB, tableName string, cond builder.Cond) int64 {
e := db.GetEngine(db.DefaultContext)
count, err := e.Table(tableName).Where(cond).Count()
assert.NoError(t, err)
require.NoError(t, err)
return count
}
// AssertCountByCond test the count of database entries matching bean
func AssertCountByCond(t assert.TestingT, tableName string, cond builder.Cond, expected int) bool {
func AssertCountByCond(t testing.TB, tableName string, cond builder.Cond, expected int) bool {
return assert.EqualValues(t, expected, GetCountByCond(t, tableName, cond),
"Failed consistency test, the counted bean (of table %s) was %+v", tableName, cond)
}