gohttp/server/middleware_test.go

87 lines
1.9 KiB
Go
Raw Normal View History

2023-12-12 22:58:30 +08:00
package server
import (
"container/list"
"net/http"
"testing"
)
func TestNewMiddlewareLink(t *testing.T) {
ml := NewMiddlewareLink()
if ml == nil {
t.Errorf("NewMiddlewareLink() = nil, want %T", &MiddlewareLink{list.New()})
}
if ml.Len() == 0 {
t.Errorf("NewMiddlewareLink() returned list with length %d, want %d", 0, 1)
}
}
func TestMiddlewareLink_Add(t *testing.T) {
ml := NewMiddlewareLink()
element := Done
if ml.Len() != 1 {
t.Errorf("Add() did not add element to the list, length = %d, want %d", ml.Len(), 1)
}
ml.Add(element)
if ml.Len() != 1 {
t.Error("Should not Add Done twice")
}
t1 := ml.ServeHTTP(nil, nil)
if !t1 {
t.Error("ServeHTTP() returned false, want true")
}
B := func(w http.ResponseWriter, r *http.Request, next func()) {
}
ml.Add(B)
if ml.Len() != 2 {
t.Error("Should has 2 middleware but got 1")
}
t2 := ml.ServeHTTP(nil, nil)
if t2 {
t.Error("ServeHTTP() returned true, want false")
}
}
func TestNewRoute(t *testing.T) {
// 创建一个测试用的http.Handler
handleFn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
// 调用被测试的函数
route := NewRoute("GET", "/test", handleFn)
// 验证生成的route是否符合预期
if route.Method != "GET" {
t.Errorf("Expected method to be GET, got %s", route.Method)
}
if route.Path != "/test" {
t.Errorf("Expected path to be /test, got %s", route.Path)
}
if route.Handler == nil {
t.Error("Expected handler to be set")
}
if route.matcher == nil {
t.Error("Expected matcher to be set")
}
if route.middles == nil {
t.Error("Expected middles to be set")
}
route2 := NewRoute("GET", "/test2/:id", handleFn)
if route2.matcher.Params[0] != "id" {
t.Errorf("Expected param name to be id, got %s", route2.matcher.Params[0])
}
if route2.matcher.Reg == nil {
t.Error("Expected matcher.Reg to be set")
}
}