首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在访问日志中间件情况下进行单元测试

如何在访问日志中间件情况下进行单元测试
EN

Stack Overflow用户
提问于 2019-12-27 11:01:27
回答 1查看 847关注 0票数 0

我有一个中间件来记录这个服务访问。但是我在做单元测试时迷惑了好几次,我在谷歌上冲浪。我还没有找到解决这个问题的正确方法。

代码语言:javascript
运行
复制
package accesslog

import (
    "net/http"
    "time"

    "github.com/go-chi/chi/middleware"

    "transactionService/pkg/log"
)

func Handler(logger log.Logger) func(next http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
        fn := func(w http.ResponseWriter, r *http.Request) {
            ctx := r.Context()
            ctx = log.WithRequest(ctx, r)
            ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)

            start := time.Now()
            defer func() {
                logger.With(ctx, "duration", time.Since(start), "status", ww.Status()).
                    Infof("%s %s %s %d %d", r.Method, r.URL.Path, r.Proto, ww.Status(), ww.BytesWritten())
            }()

            next.ServeHTTP(ww, r.WithContext(ctx))
        }

        return http.HandlerFunc(fn)
    }
}
EN

回答 1

Stack Overflow用户

发布于 2019-12-27 16:46:00

解决,这是我用来解决它的代码

代码语言:javascript
运行
复制
package accesslog

import (
    "io"
    "io/ioutil"
    "net/http"
    "net/http/httptest"
    "testing"

    "github.com/go-chi/chi"

    "transactionService/pkg/log"
)

func TestHandler(t *testing.T) {
    logger, _ := log.NewForTest()

    r := chi.NewRouter()
    r.Use(Handler(logger))
    r.Get("/", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        _, _ = w.Write([]byte("test"))
    })

    ts := httptest.NewServer(r)
    defer ts.Close()

    if resp, body := testRequest(t, ts, "GET", "/", nil); body != "root" && resp.StatusCode != 200 {
        t.Fatalf(body)
    }
}

func testRequest(t *testing.T, ts *httptest.Server, method, path string, body io.Reader) (*http.Response, string) {
    req, err := http.NewRequest(method, ts.URL+path, body)
    if err != nil {
        t.Fatal(err)
        return nil, ""
    }

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        t.Fatal(err)
        return nil, ""
    }

    respBody, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        t.Fatal(err)
        return nil, ""
    }
    defer resp.Body.Close()

    return resp, string(respBody)
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59495537

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档