From 154bf6f4770acffca06417c2e3008046eea02ebf Mon Sep 17 00:00:00 2001 From: Yannick Dylla <17772145+ydylla@users.noreply.github.com> Date: Mon, 5 Aug 2024 23:56:07 +0200 Subject: [PATCH] test: add test for fallback handler calling --- layer4/routes_test.go | 64 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 63 insertions(+), 1 deletion(-) diff --git a/layer4/routes_test.go b/layer4/routes_test.go index 1db54c7..c2324a9 100644 --- a/layer4/routes_test.go +++ b/layer4/routes_test.go @@ -2,18 +2,20 @@ package layer4 import ( "context" + "encoding/json" "errors" "net" "testing" "time" "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/modules/caddyhttp" "go.uber.org/zap" "go.uber.org/zap/zapcore" "go.uber.org/zap/zaptest/observer" ) -func TestMatchingTimeoutWorks(t *testing.T) { +func TestCompiledRouteTimeoutWorks(t *testing.T) { ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) defer cancel() @@ -64,3 +66,63 @@ func TestMatchingTimeoutWorks(t *testing.T) { t.Fatal("handler was called but should not") } } + +type testFalseMatcher struct { +} + +func (testFalseMatcher) CaddyModule() caddy.ModuleInfo { + return caddy.ModuleInfo{ + ID: "layer4.matchers.testFalseMatcher", + New: func() caddy.Module { return new(testFalseMatcher) }, + } +} + +func (m *testFalseMatcher) Match(_ *Connection) (bool, error) { + return false, nil +} + +// See https://github.com/mholt/caddy-l4/pull/210 +func TestCompiledRouteCallsFallbackIfNothingMatches(t *testing.T) { + ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) + defer cancel() + + caddy.RegisterModule(testFalseMatcher{}) + + routes := RouteList{&Route{ + MatcherSetsRaw: caddyhttp.RawMatcherSets{ + caddy.ModuleMap{"testFalseMatcher": json.RawMessage("{}")}, // always false + }, + }} + + err := routes.Provision(ctx) + if err != nil { + t.Fatalf("provision failed | %s", err) + } + + fallbackWasCalled := false + compiledRoute := routes.Compile(zap.NewNop(), 5*time.Millisecond, + NextHandlerFunc(func(con *Connection, next Handler) error { + fallbackWasCalled = true + return nil + })) + + in, out := net.Pipe() + defer out.Close() + + cx := WrapConnection(out, []byte{}, zap.NewNop()) + defer cx.Close() + + go func() { + _, _ = in.Write([]byte("Hi")) + _ = in.Close() + }() + + err = compiledRoute.Handle(cx) + if err != nil { + t.Fatalf("handle failed | %s", err) + } + + if !fallbackWasCalled { + t.Fatal("fallback handler was not called") + } +}