diff --git a/hooks_test.go b/hooks_test.go index d35b02e6c5..5c14b85f2a 100644 --- a/hooks_test.go +++ b/hooks_test.go @@ -208,14 +208,14 @@ func Test_Hook_OnPostShutdown(t *testing.T) { wg.Add(1) // Use channels to synchronize and pass results - hookResult := make(chan struct { + hookCalled := make(chan struct { err error called bool - }, 1) // Buffer size of 1 prevents deadlock - defer close(hookResult) + }, 1) + defer close(hookCalled) app.Hooks().OnPostShutdown(func(err error) error { - hookResult <- struct { + hookCalled <- struct { err error called bool }{ @@ -225,42 +225,42 @@ func Test_Hook_OnPostShutdown(t *testing.T) { return nil }) - // Use channel to make sure the server is up - serverReady := make(chan struct{}) - defer close(serverReady) - + // Start server in goroutine go func() { defer wg.Done() - serverReady <- struct{}{} // Signal that the server is ready to start + // Ignore errors when shutting down the server if err := app.Listen(":0"); err != nil { - t.Errorf("Failed to start listener: %v", err) + if !errors.Is(err, errors.New("server closed")) { + t.Errorf("unexpected error: %v", err) + } } }() + // Wait a bit for the server to start + time.Sleep(100 * time.Millisecond) - <-serverReady // Wait for the server to be ready - - app.hooks.executeOnPostShutdownHooks(expectedErr) - - // Wait for the hook to finish executing and get the result - var result struct { - err error - called bool - } + // Trigger shutdown with our expected error + go app.hooks.executeOnPostShutdownHooks(expectedErr) + // Wait for hook to be called with timeout select { - case result = <-hookResult: - case <-time.After(5 * time.Second): - t.Fatal("Hook execution timeout") + case result := <-hookCalled: + if !result.called { + t.Error("hook was not called") + } + if !errors.Is(result.err, expectedErr) { + t.Errorf("hook received wrong error: want %v, got %v", expectedErr, result.err) + } + case <-time.After(3 * time.Second): + t.Fatal("hook execution timeout") } - if !result.called { - t.Fatal("hook was not called") + // Shutdown the server + if err := app.Shutdown(); err != nil { + t.Errorf("shutdown error: %v", err) } - if !errors.Is(result.err, expectedErr) { - t.Fatalf("hook received wrong error: want %v, got %v", expectedErr, result.err) - } - wg.Wait() // Ensure server goroutine completes + // Wait for server goroutine to complete + wg.Wait() }) t.Run("should execute multiple hooks in order", func(t *testing.T) {