登录
首页 >  Golang >  Go问答

测试 Chi 路由的路径变量

来源:stackoverflow

时间:2024-03-22 19:18:33 373浏览 收藏

在测试 Go-Chi 路由的路径变量时,使用 `httptest.NewRequest` 不会自动将 URL 参数添加到请求上下文中,导致在使用 `articlectx` 中间件时出现 `http 错误:不可处理实体`。要解决此问题,需要手动将 URL 参数添加到请求上下文中,如下所示: ```go w := httptest.NewRecorder() r := httptest.NewRequest("GET", "/articles/{articleid}", nil) rctx := chi.NewRouteContext() rctx.URLParams.Add("articleid", "123") r = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, rctx)) ```

问题内容

我在测试 go-chi 路线时遇到问题,特别是带有路径变量的路线。使用 go run main.go 运行服务器工作正常,并且对带有路径变量的路由的请求的行为符合预期。

当我运行路由测试时,我总是收到 http 错误:unprocessable entity。注销 articleid 发生的情况后,articlectx 似乎无法访问路径变量。不确定这是否意味着我需要在测试中使用 articlectx,但我尝试过 articlectx(http.handlerfunc(getarticleid)) 并收到错误:

panic:接口转换:interface {} 为 nil,不是 *chi.context [已恢复] 恐慌:接口转换:接口{}为零,而不是*chi.context

运行服务器:go run main.go

测试服务器:go test .

我的来源:

// main.go

package main

import (
    "context"
    "fmt"
    "net/http"
    "strconv"

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

type ctxkey struct {
    name string
}

func main() {
    r := chi.newrouter()

    r.route("/articles", func(r chi.router) {
        r.route("/{articleid}", func(r chi.router) {
            r.use(articlectx)
            r.get("/", getarticleid) // get /articles/123
        })
    })

    http.listenandserve(":3333", r)
}

// articlectx gives the routes using it access to the requested article id in the path
func articlectx(next http.handler) http.handler {
    return http.handlerfunc(func(w http.responsewriter, r *http.request) {
        articleparam := chi.urlparam(r, "articleid")
        articleid, err := strconv.atoi(articleparam)
        if err != nil {
            http.error(w, http.statustext(http.statusbadrequest), http.statusbadrequest)
            return
        }

        ctx := context.withvalue(r.context(), ctxkey{"articleid"}, articleid)
        next.servehttp(w, r.withcontext(ctx))
    })
}

// getarticleid returns the article id that the client requested
func getarticleid(w http.responsewriter, r *http.request) {
    ctx := r.context()
    articleid, ok := ctx.value(ctxkey{"articleid"}).(int)
    if !ok {
        http.error(w, http.statustext(http.statusunprocessableentity), http.statusunprocessableentity)
        return
    }

    w.write([]byte(fmt.sprintf("article id:%d", articleid)))
}
// main_test.go

package main

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

func TestGetArticleID(t *testing.T) {
    tests := []struct {
        name           string
        rec            *httptest.ResponseRecorder
        req            *http.Request
        expectedBody   string
        expectedHeader string
    }{
        {
            name:         "OK_1",
            rec:          httptest.NewRecorder(),
            req:          httptest.NewRequest("GET", "/articles/1", nil),
            expectedBody: `article ID:1`,
        },
        {
            name:         "OK_100",
            rec:          httptest.NewRecorder(),
            req:          httptest.NewRequest("GET", "/articles/100", nil),
            expectedBody: `article ID:100`,
        },
        {
            name:         "BAD_REQUEST",
            rec:          httptest.NewRecorder(),
            req:          httptest.NewRequest("PUT", "/articles/bad", nil),
            expectedBody: fmt.Sprintf("%s\n", http.StatusText(http.StatusBadRequest)),
        },
    }

    for _, test := range tests {
        t.Run(test.name, func(t *testing.T) {
            ArticleCtx(http.HandlerFunc(GetArticleID)).ServeHTTP(test.rec, test.req)

            if test.expectedBody != test.rec.Body.String() {
                t.Errorf("Got: \t\t%s\n\tExpected: \t%s\n", test.rec.Body.String(), test.expectedBody)
            }
        })
    }
}

不知道如何继续。有任何想法吗?我想知道 net/http/httptest 中是否有关于使用 context 进行测试的答案,但没有看到任何内容。

也是相当新的 go go(以及 context 包),因此非常感谢任何代码审查/最佳实践评论:)


解决方案


尽管我直接对处理程序进行单元测试,但也有类似的问题。基本上,使用 httptest.newrequest 时,url 参数似乎不会自动添加到请求上下文中,迫使您手动添加它们。

像下面这样的东西对我有用。

w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "/{key}", nil)

rctx := chi.NewRouteContext()
rctx.URLParams.Add("key", "value")

r = r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, rctx))

handler := func(w http.ResponseWriter, r *http.Request) {
    value := chi.URLParam(r, "key")
}
handler(w, r)

所有功劳归于soedar here =)

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《测试 Chi 路由的路径变量》文章吧,也可关注golang学习网公众号了解相关技术文章。

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