测试带有路径变量的回声处理程序

huangapple go评论88阅读模式
英文:

Testing echo handlers with path variables

问题

我正在测试我的一个HTTP处理程序。像这样的curl命令是有效的: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 }

go test -v ./internal/handler/part

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
        }

        // 从S3存储桶中获取data.json
        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)
} 

我的路由:

        router.GET("/v1/parts/:id", handler.handleGetPart)
}
英文:

I’m testing one of my http handlers.
A curl like this works: curl localhost:8080/v1/parts/2bb834c9-8e17-4e2c-80b9-a20b80732899.
But the corresponding test fails as the handler is not able to extract the id from the URL.

Please have a look at this test file. I don’t understand why my curl command works but the newRequest on line 17 fails.

  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 }

go test -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)

The handler

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

Any my route:

func Register(router *echo.Echo, handler *Handler) {
        router.GET("/v1/parts/:id", handler.handleGetPart)
}

答案1

得分: 6

你应该这样设置路径:

e := echo.New()
req := httptest.NewRequest("GET", "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)

c.SetPath("/:id")
c.SetParamNames("id")
c.SetParamValues("2bb834c9-8e17-4e2c-80b9-a20b80732899")
// 测试的其余部分在下面
英文:

You should set a path in this way:

e := echo.New()
req := httptest.NewRequest("GET", "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)

c.SetPath("/:id")
c.SetParamNames("id")
c.SetParamValues("2bb834c9-8e17-4e2c-80b9-a20b80732899")
// rest of the test goes below

huangapple
  • 本文由 发表于 2020年9月8日 15:02:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/63788674.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定