测试 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学习网公众号了解相关技术文章。
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
-
139 收藏
-
204 收藏
-
325 收藏
-
477 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习