Kong / go-pdk

Write Kong plugins in Go! 🦍
https://pkg.go.dev/github.com/Kong/go-pdk
Apache License 2.0
146 stars 50 forks source link

panic: `kong.Request.GetQueryArg` using test module #117

Closed cakemanny closed 6 months ago

cakemanny commented 2 years ago

Hiya, we get a panic when trying to test a plugin that looks for a request parameter that is not always provided. i.e.

~/src/tmp/go-pdk-bug % go test -v .
=== RUN   TestPlugin
    test.go:579: Access
panic: runtime error: index out of range [0] with length 0

goroutine 35 [running]:
github.com/Kong/go-pdk/test.(*TestEnv).Handle(0x140002dc000, {0x1400029e220, 0x1a}, {0x140001260b0, 0x5, 0x5})
    /Users/daniel/.gopath/pkg/mod/github.com/!kong/go-pdk@v0.8.0/test/test.go:365 +0x3518
github.com/Kong/go-pdk/bridge/bridgetest.MockFunc.func1()
    /Users/daniel/.gopath/pkg/mod/github.com/!kong/go-pdk@v0.8.0/bridge/bridgetest/bridgetest.go:133 +0x9c
created by github.com/Kong/go-pdk/bridge/bridgetest.MockFunc
    /Users/daniel/.gopath/pkg/mod/github.com/!kong/go-pdk@v0.8.0/bridge/bridgetest/bridgetest.go:118 +0xb0
FAIL    plugintest  0.166s
FAIL
// main.go
package main

import (
    "log"

    "github.com/Kong/go-pdk"
    "github.com/Kong/go-pdk/server"
)

func main() {
    server.StartServer(New, Version, Priority)
}

var Version = "0.0.1"
var Priority = 1

type Config struct{}

func New() interface{} {
    return &Config{}
}

func (conf Config) Access(kong *pdk.PDK) {
    argValue, err := kong.Request.GetQueryArg("foo")
    if err != nil {
        log.Printf("Error getting query arg: %s", err.Error())
    }
    log.Printf("argValue: %v", argValue)
}
// main_test.go
package main

import (
    "testing"

    "github.com/Kong/go-pdk/test"
    "github.com/stretchr/testify/assert"
)

func TestPlugin(t *testing.T) {
    env, err := test.New(t, test.Request{
        Method: "GET",
        Url:    "http://example.com?bar=baz",
    })
    if assert.NoError(t, err) {
        env.DoHttps(&Config{})
        assert.Equal(t, 200, env.ClientRes.Status)
    }
}
// go.mod
module plugintest

go 1.18

require (
    github.com/Kong/go-pdk v0.8.0
    github.com/stretchr/testify v1.8.0
)

require (
    github.com/davecgh/go-spew v1.1.1 // indirect
    github.com/pmezard/go-difflib v1.0.0 // indirect
    github.com/ugorji/go/codec v1.2.1 // indirect
    google.golang.org/protobuf v1.25.0 // indirect
    gopkg.in/yaml.v3 v3.0.1 // indirect
)
StarlightIbuki commented 7 months ago

It should be located here now: https://github.com/Kong/go-pdk/blob/810d3e39be90bc81b39fc876f0bc49bef1bbc405/test/test.go#L400 and it should be easy to fix. Internally tracked: KAG-3790

gszr commented 6 months ago

Hey @cakemanny, thanks for the report. I have opened https://github.com/Kong/go-pdk/pull/192 fixing this issue.