Unit testing for functions that use gorilla/mux URL parameters
Trouble is, even when you use 0
as value to set context values, it is not same value that mux.Vars()
reads. mux.Vars()
is using varsKey
(as you already saw) which is of type contextKey
and not int
.
Sure, contextKey
is defined as:
type contextKey int
which means that it has int as underlying object, but type plays part when comparing values in go, so int(0) != contextKey(0)
.
I do not see how you could trick gorilla mux or context into returning your values.
That being said, couple of ways to test this comes to mind (note that code below is untested, I have typed it directly here, so there might be some stupid errors):
- As somebody suggested, run a server and send HTTP requests to it.
Instead of running server, just use gorilla mux Router in your tests. In this scenario, you would have one router that you pass to
ListenAndServe
, but you could also use that same router instance in tests and callServeHTTP
on it. Router would take care of setting context values and they would be available in your handlers.func Router() *mux.Router { r := mux.Router() r.HandleFunc("/employees/{1}", GetRequest) (...) return r }
somewhere in main function you would do something like this:
http.Handle("/", Router())
and in your tests you can do:
func TestGetRequest(t *testing.T) { r := http.NewRequest("GET", "employees/1", nil) w := httptest.NewRecorder() Router().ServeHTTP(w, r) // assertions }
Wrap your handlers so that they accept URL parameters as third argument and wrapper should call
mux.Vars()
and pass URL parameters to handler.With this solution, your handlers would have signature:
type VarsHandler func (w http.ResponseWriter, r *http.Request, vars map[string]string)
and you would have to adapt calls to it to conform to
http.Handler
interface:func (vh VarsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) vh(w, r, vars) }
To register handler you would use:
func GetRequest(w http.ResponseWriter, r *http.Request, vars map[string]string) { // process request using vars } mainRouter := mux.NewRouter().StrictSlash(true) mainRouter.HandleFunc("/test/{mystring}", VarsHandler(GetRequest)).Name("/test/{mystring}").Methods("GET")
Which one you use is matter of personal preference. Personally, I would probably go with option 2 or 3, with slight preference towards 3.
In golang, I have slightly different approach to testing.
I slightly rewrite your lib code:
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func main() {
startServer()
}
func startServer() {
mainRouter := mux.NewRouter().StrictSlash(true)
mainRouter.HandleFunc("/test/{mystring}", GetRequest).Name("/test/{mystring}").Methods("GET")
http.Handle("/", mainRouter)
err := http.ListenAndServe(":8080", mainRouter)
if err != nil {
fmt.Println("Something is wrong : " + err.Error())
}
}
func GetRequest(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
myString := vars["mystring"]
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte(myString))
}
And here is test for it:
package main
import (
"io/ioutil"
"net/http"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestGetRequest(t *testing.T) {
go startServer()
client := &http.Client{
Timeout: 1 * time.Second,
}
r, _ := http.NewRequest("GET", "http://localhost:8080/test/abcd", nil)
resp, err := client.Do(r)
if err != nil {
panic(err)
}
assert.Equal(t, http.StatusOK, resp.StatusCode)
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
assert.Equal(t, []byte("abcd"), body)
}
I think this is a better approach - you are really testing what you wrote since its very easy to start/stop listeners in go!
gorilla/mux
provides the SetURLVars
function for testing purposes, which you can use to inject your mock vars
.
func TestGetRequest(t *testing.T) {
t.Parallel()
r, _ := http.NewRequest("GET", "/test/abcd", nil)
w := httptest.NewRecorder()
//Hack to try to fake gorilla/mux vars
vars := map[string]string{
"mystring": "abcd",
}
// CHANGE THIS LINE!!!
r = mux.SetURLVars(r, vars)
GetRequest(w, r)
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, []byte("abcd"), w.Body.Bytes())
}