You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

187 lines
4.5 KiB

  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. "encoding/json"
  8. "fmt"
  9. "os"
  10. "runtime"
  11. "strings"
  12. "sync"
  13. "testing"
  14. "time"
  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. // PrintCurrentTest prints the current test to os.Stdout
  81. func PrintCurrentTest(t testing.TB, skip ...int) func() {
  82. start := time.Now()
  83. actualSkip := 1
  84. if len(skip) > 0 {
  85. actualSkip = skip[0]
  86. }
  87. _, filename, line, _ := runtime.Caller(actualSkip)
  88. if log.CanColorStdout {
  89. fmt.Fprintf(os.Stdout, "=== %s (%s:%d)\n", fmt.Formatter(log.NewColoredValue(t.Name())), strings.TrimPrefix(filename, prefix), line)
  90. } else {
  91. fmt.Fprintf(os.Stdout, "=== %s (%s:%d)\n", t.Name(), strings.TrimPrefix(filename, prefix), line)
  92. }
  93. writerCloser.setT(&t)
  94. return func() {
  95. took := time.Since(start)
  96. if took > slowTest {
  97. if log.CanColorStdout {
  98. 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)))
  99. } else {
  100. fmt.Fprintf(os.Stdout, "+++ %s is a slow tets (took %v)\n", t.Name(), took)
  101. }
  102. }
  103. timer := time.AfterFunc(slowFlush, func() {
  104. if log.CanColorStdout {
  105. fmt.Fprintf(os.Stdout, "+++ %s ... still flushing after %v ...\n", fmt.Formatter(log.NewColoredValue(t.Name(), log.Bold, log.FgRed)), slowFlush)
  106. } else {
  107. fmt.Fprintf(os.Stdout, "+++ %s ... still flushing after %v ...\n", t.Name(), slowFlush)
  108. }
  109. })
  110. if err := queue.GetManager().FlushAll(context.Background(), -1); err != nil {
  111. t.Errorf("Flushing queues failed with error %v", err)
  112. }
  113. timer.Stop()
  114. flushTook := time.Since(start) - took
  115. if flushTook > slowFlush {
  116. if log.CanColorStdout {
  117. 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)))
  118. } else {
  119. fmt.Fprintf(os.Stdout, "+++ %s had a slow clean-up flush (took %v)\n", t.Name(), flushTook)
  120. }
  121. }
  122. _ = writerCloser.Close()
  123. }
  124. }
  125. // Printf takes a format and args and prints the string to os.Stdout
  126. func Printf(format string, args ...interface{}) {
  127. if log.CanColorStdout {
  128. for i := 0; i < len(args); i++ {
  129. args[i] = log.NewColoredValue(args[i])
  130. }
  131. }
  132. fmt.Fprintf(os.Stdout, "\t"+format, args...)
  133. }
  134. // NewTestLogger creates a TestLogger as a log.LoggerProvider
  135. func NewTestLogger() log.LoggerProvider {
  136. logger := &TestLogger{}
  137. logger.Colorize = log.CanColorStdout
  138. logger.Level = log.TRACE
  139. return logger
  140. }
  141. // Init inits connection writer with json config.
  142. // json config only need key "level".
  143. func (log *TestLogger) Init(config string) error {
  144. err := json.Unmarshal([]byte(config), log)
  145. if err != nil {
  146. return err
  147. }
  148. log.NewWriterLogger(writerCloser)
  149. return nil
  150. }
  151. // Flush when log should be flushed
  152. func (log *TestLogger) Flush() {
  153. }
  154. //ReleaseReopen does nothing
  155. func (log *TestLogger) ReleaseReopen() error {
  156. return nil
  157. }
  158. // GetName returns the default name for this implementation
  159. func (log *TestLogger) GetName() string {
  160. return "test"
  161. }
  162. func init() {
  163. log.Register("test", NewTestLogger)
  164. _, filename, _, _ := runtime.Caller(0)
  165. prefix = strings.TrimSuffix(filename, "integrations/testlogger.go")
  166. }