Skip to content

Commit

Permalink
🩹 Fix: Server but not shut down properly
Browse files Browse the repository at this point in the history
  • Loading branch information
JIeJaitt committed Feb 14, 2025
1 parent ebdccd0 commit 0860595
Showing 1 changed file with 28 additions and 28 deletions.
56 changes: 28 additions & 28 deletions hooks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}{
Expand All @@ -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) {
Expand Down

0 comments on commit 0860595

Please sign in to comment.