Skip to content

Commit

Permalink
test: add test for fallback handler calling
Browse files Browse the repository at this point in the history
  • Loading branch information
ydylla committed Aug 5, 2024
1 parent d110e3e commit 154bf6f
Showing 1 changed file with 63 additions and 1 deletion.
64 changes: 63 additions & 1 deletion layer4/routes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -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")
}
}

0 comments on commit 154bf6f

Please sign in to comment.