github.com/cloudwego/hertz@v0.9.3/pkg/app/middlewares/server/recovery/recovery_test.go (about)

     1  /*
     2   * Copyright 2022 CloudWeGo Authors
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package recovery
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  	"testing"
    23  
    24  	"github.com/cloudwego/hertz/pkg/app"
    25  	"github.com/cloudwego/hertz/pkg/common/test/assert"
    26  	"github.com/cloudwego/hertz/pkg/protocol/consts"
    27  )
    28  
    29  func TestRecovery(t *testing.T) {
    30  	ctx := app.NewContext(0)
    31  	var hc app.HandlersChain
    32  	hc = append(hc, func(c context.Context, ctx *app.RequestContext) {
    33  		fmt.Println("this is test")
    34  		panic("test")
    35  	})
    36  	ctx.SetHandlers(hc)
    37  
    38  	Recovery()(context.Background(), ctx)
    39  
    40  	if ctx.Response.StatusCode() != 500 {
    41  		t.Fatalf("unexpected %v. Expecting %v", ctx.Response.StatusCode(), 500)
    42  	}
    43  }
    44  
    45  func TestWithRecoveryHandler(t *testing.T) {
    46  	ctx := app.NewContext(0)
    47  	var hc app.HandlersChain
    48  	hc = append(hc, func(c context.Context, ctx *app.RequestContext) {
    49  		fmt.Println("this is test")
    50  		panic("test")
    51  	})
    52  	ctx.SetHandlers(hc)
    53  
    54  	Recovery(WithRecoveryHandler(newRecoveryHandler))(context.Background(), ctx)
    55  
    56  	if ctx.Response.StatusCode() != consts.StatusNotImplemented {
    57  		t.Fatalf("unexpected %v. Expecting %v", ctx.Response.StatusCode(), 501)
    58  	}
    59  	assert.DeepEqual(t, "{\"msg\":\"test\"}", string(ctx.Response.Body()))
    60  }