Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
wxiaoguang committed Nov 15, 2024
1 parent 68731c0 commit 08559e3
Show file tree
Hide file tree
Showing 7 changed files with 67 additions and 70 deletions.
3 changes: 1 addition & 2 deletions models/migrations/base/tests.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import (
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/testlogger"

Expand Down Expand Up @@ -91,7 +90,7 @@ func PrepareTestEnv(t *testing.T, skip int, syncModels ...any) (*xorm.Engine, fu
}

func MainTest(m *testing.M) {
log.RegisterEventWriter("test", testlogger.NewTestLoggerWriter)
testlogger.Init()

giteaRoot := base.SetupGiteaRoot()
if giteaRoot == "" {
Expand Down
6 changes: 6 additions & 0 deletions modules/log/color.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,19 @@ type ColoredValue struct {
colors []ColorAttribute
}

var _ fmt.Formatter = (*ColoredValue)(nil)

func (c *ColoredValue) Format(f fmt.State, verb rune) {
_, _ = f.Write(ColorBytes(c.colors...))
s := fmt.Sprintf(fmt.FormatString(f, verb), c.v)
_, _ = f.Write([]byte(s))
_, _ = f.Write(resetBytes)
}

func (c *ColoredValue) Value() any {
return c.v
}

func NewColoredValue(v any, color ...ColorAttribute) *ColoredValue {
return &ColoredValue{v: v, colors: color}
}
Expand Down
57 changes: 24 additions & 33 deletions modules/testlogger/testlogger.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,79 +89,70 @@ func (w *testLoggerWriterCloser) Reset() {
w.Unlock()
}

// Printf takes a format and args and prints the string to os.Stdout
func Printf(format string, args ...any) {
if !log.CanColorStdout {
for i := 0; i < len(args); i++ {
if c, ok := args[i].(*log.ColoredValue); ok {
args[i] = c.Value()
}
}
}
_, _ = fmt.Fprintf(os.Stdout, "\t"+format, args...)
}

// PrintCurrentTest prints the current test to os.Stdout
func PrintCurrentTest(t testing.TB, skip ...int) func() {
t.Helper()
start := time.Now()
actualSkip := util.OptionalArg(skip) + 1
_, filename, line, _ := runtime.Caller(actualSkip)

if log.CanColorStdout {
_, _ = fmt.Fprintf(os.Stdout, "=== %s (%s:%d)\n", fmt.Formatter(log.NewColoredValue(t.Name())), strings.TrimPrefix(filename, prefix), line)
} else {
_, _ = fmt.Fprintf(os.Stdout, "=== %s (%s:%d)\n", t.Name(), strings.TrimPrefix(filename, prefix), line)
}
Printf("=== %s (%s:%d)\n", log.NewColoredValue(t.Name()), strings.TrimPrefix(filename, prefix), line)

WriterCloser.pushT(t)
return func() {
took := time.Since(start)
if took > SlowTest {
if log.CanColorStdout {
_, _ = fmt.Fprintf(os.Stdout, "+++ %s is a slow test (took %v)\n", fmt.Formatter(log.NewColoredValue(t.Name(), log.Bold, log.FgYellow)), fmt.Formatter(log.NewColoredValue(took, log.Bold, log.FgYellow)))
} else {
_, _ = fmt.Fprintf(os.Stdout, "+++ %s is a slow test (took %v)\n", t.Name(), took)
}
Printf("+++ %s is a slow test (took %v)\n", log.NewColoredValue(t.Name(), log.Bold, log.FgYellow), log.NewColoredValue(took, log.Bold, log.FgYellow))
}

timer := time.AfterFunc(SlowFlush, func() {
if log.CanColorStdout {
_, _ = fmt.Fprintf(os.Stdout, "+++ %s ... still flushing after %v ...\n", fmt.Formatter(log.NewColoredValue(t.Name(), log.Bold, log.FgRed)), SlowFlush)
} else {
_, _ = fmt.Fprintf(os.Stdout, "+++ %s ... still flushing after %v ...\n", t.Name(), SlowFlush)
}
Printf("+++ %s ... still flushing after %v ...\n", log.NewColoredValue(t.Name(), log.Bold, log.FgRed), SlowFlush)
})
if err := queue.GetManager().FlushAll(context.Background(), -1); err != nil {
t.Errorf("Flushing queues failed with error %v", err)
}
timer.Stop()
flushTook := time.Since(start) - took
if flushTook > SlowFlush {
if log.CanColorStdout {
_, _ = fmt.Fprintf(os.Stdout, "+++ %s had a slow clean-up flush (took %v)\n", fmt.Formatter(log.NewColoredValue(t.Name(), log.Bold, log.FgRed)), fmt.Formatter(log.NewColoredValue(flushTook, log.Bold, log.FgRed)))
} else {
_, _ = fmt.Fprintf(os.Stdout, "+++ %s had a slow clean-up flush (took %v)\n", t.Name(), flushTook)
}
Printf("+++ %s had a slow clean-up flush (took %v)\n", log.NewColoredValue(t.Name(), log.Bold, log.FgRed), log.NewColoredValue(flushTook, log.Bold, log.FgRed))
}
WriterCloser.popT()
}
}

// Printf takes a format and args and prints the string to os.Stdout
func Printf(format string, args ...any) {
if log.CanColorStdout {
for i := 0; i < len(args); i++ {
args[i] = log.NewColoredValue(args[i])
}
WriterCloser.popT()
}
_, _ = fmt.Fprintf(os.Stdout, "\t"+format, args...)
}

// TestLogEventWriter is a logger which will write to the testing log
type TestLogEventWriter struct {
*log.EventWriterBaseImpl
}

// NewTestLoggerWriter creates a TestLogEventWriter as a log.LoggerProvider
func NewTestLoggerWriter(name string, mode log.WriterMode) log.EventWriter {
// newTestLoggerWriter creates a TestLogEventWriter as a log.LoggerProvider
func newTestLoggerWriter(name string, mode log.WriterMode) log.EventWriter {
w := &TestLogEventWriter{}
w.EventWriterBaseImpl = log.NewEventWriterBase(name, "test-log-writer", mode)
w.OutputWriteCloser = WriterCloser
return w
}

func init() {
func Init() {
const relFilePath = "modules/testlogger/testlogger.go"
_, filename, _, _ := runtime.Caller(0)
if !strings.HasSuffix(filename, relFilePath) {
panic("source code file path doesn't match expected: " + relFilePath)
}
prefix = strings.TrimSuffix(filename, relFilePath)

log.RegisterEventWriter("test", newTestLoggerWriter)
}
2 changes: 0 additions & 2 deletions tests/integration/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,6 @@ func TestMain(m *testing.M) {
// Instead, "No tests were found", last nonsense log is "According to the configuration, subsequent logs will not be printed to the console"
exitCode := m.Run()

testlogger.WriterCloser.Reset()

if err = util.RemoveAll(setting.Indexer.IssuePath); err != nil {
fmt.Printf("util.RemoveAll: %v\n", err)
os.Exit(1)
Expand Down
65 changes: 34 additions & 31 deletions tests/integration/linguist_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package integration
import (
"context"
"net/url"
"strconv"
"strings"
"testing"
"time"
Expand All @@ -19,6 +20,7 @@ import (
"code.gitea.io/gitea/modules/queue"
repo_service "code.gitea.io/gitea/services/repository"
files_service "code.gitea.io/gitea/services/repository/files"
"code.gitea.io/gitea/tests"

"github.com/stretchr/testify/assert"
)
Expand Down Expand Up @@ -218,42 +220,43 @@ func TestLinguist(t *testing.T) {
}

for i, c := range cases {
repo, err := repo_service.CreateRepository(db.DefaultContext, user, user, repo_service.CreateRepoOptions{
Name: "linguist-test",
})
assert.NoError(t, err)

files := []*files_service.ChangeRepoFile{
{
TreePath: ".gitattributes",
ContentReader: strings.NewReader(c.GitAttributesContent),
},
}
files = append(files, c.FilesToAdd...)
for _, f := range files {
f.Operation = "create"
}
t.Run("Case-"+strconv.Itoa(i), func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
repo, err := repo_service.CreateRepository(db.DefaultContext, user, user, repo_service.CreateRepoOptions{
Name: "linguist-test-" + strconv.Itoa(i),
})
assert.NoError(t, err)

_, err = files_service.ChangeRepoFiles(git.DefaultContext, repo, user, &files_service.ChangeRepoFilesOptions{
Files: files,
OldBranch: repo.DefaultBranch,
NewBranch: repo.DefaultBranch,
})
assert.NoError(t, err)
files := []*files_service.ChangeRepoFile{
{
TreePath: ".gitattributes",
ContentReader: strings.NewReader(c.GitAttributesContent),
},
}
files = append(files, c.FilesToAdd...)
for _, f := range files {
f.Operation = "create"
}

assert.NoError(t, stats.UpdateRepoIndexer(repo))
assert.NoError(t, queue.GetManager().FlushAll(context.Background(), 10*time.Second))
_, err = files_service.ChangeRepoFiles(git.DefaultContext, repo, user, &files_service.ChangeRepoFilesOptions{
Files: files,
OldBranch: repo.DefaultBranch,
NewBranch: repo.DefaultBranch,
})
assert.NoError(t, err)

stats, err := repo_model.GetTopLanguageStats(db.DefaultContext, repo, len(c.FilesToAdd))
assert.NoError(t, err)
assert.NoError(t, stats.UpdateRepoIndexer(repo))
assert.NoError(t, queue.GetManager().FlushAll(context.Background(), 10*time.Second))

languages := make([]string, 0, len(stats))
for _, s := range stats {
languages = append(languages, s.Language)
}
assert.Equal(t, c.ExpectedLanguageOrder, languages, "case %d: unexpected language stats", i)
stats, err := repo_model.GetTopLanguageStats(db.DefaultContext, repo, len(c.FilesToAdd))
assert.NoError(t, err)

assert.NoError(t, repo_service.DeleteRepository(db.DefaultContext, user, repo, false))
languages := make([]string, 0, len(stats))
for _, s := range stats {
languages = append(languages, s.Language)
}
assert.Equal(t, c.ExpectedLanguageOrder, languages, "case %d: unexpected language stats", i)
})
}
})
}
2 changes: 1 addition & 1 deletion tests/integration/migration-test/migration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import (
var currentEngine *xorm.Engine

func initMigrationTest(t *testing.T) func() {
log.RegisterEventWriter("test", testlogger.NewTestLoggerWriter)
testlogger.Init()

deferFn := tests.PrintCurrentTest(t, 2)
giteaRoot := base.SetupGiteaRoot()
Expand Down
2 changes: 1 addition & 1 deletion tests/test_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func exitf(format string, args ...any) {
}

func InitTest(requireGitea bool) {
log.RegisterEventWriter("test", testlogger.NewTestLoggerWriter)
testlogger.Init()

giteaRoot := base.SetupGiteaRoot()
if giteaRoot == "" {
Expand Down

0 comments on commit 08559e3

Please sign in to comment.