60 lines
1.4 KiB
Go
60 lines
1.4 KiB
Go
package handler_test
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/go-chi/chi/v5/middleware"
|
|
)
|
|
|
|
func TestRouterStripSlashes(t *testing.T) {
|
|
r := chi.NewRouter()
|
|
r.Use(middleware.StripSlashes)
|
|
|
|
r.Route("/api/v1", func(r chi.Router) {
|
|
r.Post("/auth/login", func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusOK)
|
|
w.Write([]byte(`{"code":200}`))
|
|
})
|
|
})
|
|
|
|
tests := []struct {
|
|
name string
|
|
method string
|
|
url string
|
|
expectedStatus int
|
|
}{
|
|
{
|
|
name: "Login without trailing slash",
|
|
method: "POST",
|
|
url: "/api/v1/auth/login",
|
|
expectedStatus: http.StatusOK,
|
|
},
|
|
{
|
|
name: "Login with trailing slash",
|
|
method: "POST",
|
|
url: "/api/v1/auth/login/",
|
|
expectedStatus: http.StatusOK,
|
|
},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
req, _ := http.NewRequest(tt.method, tt.url, nil)
|
|
rr := httptest.NewRecorder()
|
|
r.ServeHTTP(rr, req)
|
|
|
|
if rr.Code != tt.expectedStatus {
|
|
t.Errorf("expected status %v, got %v for %s", tt.expectedStatus, rr.Code, tt.url)
|
|
}
|
|
|
|
// Check if it redirected (it shouldn't with StripSlashes middleware correctly placed)
|
|
if rr.Code == http.StatusPermanentRedirect || rr.Code == http.StatusMovedPermanently {
|
|
t.Errorf("got redirect %v for %s", rr.Code, tt.url)
|
|
}
|
|
})
|
|
}
|
|
}
|