102 lines
2.5 KiB
Go
Executable file
102 lines
2.5 KiB
Go
Executable file
package gohttprouter
|
|
|
|
import (
|
|
"net"
|
|
"net/http"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestRouterInvalidPath(t *testing.T) {
|
|
router := New()
|
|
if err := router.HandleFunc(http.MethodGet, "missing/slash", emptyHandlerFunction); err == nil {
|
|
t.Error("an error was expected during path parsing (missing slash)")
|
|
}
|
|
if err := router.HandleFunc(http.MethodGet, "/invalid/shash/", emptyHandlerFunction); err == nil {
|
|
t.Error("an error was expected during path parsing (ending slash)")
|
|
}
|
|
}
|
|
|
|
func TestRouterSamePath(t *testing.T) {
|
|
router := New()
|
|
Must(router.HandleFunc(http.MethodGet, "/user/:id/name", emptyHandlerFunction))
|
|
if err := router.HandleFunc(http.MethodGet, "/user/:name/name", emptyHandlerFunction); err == nil {
|
|
t.Error("missing exception; path was defined twice")
|
|
}
|
|
}
|
|
|
|
func TestRouterServer(t *testing.T) {
|
|
quitChan := make(chan bool, 2)
|
|
|
|
router := New()
|
|
router.HandleFunc(http.MethodGet, "/home", func(response http.ResponseWriter, request *http.Request, info RoutingInfo) {
|
|
quitChan <- true
|
|
})
|
|
listener, err := net.Listen("tcp", "localhost:8080")
|
|
if err != nil {
|
|
t.Error(err)
|
|
}
|
|
go http.Serve(listener, router)
|
|
|
|
// call method (not existing)
|
|
resp, err := http.Get("http://localhost:8080/home/test")
|
|
if err != nil {
|
|
t.Error(err)
|
|
}
|
|
if resp.StatusCode != http.StatusNotFound {
|
|
t.Error("server should return 404 but returned", resp.StatusCode)
|
|
}
|
|
|
|
// call method (POST not defined)
|
|
resp, err = http.Post("http://localhost:8080/home", "text/text", strings.NewReader("yea"))
|
|
if err != nil {
|
|
t.Error(err)
|
|
}
|
|
if resp.StatusCode != http.StatusNotFound {
|
|
t.Error("server should return 404 but returned", resp.StatusCode)
|
|
}
|
|
|
|
// call method
|
|
_, err = http.Get("http://localhost:8080/home")
|
|
if err != nil {
|
|
t.Error(err)
|
|
}
|
|
|
|
// wait for completion
|
|
<-quitChan
|
|
listener.Close()
|
|
}
|
|
|
|
func TestRouterServerHandler(t *testing.T) {
|
|
testHandler := TestHandler{CloseChannel: make(chan bool, 2)}
|
|
|
|
router := New()
|
|
router.Handle(http.MethodGet, "/", testHandler)
|
|
listener, err := net.Listen("tcp", "localhost:8081")
|
|
if err != nil {
|
|
t.Error(err)
|
|
}
|
|
go http.Serve(listener, router)
|
|
|
|
// call method
|
|
_, err = http.Get("http://localhost:8081/?test=false")
|
|
if err != nil {
|
|
t.Error(err)
|
|
}
|
|
|
|
// wait for completion
|
|
<-testHandler.CloseChannel
|
|
listener.Close()
|
|
}
|
|
|
|
func emptyHandlerFunction(response http.ResponseWriter, request *http.Request, routerInfo RoutingInfo) {
|
|
// it's fine
|
|
}
|
|
|
|
type TestHandler struct {
|
|
CloseChannel chan bool
|
|
}
|
|
|
|
func (t TestHandler) ServeHTTP(response http.ResponseWriter, request *http.Request, routerInfo RoutingInfo) {
|
|
t.CloseChannel <- true
|
|
}
|