github.com/cloudwego/hertz@v0.9.3/pkg/common/ut/request.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 ut provides a convenient way to write unit test for the business logic.
    18  package ut
    19  
    20  import (
    21  	"context"
    22  	"io"
    23  
    24  	"github.com/cloudwego/hertz/pkg/route"
    25  )
    26  
    27  // Header is a key-value pair indicating one http header
    28  type Header struct {
    29  	Key   string
    30  	Value string
    31  }
    32  
    33  // Body is for setting Request.Body
    34  type Body struct {
    35  	Body io.Reader
    36  	Len  int
    37  }
    38  
    39  // PerformRequest send a constructed request to given engine without network transporting
    40  //
    41  // # Url can be a standard relative URI or a simple absolute path
    42  //
    43  // If engine.streamRequestBody is true, it sets body as bodyStream
    44  // if not, it sets body as bodyBytes
    45  //
    46  // ResponseRecorder returned are flushed, which means its StatusCode is always set (default 200)
    47  //
    48  // See ./request_test.go for more examples
    49  func PerformRequest(engine *route.Engine, method, url string, body *Body, headers ...Header) *ResponseRecorder {
    50  	ctx := createUtRequestContext(engine, method, url, body, headers...)
    51  	engine.ServeHTTP(context.Background(), ctx)
    52  
    53  	w := NewRecorder()
    54  	h := w.Header()
    55  	ctx.Response.Header.CopyTo(h)
    56  
    57  	w.WriteHeader(ctx.Response.StatusCode())
    58  	w.Write(ctx.Response.Body())
    59  	w.Flush()
    60  	return w
    61  }