测试修改请求的 golang 中间件

scu*_*uit 6 testing middleware go

我有一些中间件可以将带有请求 ID 的上下文添加到请求中。

func AddContextWithRequestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    var ctx context.Context
    ctx = NewContextWithRequestID(ctx, r)
    next.ServeHTTP(w, r.WithContext(ctx))
})}
Run Code Online (Sandbox Code Playgroud)

我如何为此编写测试?

eug*_*ioy 8

要对此进行测试,您需要运行传入请求的处理程序,并使用自定义next处理程序来检查请求是否确实已修改。

您可以按如下方式创建该处理程序:

(我假设您NewContextWithRequestID向具有“1234”值的请求添加了“reqId”键,您当然应该根据需要修改断言)

// create a handler to use as "next" which will verify the request
nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    val := r.Context().Value("reqId")
    if val == nil {
        t.Error("reqId not present")
    }
    valStr, ok := val.(string)
    if !ok {
        t.Error("not string")
    }
    if valStr != "1234" {
        t.Error("wrong reqId")
    }
})
Run Code Online (Sandbox Code Playgroud)

然后您可以使用该处理程序作为您的处理程序next

// create the handler to test, using our custom "next" handler
handlerToTest := AddContextWithRequestID(nextHandler)
Run Code Online (Sandbox Code Playgroud)

然后调用该处理程序:

// create a mock request to use
req := httptest.NewRequest("GET", "http://testing", nil)
// call the handler using a mock response recorder (we'll not use that anyway)
handlerToTest.ServeHTTP(httptest.NewRecorder(), req)
Run Code Online (Sandbox Code Playgroud)

将所有内容放在一起作为工作测试,这就是下面的代码。

注意:我修复了您原来的“AddContextWithRequestID”中的一个小错误,因为该值在您刚刚声明它时没有初始化时ctx以一个nil值开头。

import (
    "net/http"
    "context"
    "testing"
    "net/http/httptest"
)

func NewContextWithRequestID(ctx context.Context, r *http.Request) context.Context {
    return context.WithValue(ctx, "reqId", "1234")
}

func AddContextWithRequestID(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        var ctx = context.Background()
        ctx = NewContextWithRequestID(ctx, r)
        next.ServeHTTP(w, r.WithContext(ctx))
    })
}

func TestIt(t *testing.T) {

    // create a handler to use as "next" which will verify the request
    nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        val := r.Context().Value("reqId")
        if val == nil {
            t.Error("reqId not present")
        }
        valStr, ok := val.(string)
        if !ok {
            t.Error("not string")
        }
        if valStr != "1234" {
            t.Error("wrong reqId")
        }
    })

    // create the handler to test, using our custom "next" handler
    handlerToTest := AddContextWithRequestID(nextHandler)

    // create a mock request to use
    req := httptest.NewRequest("GET", "http://testing", nil)

    // call the handler using a mock response recorder (we'll not use that anyway)
    handlerToTest.ServeHTTP(httptest.NewRecorder(), req)
}
Run Code Online (Sandbox Code Playgroud)

  • @Raz:似乎您的原始“AddContextWithRequestID”有一个小错误,因为“ctx”在您刚刚声明但未为其分配任何内容时以 nil 值开头。我编辑了我的答案以通过分配 ctx​​ = context.Background() 来解决这个问题 (2认同)