Files
summercms/surf/params_test.go
Jakub Zych 8e3bf266d8 feat(03-03): add typed path params and per-plugin rollback
Compile regex and enum constraints at route registration so malformed and unknown IDs share a 404, and named rollback errors isolate one plugin's history.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-17 20:19:59 +02:00

57 lines
1.3 KiB
Go

package surf
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestIntParamMalformedIsFalse(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/items/abc", nil)
req.SetPathValue("id", "abc")
if _, ok := IntParam(req, "id"); ok {
t.Fatal("malformed id must be false")
}
req.SetPathValue("id", "12")
n, ok := IntParam(req, "id")
if !ok || n != 12 {
t.Fatalf("got %d %t", n, ok)
}
req.SetPathValue("id", "0")
if _, ok := IntParam(req, "id"); ok {
t.Fatal("non-positive id must be false")
}
}
func TestRegexCompilesAtRegistration(t *testing.T) {
c, err := Regex("id", `[0-9]+`)
if err != nil {
t.Fatal(err)
}
if !c.match("12") || c.match("nope") || c.match("") {
t.Fatal("regex match")
}
if _, err := Regex("id", "["); err == nil {
t.Fatal("want invalid regex error")
}
if _, err := Regex("", `[0-9]+`); err == nil {
t.Fatal("want empty param error")
}
}
func TestEnumAllowListDoesNotBuildRegexFromValues(t *testing.T) {
c, err := Enum("kind", "widget", "gadget")
if err != nil {
t.Fatal(err)
}
if c.re != nil {
t.Fatal("enum must not compile a regex")
}
if !c.match("widget") || !c.match("gadget") || c.match("other") || c.match("widget|gadget") {
t.Fatal("enum match")
}
if _, err := Enum("kind"); err == nil {
t.Fatal("want empty enum error")
}
}