router/tree_test.go

138 lines
2.9 KiB
Go
Executable File

package router
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
var nilHandle = func(w http.ResponseWriter, r *http.Request) {}
func TestNewTree(t *testing.T) {
newTree()
}
func TestTreeInsert(t *testing.T) {
tree := newTree()
if err := tree.Insert("/hello/world", nilHandle); err != nil {
t.Errorf("failed to insert first path: %v", err)
}
if err := tree.Insert("/hello/world", nilHandle); err == nil {
t.Errorf("succeeded to insert dupe path: %v", err)
}
if err := tree.Insert("/hello/", nilHandle); err != nil {
t.Errorf("failed to insert sub path: %v", err)
}
if err := tree.Insert("/world/", nilHandle); err != nil {
t.Errorf("failed to insert new path: %v", err)
}
}
func TestTreeLookup(t *testing.T) {
tree := newTree()
subtree := newTree()
checked := false
subtree.handler = func(w http.ResponseWriter, r *http.Request) {
checked = true
}
tree.next["hi"] = subtree
foo := tree.Lookup("/hi/")
if foo == nil {
t.Errorf("cannot lookup path: %v", "/hi/")
} else {
foo(nil, nil)
}
if !checked {
t.Errorf("lookup returned wrong function")
}
}
func TestTreeInsertLookup(t *testing.T) {
tree := newTree()
checked := false
foo := func(_ http.ResponseWriter, _ *http.Request) {
checked = true
}
paths := []string{
"/hello",
"/hello/world",
"/world",
}
for _, p := range paths {
if err := tree.Insert(p, foo); err != nil {
t.Fatalf("cannot insert: %v", err)
}
}
for _, p := range paths {
if bar := tree.Lookup(p[1:] + "/"); bar == nil {
t.Fatalf("cannot lookup: %v", p)
} else {
checked = false
bar(nil, nil)
if !checked {
t.Errorf("failed to call %v: %v", p, checked)
}
}
}
}
func TestTreeWildcardSubstr(t *testing.T) {
tree := newTree()
foo := func(w http.ResponseWriter, r *http.Request) {
}
if err := tree.Insert("/prefix-"+Wildcard, foo); err != nil {
t.Fatal(err)
}
if foo := tree.Lookup("/prefix-suffix"); foo == nil {
t.Error(foo)
}
}
func TestTreeWildcard(t *testing.T) {
tree := newTree()
checked := false
foo := func(w http.ResponseWriter, r *http.Request) {
checked = true
fmt.Fprintf(w, "%v", r.Header[WildcardHeader])
}
paths := []string{
"/hello/{}",
"/hello/{}/{}/world",
}
for _, p := range paths {
if err := tree.Insert(p, foo); err != nil {
t.Fatalf("cannot insert: %v", err)
}
}
for _, p := range paths {
dpath := strings.Replace(p, "{}", "seq", -1)
if bar := tree.Lookup(dpath[1:] + "/"); bar == nil {
t.Fatalf("cannot lookup: %v", p)
} else {
checked = false
w := httptest.NewRecorder()
r, _ := http.NewRequest("GET", dpath, nil)
bar(w, r)
if !checked {
t.Errorf("failed to call %v: %v", p, checked)
}
b, err := ioutil.ReadAll(w.Body)
if err != nil {
t.Errorf("failed to read all: %v", err)
}
if strings.Count(string(b), "seq") != strings.Count(p, "{}") {
t.Errorf("failed to decode wildcards: %s", b)
}
}
}
}