fix: checker map mutation

This commit is contained in:
Florian Schade
2024-10-17 02:51:56 +02:00
parent 66ff86bd35
commit 331fc85da2
2 changed files with 9 additions and 5 deletions

View File

@@ -50,14 +50,16 @@ func (c CheckHandlerConfiguration) WithCheck(name string, check checker) CheckHa
c.logger.Panic().Str("check", name).Msg("check already exists")
}
c.checks = maps.Clone(c.checks) // prevent propagated check duplication, maps are references;
c.checks[name] = check
return c
}
// WithChecks adds multiple checks to the CheckHandlerConfiguration.
func (c CheckHandlerConfiguration) WithChecks(checks checkers) CheckHandlerConfiguration {
for name, check := range checks {
c.WithCheck(name, check)
c.checks = c.WithCheck(name, check).checks
}
return c

View File

@@ -21,13 +21,15 @@ func TestCheckHandlerConfiguration(t *testing.T) {
handlerConfiguration := handlers.NewCheckHandlerConfiguration().WithCheck("check-1", nopCheck)
t.Run("add check", func(t *testing.T) {
handlerConfiguration.WithCheck("check-2", nopCheck)
require.Equal(t, 2, len(handlers.NewCheckHandler(handlerConfiguration).Checks()))
inheritedHandlerConfiguration := handlerConfiguration.WithCheck("check-2", nopCheck)
require.Equal(t, 1, len(handlers.NewCheckHandler(handlerConfiguration).Checks()))
require.Equal(t, 2, len(handlers.NewCheckHandler(inheritedHandlerConfiguration).Checks()))
})
t.Run("add checks", func(t *testing.T) {
handlerConfiguration.WithChecks(map[string]func(ctx context.Context) error{"check-3": nopCheck, "check-4": nopCheck})
require.Equal(t, 4, len(handlers.NewCheckHandler(handlerConfiguration).Checks()))
inheritedHandlerConfiguration := handlerConfiguration.WithChecks(map[string]func(ctx context.Context) error{"check-2": nopCheck, "check-3": nopCheck})
require.Equal(t, 1, len(handlers.NewCheckHandler(handlerConfiguration).Checks()))
require.Equal(t, 3, len(handlers.NewCheckHandler(inheritedHandlerConfiguration).Checks()))
})
t.Run("checks are unique", func(t *testing.T) {