test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package util
  2. import (
  3. "io/ioutil"
  4. "net/http"
  5. "testing"
  6. "gitea.ckfah.com/cjjy/gocommon/pkg/common"
  7. "gitea.ckfah.com/cjjy/gocommon/pkg/logger"
  8. "gitea.ckfah.com/cjjy/gocommon/pkg/net/engines"
  9. )
  10. func MockContext() *engines.Context {
  11. ctx := &engines.Context{}
  12. ctx.Set(logger.TraceIdKey, logger.GenerateTraceId())
  13. return ctx
  14. }
  15. type Testing interface {
  16. CheckResult(result interface{}, err interface{})
  17. }
  18. type _testing struct {
  19. testing.TB
  20. }
  21. func NewTesting(t testing.TB) Testing {
  22. return &_testing{TB: t}
  23. }
  24. // 测试必备包!!
  25. // 后期改进,支持动态参数识别,自动抓取error
  26. func (t *_testing) CheckResult(result interface{}, err interface{}) {
  27. printError := func(err interface{}) {
  28. t.Fatalf("\n================ Error ================\n\n"+
  29. "%s"+
  30. "\n\n================= End =================\n\n", err)
  31. return
  32. }
  33. if err != nil {
  34. printError(err)
  35. return
  36. }
  37. printSuccess := func(jsonBody []byte) {
  38. jsonBody, err = common.JsonFormat(jsonBody)
  39. if err != nil {
  40. printError(err)
  41. return
  42. }
  43. t.Logf("\n================ Success ================\n\n"+
  44. "%s"+
  45. "\n\n================== End ==================\n\n", jsonBody)
  46. }
  47. printResponse := func(response *http.Response) {
  48. status := response.StatusCode
  49. header := response.Header
  50. jsonBody, err := ioutil.ReadAll(response.Body)
  51. if err != nil {
  52. printError(err)
  53. return
  54. }
  55. jsonBody, err = common.JsonFormat(jsonBody)
  56. if err != nil {
  57. printError(err)
  58. return
  59. }
  60. t.Logf("\n================ Success ================\n"+
  61. "HTTP-STATUS: %v\n"+
  62. "HTTP-HEADER: %#v\n"+
  63. "HTTP-BODY:\n%s\n"+
  64. "\n\n================== End ==================\n\n", status, header, jsonBody)
  65. }
  66. var (
  67. jsonBody []byte
  68. )
  69. switch typeResult := result.(type) {
  70. case []byte:
  71. jsonBody = typeResult
  72. case string:
  73. jsonBody = []byte(typeResult)
  74. case *http.Response:
  75. printResponse(typeResult)
  76. return
  77. default:
  78. jsonBody, err = common.MarshalJsonFormat(&result)
  79. }
  80. if err != nil {
  81. printError(err)
  82. return
  83. }
  84. printSuccess(jsonBody)
  85. }