Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package testlogger
  4. import (
  5. "context"
  6. "fmt"
  7. "os"
  8. "runtime"
  9. "strings"
  10. "sync"
  11. "testing"
  12. "time"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/queue"
  15. )
  16. var (
  17. prefix string
  18. SlowTest = 10 * time.Second
  19. SlowFlush = 5 * time.Second
  20. )
  21. var WriterCloser = &testLoggerWriterCloser{}
  22. type testLoggerWriterCloser struct {
  23. sync.RWMutex
  24. t []testing.TB
  25. }
  26. func (w *testLoggerWriterCloser) pushT(t testing.TB) {
  27. w.Lock()
  28. w.t = append(w.t, t)
  29. w.Unlock()
  30. }
  31. func (w *testLoggerWriterCloser) Write(p []byte) (int, error) {
  32. // There was a data race problem: the logger system could still try to output logs after the runner is finished.
  33. // So we must ensure that the "t" in stack is still valid.
  34. w.RLock()
  35. defer w.RUnlock()
  36. var t testing.TB
  37. if len(w.t) > 0 {
  38. t = w.t[len(w.t)-1]
  39. }
  40. if len(p) > 0 && p[len(p)-1] == '\n' {
  41. p = p[:len(p)-1]
  42. }
  43. if t == nil {
  44. // if there is no running test, the log message should be outputted to console, to avoid losing important information.
  45. // the "???" prefix is used to match the "===" and "+++" in PrintCurrentTest
  46. return fmt.Fprintf(os.Stdout, "??? [TestLogger] %s\n", p)
  47. }
  48. t.Log(string(p))
  49. return len(p), nil
  50. }
  51. func (w *testLoggerWriterCloser) popT() {
  52. w.Lock()
  53. if len(w.t) > 0 {
  54. w.t = w.t[:len(w.t)-1]
  55. }
  56. w.Unlock()
  57. }
  58. func (w *testLoggerWriterCloser) Close() error {
  59. return nil
  60. }
  61. func (w *testLoggerWriterCloser) Reset() {
  62. w.Lock()
  63. if len(w.t) > 0 {
  64. for _, t := range w.t {
  65. if t == nil {
  66. continue
  67. }
  68. _, _ = fmt.Fprintf(os.Stdout, "Unclosed logger writer in test: %s", t.Name())
  69. t.Errorf("Unclosed logger writer in test: %s", t.Name())
  70. }
  71. w.t = nil
  72. }
  73. w.Unlock()
  74. }
  75. // PrintCurrentTest prints the current test to os.Stdout
  76. func PrintCurrentTest(t testing.TB, skip ...int) func() {
  77. t.Helper()
  78. start := time.Now()
  79. actualSkip := 1
  80. if len(skip) > 0 {
  81. actualSkip = skip[0] + 1
  82. }
  83. _, filename, line, _ := runtime.Caller(actualSkip)
  84. if log.CanColorStdout {
  85. _, _ = fmt.Fprintf(os.Stdout, "=== %s (%s:%d)\n", fmt.Formatter(log.NewColoredValue(t.Name())), strings.TrimPrefix(filename, prefix), line)
  86. } else {
  87. _, _ = fmt.Fprintf(os.Stdout, "=== %s (%s:%d)\n", t.Name(), strings.TrimPrefix(filename, prefix), line)
  88. }
  89. WriterCloser.pushT(t)
  90. return func() {
  91. took := time.Since(start)
  92. if took > SlowTest {
  93. if log.CanColorStdout {
  94. _, _ = 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)))
  95. } else {
  96. _, _ = fmt.Fprintf(os.Stdout, "+++ %s is a slow test (took %v)\n", t.Name(), took)
  97. }
  98. }
  99. timer := time.AfterFunc(SlowFlush, func() {
  100. if log.CanColorStdout {
  101. _, _ = fmt.Fprintf(os.Stdout, "+++ %s ... still flushing after %v ...\n", fmt.Formatter(log.NewColoredValue(t.Name(), log.Bold, log.FgRed)), SlowFlush)
  102. } else {
  103. _, _ = fmt.Fprintf(os.Stdout, "+++ %s ... still flushing after %v ...\n", t.Name(), SlowFlush)
  104. }
  105. })
  106. if err := queue.GetManager().FlushAll(context.Background(), time.Minute); err != nil {
  107. t.Errorf("Flushing queues failed with error %v", err)
  108. }
  109. timer.Stop()
  110. flushTook := time.Since(start) - took
  111. if flushTook > SlowFlush {
  112. if log.CanColorStdout {
  113. _, _ = 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)))
  114. } else {
  115. _, _ = fmt.Fprintf(os.Stdout, "+++ %s had a slow clean-up flush (took %v)\n", t.Name(), flushTook)
  116. }
  117. }
  118. WriterCloser.popT()
  119. }
  120. }
  121. // Printf takes a format and args and prints the string to os.Stdout
  122. func Printf(format string, args ...any) {
  123. if log.CanColorStdout {
  124. for i := 0; i < len(args); i++ {
  125. args[i] = log.NewColoredValue(args[i])
  126. }
  127. }
  128. _, _ = fmt.Fprintf(os.Stdout, "\t"+format, args...)
  129. }
  130. // TestLogEventWriter is a logger which will write to the testing log
  131. type TestLogEventWriter struct {
  132. *log.EventWriterBaseImpl
  133. }
  134. // NewTestLoggerWriter creates a TestLogEventWriter as a log.LoggerProvider
  135. func NewTestLoggerWriter(name string, mode log.WriterMode) log.EventWriter {
  136. w := &TestLogEventWriter{}
  137. w.EventWriterBaseImpl = log.NewEventWriterBase(name, "test-log-writer", mode)
  138. w.OutputWriteCloser = WriterCloser
  139. return w
  140. }
  141. func init() {
  142. const relFilePath = "modules/testlogger/testlogger.go"
  143. _, filename, _, _ := runtime.Caller(0)
  144. if !strings.HasSuffix(filename, relFilePath) {
  145. panic("source code file path doesn't match expected: " + relFilePath)
  146. }
  147. prefix = strings.TrimSuffix(filename, relFilePath)
  148. }