github.com/wfusion/gofusion@v1.1.14/test/http/cases/middleware_test.go (about)

     1  package cases
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net/http"
     7  	"testing"
     8  
     9  	"github.com/gin-gonic/gin"
    10  	"github.com/pkg/errors"
    11  	"github.com/stretchr/testify/suite"
    12  
    13  	"github.com/wfusion/gofusion/common/utils"
    14  	"github.com/wfusion/gofusion/log"
    15  
    16  	fusHtp "github.com/wfusion/gofusion/http"
    17  	testHtp "github.com/wfusion/gofusion/test/http"
    18  )
    19  
    20  func TestMiddleware(t *testing.T) {
    21  	testingSuite := &Middleware{Test: new(testHtp.Test)}
    22  	testingSuite.Init(testingSuite)
    23  	suite.Run(t, testingSuite)
    24  }
    25  
    26  type Middleware struct {
    27  	*testHtp.Test
    28  }
    29  
    30  func (t *Middleware) BeforeTest(suiteName, testName string) {
    31  	t.Catch(func() {
    32  		log.Info(context.Background(), "right before %s %s", suiteName, testName)
    33  	})
    34  }
    35  
    36  func (t *Middleware) AfterTest(suiteName, testName string) {
    37  	t.Catch(func() {
    38  		log.Info(context.Background(), "right after %s %s", suiteName, testName)
    39  	})
    40  }
    41  
    42  func (t *Middleware) TestRecover() {
    43  	t.Catch(func() {
    44  		// Given
    45  		path := "/TestRecover"
    46  		ctx := context.Background()
    47  		router := fusHtp.Use(fusHtp.AppName(t.AppName()))
    48  		router.POST(path, func(c *gin.Context) error {
    49  			panic(errors.New("TestRecover panic"))
    50  		})
    51  		router.Start()
    52  		<-router.Running()
    53  		cli := fusHtp.NewRequest(ctx, fusHtp.CName(clientLocalName), fusHtp.AppName(t.AppName()))
    54  		rsp, err := cli.Post(t.addr() + path)
    55  		t.NoError(err)
    56  		t.EqualValues(http.StatusInternalServerError, rsp.StatusCode())
    57  	})
    58  }
    59  
    60  func (t *Middleware) addr() string {
    61  	conf := fusHtp.Use(fusHtp.AppName(t.AppName())).Config()
    62  	if conf.TLS {
    63  		return fmt.Sprintf("https://%s:%v", utils.ClientIP(), conf.Port)
    64  	} else {
    65  		return fmt.Sprintf("http://%s:%v", utils.ClientIP(), conf.Port)
    66  	}
    67  }