From fcf545c27c70fb795a631a42738c486c07092e83 Mon Sep 17 00:00:00 2001 From: tjpcc Date: Tue, 14 Feb 2023 20:10:57 -0700 Subject: Router improvements. - test coverage for Router, not just PathTree - Router.Mount() now flattens routes into the parent router - Router.Use() implemented to set middleware on a router itself --- router_test.go | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 router_test.go (limited to 'router_test.go') diff --git a/router_test.go b/router_test.go new file mode 100644 index 0000000..6f9c915 --- /dev/null +++ b/router_test.go @@ -0,0 +1,80 @@ +package gus_test + +import ( + "bytes" + "context" + "io" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "tildegit.org/tjp/gus" + "tildegit.org/tjp/gus/gemini" +) + +func h1(_ context.Context, _ *gus.Request) *gus.Response { + return gemini.Success("", &bytes.Buffer{}) +} + +func mw1(h gus.Handler) gus.Handler { + return func(ctx context.Context, req *gus.Request) *gus.Response { + resp := h(ctx, req) + resp.Body = io.MultiReader(resp.Body, bytes.NewBufferString("\nmiddleware 1")) + return resp + } +} + +func mw2(h gus.Handler) gus.Handler { + return func(ctx context.Context, req *gus.Request) *gus.Response { + resp := h(ctx, req) + resp.Body = io.MultiReader(resp.Body, bytes.NewBufferString("\nmiddleware 2")) + return resp + } +} + +func TestRouterUse(t *testing.T) { + r := &gus.Router{} + r.Use(mw1) + r.Use(mw2) + r.Route("/", h1) + + request, err := gemini.ParseRequest(bytes.NewBufferString("/\r\n")) + require.Nil(t, err) + + response := r.Handler(context.Background(), request) + require.NotNil(t, response) + + body, err := io.ReadAll(response.Body) + require.Nil(t, err) + + assert.Equal(t, "\nmiddleware 2\nmiddleware 1", string(body)) +} + +func TestRouterMount(t *testing.T) { + outer := &gus.Router{} + outer.Use(mw2) + + inner := &gus.Router{} + inner.Use(mw1) + inner.Route("/bar", h1) + + outer.Mount("/foo", inner) + + request, err := gemini.ParseRequest(bytes.NewBufferString("/foo/bar\r\n")) + require.Nil(t, err) + + response := outer.Handler(context.Background(), request) + require.NotNil(t, response) + + body, err := io.ReadAll(response.Body) + require.Nil(t, err) + + assert.Equal(t, "\nmiddleware 1\nmiddleware 2", string(body)) + + request, err = gemini.ParseRequest(bytes.NewBufferString("/foo\r\n")) + require.Nil(t, err) + + response = outer.Handler(context.Background(), request) + require.Nil(t, response) +} -- cgit v1.2.3