| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- package util
- import (
- "io/ioutil"
- "net/http"
- "testing"
- "gitea.ckfah.com/cjjy/gocommon/pkg/common"
- "gitea.ckfah.com/cjjy/gocommon/pkg/logger"
- "gitea.ckfah.com/cjjy/gocommon/pkg/net/engines"
- )
- func MockContext() *engines.Context {
- ctx := &engines.Context{}
- ctx.Set(logger.TraceIdKey, logger.GenerateTraceId())
- return ctx
- }
- type Testing interface {
- CheckResult(result interface{}, err interface{})
- }
- type _testing struct {
- testing.TB
- }
- func NewTesting(t testing.TB) Testing {
- return &_testing{TB: t}
- }
- // 测试必备包!!
- // 后期改进,支持动态参数识别,自动抓取error
- func (t *_testing) CheckResult(result interface{}, err interface{}) {
- printError := func(err interface{}) {
- t.Fatalf("\n================ Error ================\n\n"+
- "%s"+
- "\n\n================= End =================\n\n", err)
- return
- }
- if err != nil {
- printError(err)
- return
- }
- printSuccess := func(jsonBody []byte) {
- jsonBody, err = common.JsonFormat(jsonBody)
- if err != nil {
- printError(err)
- return
- }
- t.Logf("\n================ Success ================\n\n"+
- "%s"+
- "\n\n================== End ==================\n\n", jsonBody)
- }
- printResponse := func(response *http.Response) {
- status := response.StatusCode
- header := response.Header
- jsonBody, err := ioutil.ReadAll(response.Body)
- if err != nil {
- printError(err)
- return
- }
- jsonBody, err = common.JsonFormat(jsonBody)
- if err != nil {
- printError(err)
- return
- }
- t.Logf("\n================ Success ================\n"+
- "HTTP-STATUS: %v\n"+
- "HTTP-HEADER: %#v\n"+
- "HTTP-BODY:\n%s\n"+
- "\n\n================== End ==================\n\n", status, header, jsonBody)
- }
- var (
- jsonBody []byte
- )
- switch typeResult := result.(type) {
- case []byte:
- jsonBody = typeResult
- case string:
- jsonBody = []byte(typeResult)
- case *http.Response:
- printResponse(typeResult)
- return
- default:
- jsonBody, err = common.MarshalJsonFormat(&result)
- }
- if err != nil {
- printError(err)
- return
- }
- printSuccess(jsonBody)
- }
|