Fix internal handlers ServiceBuilder composition

This commit is contained in:
Julien Salleyron 2024-11-19 14:52:04 +01:00 committed by GitHub
parent 8ffd1854db
commit cc80568d9e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 80 additions and 27 deletions

View file

@ -18,9 +18,9 @@ import (
"github.com/traefik/traefik/v2/pkg/testhelpers"
)
type MockForwarder struct{}
type mockForwarder struct{}
func (MockForwarder) ServeHTTP(http.ResponseWriter, *http.Request) {
func (mockForwarder) ServeHTTP(http.ResponseWriter, *http.Request) {
panic("implement me")
}
@ -44,14 +44,14 @@ func TestGetLoadBalancer(t *testing.T) {
},
},
},
fwd: &MockForwarder{},
fwd: &mockForwarder{},
expectError: true,
},
{
desc: "Succeeds when there are no servers",
serviceName: "test",
service: &dynamic.ServersLoadBalancer{},
fwd: &MockForwarder{},
fwd: &mockForwarder{},
expectError: false,
},
{
@ -60,7 +60,7 @@ func TestGetLoadBalancer(t *testing.T) {
service: &dynamic.ServersLoadBalancer{
Sticky: &dynamic.Sticky{Cookie: &dynamic.Cookie{}},
},
fwd: &MockForwarder{},
fwd: &mockForwarder{},
expectError: false,
},
}
@ -476,6 +476,48 @@ func Test1xxResponses(t *testing.T) {
}
}
type serviceBuilderFunc func(ctx context.Context, serviceName string) (http.Handler, error)
func (s serviceBuilderFunc) BuildHTTP(ctx context.Context, serviceName string) (http.Handler, error) {
return s(ctx, serviceName)
}
type internalHandler struct{}
func (internalHandler) ServeHTTP(_ http.ResponseWriter, _ *http.Request) {}
func TestManager_ServiceBuilders(t *testing.T) {
var internalHandler internalHandler
manager := NewManager(map[string]*runtime.ServiceInfo{
"test@test": {
Service: &dynamic.Service{
LoadBalancer: &dynamic.ServersLoadBalancer{},
},
},
}, nil, nil, &RoundTripperManager{
roundTrippers: map[string]http.RoundTripper{
"default@internal": http.DefaultTransport,
},
}, serviceBuilderFunc(func(rootCtx context.Context, serviceName string) (http.Handler, error) {
if strings.HasSuffix(serviceName, "@internal") {
return internalHandler, nil
}
return nil, nil
}))
h, err := manager.BuildHTTP(context.Background(), "test@internal")
require.NoError(t, err)
assert.Equal(t, internalHandler, h)
h, err = manager.BuildHTTP(context.Background(), "test@test")
require.NoError(t, err)
assert.NotNil(t, h)
_, err = manager.BuildHTTP(context.Background(), "wrong@test")
assert.Error(t, err)
}
func TestManager_Build(t *testing.T) {
testCases := []struct {
desc string