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 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘