登录
首页 >  Golang >  Go问答

中间件访问日志的单元测试方法

来源:stackoverflow

时间:2024-03-25 21:06:26 221浏览 收藏

中间件访问日志的单元测试方法在开发过程中至关重要,但缺乏清晰的指导。本文介绍了一种有效的单元测试方法,使用 `github.com/go-chi/chi/middleware` 包和 `github.com/go-chi/chi` 路由器来测试中间件。该方法通过创建 HTTP 请求并断言响应代码和日志消息的正确性,验证中间件在记录访问日志方面的行为。

问题内容

我有一个中间件来记录此服务访问。但我在谷歌上搜索了几次后,对进行单元测试感到困惑。我还没有找到解决这个问题的正确方法

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

解决方案


已解决,这是我解决问题的代码

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

到这里,我们也就讲完了《中间件访问日志的单元测试方法》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>