diff options
author | tjpcc <tjp@ctrl-c.club> | 2023-02-14 20:10:57 -0700 |
---|---|---|
committer | tjpcc <tjp@ctrl-c.club> | 2023-02-14 20:13:25 -0700 |
commit | fcf545c27c70fb795a631a42738c486c07092e83 (patch) | |
tree | f533c819c8f4a382f796235b739f8fece0313588 /router_test.go | |
parent | 18d69173b4e23a2edd8c07c35f7a5b927587e6d7 (diff) |
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
Diffstat (limited to 'router_test.go')
-rw-r--r-- | router_test.go | 80 |
1 files changed, 80 insertions, 0 deletions
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) +} |