mardi 8 septembre 2020

Testing echo handlers with path variables

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

Aucun commentaire:

Enregistrer un commentaire