【发布时间】:2020-09-08 15:19:17
【问题描述】:
我正在测试我的一个 http 处理程序。
像这样的卷曲有效:curl localhost:8080/v1/parts/2bb834c9-8e17-4e2c-80b9-a20b80732899。
但相应的测试失败,因为处理程序无法从 URL 中提取 id。
请看一下这个测试文件。我不明白为什么我的 curl 命令有效,但第 17 行的 newRequest 失败。
1 package part
2
3 import (
4 "net/http"
5 "net/http/httptest"
6 "testing"
7
8 "github.com/labstack/echo/v4"
9 "github.com/stretchr/testify/assert"
10 )
11
12 var handler *Handler
13
14 func TestGetPart(t *testing.T) {
15 e := echo.New()
16
17 req := httptest.NewRequest("GET", "/v1/parts/2bb834c9-8e17-4e2c-80b9-a20b80732899", nil)
18 rec := httptest.NewRecorder()
19 c := e.NewContext(req, rec)
20
21 if assert.NoError(t, handler.handleGetPart(c)) {
22 assert.Equal(t, http.StatusOK, rec.Code)
23 }
24 }
去测试 -v ./internal/handler/part
=== RUN TestGetPart
2020/09/08 08:51:10 UUID PASSED:
time="2020-09-08T08:51:10+02:00" level=error msg="Could not decode string to uuid"
TestGetPart: handler_test.go:21:
Error Trace: handler_test.go:21
Error: Received unexpected error:
invalid UUID length: 0
Test: TestGetPart
--- FAIL: TestGetPart (0.00s)
处理程序
ID := ctx.Param("id")
log.Println("UUID PASSED: ", ID)
uuid, err := uuid.Parse(ID)
if err != nil {
logrus.Error("Could not decode string to uuid")
return err
}
// Fetch data.json from S3 bucket
filename := helper.PartFileName(uuid)
content, err := a.GetObject(filename)
if err != nil {
logrus.Error(err)
return ctx.JSON(http.StatusNotFound, "file not found")
}
return ctx.String(http.StatusOK, content)
}
我的任何路线:
func Register(router *echo.Echo, handler *Handler) {
router.GET("/v1/parts/:id", handler.handleGetPart)
}
【问题讨论】:
-
如果您的错误消息包含实际的错误消息,调试起来会容易得多:
logrus.Errorf("Could not decode string '%s' to uuid: %s", ID, err)