ev/pkg/mux/httpmux_test.go

105 lines
2.1 KiB
Go
Raw Normal View History

package mux_test
2022-09-07 16:00:10 -06:00
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/matryer/is"
"github.com/sour-is/ev/pkg/mux"
2022-09-07 16:00:10 -06:00
)
type mockHTTP struct {
2023-01-09 12:32:45 -07:00
onServeHTTP func()
onServeAPIv1 func()
onServeWellKnown func()
2022-09-07 16:00:10 -06:00
}
2023-01-09 12:32:45 -07:00
func (*mockHTTP) ServeFn(fn func()) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) { fn() }
2022-09-07 16:00:10 -06:00
}
func (h *mockHTTP) RegisterHTTP(mux *http.ServeMux) {
2023-01-09 12:32:45 -07:00
mux.HandleFunc("/", h.ServeFn(h.onServeHTTP))
2022-09-07 16:00:10 -06:00
}
func (h *mockHTTP) RegisterAPIv1(mux *http.ServeMux) {
2023-01-09 12:32:45 -07:00
mux.HandleFunc("/ping", h.ServeFn(h.onServeAPIv1))
}
func (h *mockHTTP) RegisterWellKnown(mux *http.ServeMux) {
mux.HandleFunc("/echo", h.ServeFn(h.onServeWellKnown))
2022-09-07 16:00:10 -06:00
}
2023-01-09 12:32:45 -07:00
func TestHttp(t *testing.T) {
2022-09-07 16:00:10 -06:00
is := is.New(t)
called := false
2023-01-09 12:32:45 -07:00
calledAPIv1 := false
calledWellKnown := false
2022-09-07 16:00:10 -06:00
mux := mux.New()
2023-01-09 12:32:45 -07:00
mux.Add(&mockHTTP{
func() { called = true },
func() { calledAPIv1 = true },
func() { calledWellKnown = true },
})
2022-09-07 16:00:10 -06:00
is.True(mux != nil)
w := httptest.NewRecorder()
2023-01-09 12:32:45 -07:00
r := httptest.NewRequest(http.MethodGet, "/", nil)
2022-09-07 16:00:10 -06:00
mux.ServeHTTP(w, r)
is.True(called)
2023-01-09 12:32:45 -07:00
is.True(!calledAPIv1)
is.True(!calledWellKnown)
}
func TestHttpAPIv1(t *testing.T) {
is := is.New(t)
called := false
calledAPIv1 := false
calledWellKnown := false
mux := mux.New()
mux.Add(&mockHTTP{
func() { called = true },
func() { calledAPIv1 = true },
func() { calledWellKnown = true },
})
is.True(mux != nil)
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/api/v1/ping", nil)
mux.ServeHTTP(w, r)
is.True(!called)
is.True(calledAPIv1)
is.True(!calledWellKnown)
}
func TestHttpWellKnown(t *testing.T) {
is := is.New(t)
called := false
calledAPIv1 := false
calledWellKnown := false
mux := mux.New()
mux.Add(&mockHTTP{
func() { called = true },
func() { calledAPIv1 = true },
func() { calledWellKnown = true },
})
is.True(mux != nil)
w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/.well-known/echo", nil)
mux.ServeHTTP(w, r)
is.True(!called)
is.True(!calledAPIv1)
is.True(calledWellKnown)
2022-09-07 16:00:10 -06:00
}