Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

testlogger.go 5.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package integrations
  5. import (
  6. "context"
  7. "fmt"
  8. "os"
  9. "runtime"
  10. "strings"
  11. "sync"
  12. "testing"
  13. "time"
  14. "code.gitea.io/gitea/modules/json"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/queue"
  17. )
  18. var (
  19. prefix string
  20. slowTest = 10 * time.Second
  21. slowFlush = 5 * time.Second
  22. )
  23. // TestLogger is a logger which will write to the testing log
  24. type TestLogger struct {
  25. log.WriterLogger
  26. }
  27. var writerCloser = &testLoggerWriterCloser{}
  28. type testLoggerWriterCloser struct {
  29. sync.RWMutex
  30. t []*testing.TB
  31. }
  32. func (w *testLoggerWriterCloser) setT(t *testing.TB) {
  33. w.Lock()
  34. w.t = append(w.t, t)
  35. w.Unlock()
  36. }
  37. func (w *testLoggerWriterCloser) Write(p []byte) (int, error) {
  38. w.RLock()
  39. var t *testing.TB
  40. if len(w.t) > 0 {
  41. t = w.t[len(w.t)-1]
  42. }
  43. w.RUnlock()
  44. if t != nil && *t != nil {
  45. if len(p) > 0 && p[len(p)-1] == '\n' {
  46. p = p[:len(p)-1]
  47. }
  48. defer func() {
  49. err := recover()
  50. if err == nil {
  51. return
  52. }
  53. var errString string
  54. errErr, ok := err.(error)
  55. if ok {
  56. errString = errErr.Error()
  57. } else {
  58. errString, ok = err.(string)
  59. }
  60. if !ok {
  61. panic(err)
  62. }
  63. if !strings.HasPrefix(errString, "Log in goroutine after ") {
  64. panic(err)
  65. }
  66. }()
  67. (*t).Log(string(p))
  68. return len(p), nil
  69. }
  70. return len(p), nil
  71. }
  72. func (w *testLoggerWriterCloser) Close() error {
  73. w.Lock()
  74. if len(w.t) > 0 {
  75. w.t = w.t[:len(w.t)-1]
  76. }
  77. w.Unlock()
  78. return nil
  79. }
  80. func (w *testLoggerWriterCloser) Reset() {
  81. w.Lock()
  82. if len(w.t) > 0 {
  83. for _, t := range w.t {
  84. if t == nil {
  85. continue
  86. }
  87. fmt.Fprintf(os.Stdout, "Unclosed logger writer in test: %s", (*t).Name())
  88. (*t).Errorf("Unclosed logger writer in test: %s", (*t).Name())
  89. }
  90. w.t = nil
  91. }
  92. w.Unlock()
  93. }
  94. // PrintCurrentTest prints the current test to os.Stdout
  95. func PrintCurrentTest(t testing.TB, skip ...int) func() {
  96. start := time.Now()
  97. actualSkip := 1
  98. if len(skip) > 0 {
  99. actualSkip = skip[0]
  100. }
  101. _, filename, line, _ := runtime.Caller(actualSkip)
  102. if log.CanColorStdout {
  103. fmt.Fprintf(os.Stdout, "=== %s (%s:%d)\n", fmt.Formatter(log.NewColoredValue(t.Name())), strings.TrimPrefix(filename, prefix), line)
  104. } else {
  105. fmt.Fprintf(os.Stdout, "=== %s (%s:%d)\n", t.Name(), strings.TrimPrefix(filename, prefix), line)
  106. }
  107. writerCloser.setT(&t)
  108. return func() {
  109. took := time.Since(start)
  110. if took > slowTest {
  111. if log.CanColorStdout {
  112. 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)))
  113. } else {
  114. fmt.Fprintf(os.Stdout, "+++ %s is a slow test (took %v)\n", t.Name(), took)
  115. }
  116. }
  117. timer := time.AfterFunc(slowFlush, func() {
  118. if log.CanColorStdout {
  119. fmt.Fprintf(os.Stdout, "+++ %s ... still flushing after %v ...\n", fmt.Formatter(log.NewColoredValue(t.Name(), log.Bold, log.FgRed)), slowFlush)
  120. } else {
  121. fmt.Fprintf(os.Stdout, "+++ %s ... still flushing after %v ...\n", t.Name(), slowFlush)
  122. }
  123. })
  124. if err := queue.GetManager().FlushAll(context.Background(), 2*time.Minute); err != nil {
  125. t.Errorf("Flushing queues failed with error %v", err)
  126. }
  127. timer.Stop()
  128. flushTook := time.Since(start) - took
  129. if flushTook > slowFlush {
  130. if log.CanColorStdout {
  131. 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)))
  132. } else {
  133. fmt.Fprintf(os.Stdout, "+++ %s had a slow clean-up flush (took %v)\n", t.Name(), flushTook)
  134. }
  135. }
  136. _ = writerCloser.Close()
  137. }
  138. }
  139. // Printf takes a format and args and prints the string to os.Stdout
  140. func Printf(format string, args ...interface{}) {
  141. if log.CanColorStdout {
  142. for i := 0; i < len(args); i++ {
  143. args[i] = log.NewColoredValue(args[i])
  144. }
  145. }
  146. fmt.Fprintf(os.Stdout, "\t"+format, args...)
  147. }
  148. // NewTestLogger creates a TestLogger as a log.LoggerProvider
  149. func NewTestLogger() log.LoggerProvider {
  150. logger := &TestLogger{}
  151. logger.Colorize = log.CanColorStdout
  152. logger.Level = log.TRACE
  153. return logger
  154. }
  155. // Init inits connection writer with json config.
  156. // json config only need key "level".
  157. func (log *TestLogger) Init(config string) error {
  158. err := json.Unmarshal([]byte(config), log)
  159. if err != nil {
  160. return err
  161. }
  162. log.NewWriterLogger(writerCloser)
  163. return nil
  164. }
  165. // Content returns the content accumulated in the content provider
  166. func (log *TestLogger) Content() (string, error) {
  167. return "", fmt.Errorf("not supported")
  168. }
  169. // Flush when log should be flushed
  170. func (log *TestLogger) Flush() {
  171. }
  172. // ReleaseReopen does nothing
  173. func (log *TestLogger) ReleaseReopen() error {
  174. return nil
  175. }
  176. // GetName returns the default name for this implementation
  177. func (log *TestLogger) GetName() string {
  178. return "test"
  179. }
  180. func init() {
  181. log.Register("test", NewTestLogger)
  182. _, filename, _, _ := runtime.Caller(0)
  183. prefix = strings.TrimSuffix(filename, "integrations/testlogger.go")
  184. }