Skip to content

Instantly share code, notes, and snippets.

@lateefj
Created January 4, 2014 02:40
Show Gist options
  • Save lateefj/8250794 to your computer and use it in GitHub Desktop.
Save lateefj/8250794 to your computer and use it in GitHub Desktop.
Name search handler test with Gorilla mux
package names
import (
"encoding/json"
"net/http"
"testing"
"github.com/gorilla/context"
"github.com/gorilla/mux"
"github.com/lateefj/mctest"
)
// setRequestVars ... This wrapper around setting request variables for garilla
func setRequestVars(r *mux.Router, req *http.Request) {
var match mux.RouteMatch
// Take the request and match it
r.Match(req, &match)
// Push the variable onto the context
context.Set(req, varsKey, match.Vars)
}
// Create a structure to hold a mock of the interface
type mockNameSearch struct {
Names *[]CensusName
Error error
}
// FindByName ... The only function in the interface
func (mns *mockNameSearch) FindByName(name string) (*[]CensusName, error) {
if mns.Error != nil {
return nil, mns.Error
}
return mns.Names, nil
}
func TestFindName(t *testing.T) {
// Create a mock test response
mockResp := mctest.NewMockTestResponse(t)
// Mock data initialization
names := []CensusName{CensusName{Year: 2011, Name: "Lateef", Sex: "M", Size: 11}}
// Fakes the name search interface
mns := &mockNameSearch{Names: &names, Error: nil}
// Create a new request
req, _ := http.NewRequest("GET", "http://lhj.me/n/name/Lateef", nil)
// Create a gorilla mux
r := mux.NewRouter()
// Initialize the rest service(s)
InitRest(r)
// Set the request variable based on the request url
setRequestVars(r, req)
// Could just do this if I didn't want to test the routing
//context.Set(req, varsKey, map[string]string{"name": "Lateef"})
// Call the actually web service handler
handleFindName(mns, mockResp, req)
// THe rest of this just confirms the responses we expect
if !mockResp.AssertCode(http.StatusOK) {
t.Fatalf("Should have been 200 however got %d", mockResp.StatusCode)
}
nr := &NameResponse{}
// Unmashal the json to a NameResponse
err := json.Unmarshal(mockResp.Bytes(), nr)
if err != nil {
t.Fatalf("Could not unmarshal expected error: %s", err)
}
if nr.Male[0].Year != 2011 {
t.Fatalf("Expected 2011 to be year but was %d", nr.Male[0].Year)
}
if nr.Male[0].Name != "Lateef" {
t.Fatalf("Expected Lateef to be name but was %s", nr.Male[0].Name)
}
// 500 example
mockResp = mctest.NewMockTestResponse(t)
req, _ = http.NewRequest("GET", "http://lhj.me/n/name/", nil)
setRequestVars(r, req)
handleFindName(mns, mockResp, req)
if !mockResp.AssertCode(http.StatusInternalServerError) {
t.Fatalf("This has no name in the url so should fail with 500 but was: %d", mockResp.StatusCode)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment