Core functionality for new aiterp.net servers
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
1.6 KiB

package wrouter
import (
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"git.aiterp.net/gisle/wrouter/auth"
)
type testRoute struct {
Name string
}
func (tr *testRoute) Handle(path string, w http.ResponseWriter, req *http.Request, user *auth.User) bool {
w.WriteHeader(200)
w.Write([]byte(tr.Name))
return true
}
func TestPaths(t *testing.T) {
tr1 := testRoute{"Test Route 1"}
tr2 := testRoute{"Test Route 2"}
router := Router{}
router.Route("/test1", &tr1)
router.Route("/test2", &tr2)
t.Run("It finds /test1", func(t *testing.T) {
req := httptest.NewRequest("GET", "http://test.aiterp.net/test1", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
data, _ := ioutil.ReadAll(w.Body)
if string(data) != "Test Route 1" {
t.Error("Wrong content:", string(data))
t.Fail()
}
if w.Code != 200 {
t.Error("Wrong code:", w.Code)
t.Fail()
}
})
t.Run("It finds /test2", func(t *testing.T) {
req := httptest.NewRequest("GET", "http://test.aiterp.net/test2", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
data, _ := ioutil.ReadAll(w.Body)
if string(data) != "Test Route 2" {
t.Error("Wrong content:", string(data))
t.Fail()
}
if w.Header().Get("X-Route-Index") != "1" {
t.Error("Wrong index:", w.Code)
t.Fail()
}
if w.Code != 200 {
t.Error("Wrong code:", w.Code)
t.Fail()
}
})
t.Run("It does not find /test3", func(t *testing.T) {
req := httptest.NewRequest("GET", "http://test.aiterp.net/test3", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != 404 {
t.Error("Wrong code:", w.Code)
t.Fail()
}
})
}