dongtan6695 2018-07-05 23:16
浏览 82
已采纳

测试修改请求的golang中间件

I have some middleware that adds a context with a request id to a request.

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))
})}

How do I write a test for this ?

  • 写回答

1条回答 默认 最新

  • dongqiao6730 2018-07-06 00:15
    关注

    To test that, you need to run that handler passing in a request, and using a custom next handler that checks that the request was indeed modified.

    You can create that handler as follows:

    (I am assuming your NewContextWithRequestID adds a "reqId" key to the request with a "1234" value, you should of course modify the assertions as needed)

    // 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")
        }
    })
    

    You can then use that handler as your next one:

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

    And then invoke that handler:

    // 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)
    

    Putting everything together as a working test, that'd be the code below.

    Note: I fixed a small bug in your original "AddContextWithRequestID", as the ctx value started with a nil value when you just declared it with no initialization.

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图