Description
Issue Description
Hi,
I' currently encountering an issue when setting parameter values via SetParamValues function. This is frequently used by my test cases, hence, tests are all failing.
Checklist
- Dependencies installed
- No typos
- Searched existing issues and docs
Expected behaviour
Should be able to set parameter values via SetParamValues function
Actual behaviour
SetParamValues function throws runtime error: index out of range [0] with length 0
Steps to reproduce
- Create a folder inside your go source path.
- Copy the codes below into files handler.go and handler_test.go and store them inside that folder.
- cd yourfolder
- go test -run ^(TestGetUser)$ -v
It will show this test logs afterwards:
=== RUN TestGetUser
--- FAIL: TestGetUser (0.00s)
panic: runtime error: index out of range [0] with length 0 [recovered]
panic: runtime error: index out of range [0] with length 0goroutine 20 [running]:
testing.tRunner.func1(0xc00010e100)
/usr/local/Cellar/go/1.13.3/libexec/src/testing/testing.go:874 +0x3a3
panic(0x1387d40, 0xc0000c4380)
/usr/local/Cellar/go/1.13.3/libexec/src/runtime/panic.go:679 +0x1b2
github.com/labstack/echo.(*context).SetParamValues(0xc0000bd180, 0xc00008d2b0, 0x1, 0x1)
/Users/sonnysidramos/go/src/github.com/labstack/echo/context.go:317 +0x93
bitbucket.org/pulseid/echotest.TestGetUser(0xc00010e100)
/Users/sonnysidramos/go/src/bitbucket.org/pulseid/echotest/handler_test.go:27 +0x307
testing.tRunner(0xc00010e100, 0x13ce2a0)
/usr/local/Cellar/go/1.13.3/libexec/src/testing/testing.go:909 +0xc9
created by testing.(*T).Run
/usr/local/Cellar/go/1.13.3/libexec/src/testing/testing.go:960 +0x350
exit status 2
Working code to debug
handler.go
package handler
import (
"net/http"
"github.com/labstack/echo"
)
type (
User struct {
Name string `json:"name" form:"name"`
Email string `json:"email" form:"email"`
}
handler struct {
db map[string]*User
}
)
func (h *handler) getUser(c echo.Context) error {
email := c.Param("email")
user := h.db[email]
if user == nil {
return echo.NewHTTPError(http.StatusNotFound, "user not found")
}
return c.JSON(http.StatusOK, user)
}
handler_test.go:
package handler
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/labstack/echo"
"github.com/stretchr/testify/assert"
)
var (
mockDB = map[string]*User{
"[email protected]": &User{"Jon Snow", "[email protected]"},
}
userJSON = `{"name":"Jon Snow","email":"[email protected]"}`
)
func TestGetUser(t *testing.T) {
// Setup
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
c.SetPath("/users/:email")
c.SetParamNames("email")
c.SetParamValues("[email protected]")
h := &handler{mockDB}
// Assertions
if assert.NoError(t, h.getUser(c)) {
assert.Equal(t, http.StatusOK, rec.Code)
assert.Equal(t, userJSON, rec.Body.String())
}
}