-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecovery_test.go
More file actions
79 lines (66 loc) · 1.93 KB
/
Copy pathrecovery_test.go
File metadata and controls
79 lines (66 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package lane
import (
"context"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"testing"
"time"
)
func TestGo_NoPanic(t *testing.T) {
log := slog.New(slog.NewTextHandler(os.Stderr, nil))
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
done := make(chan struct{})
Go(ctx, log, "test-goroutine", cancel, func(ctx context.Context) {
defer close(done)
})
<-done
// cancel should NOT have been called by the runtime (no panic)
select {
case <-ctx.Done():
t.Fatal("context was cancelled without a panic")
default:
}
}
func TestGo_PanicCancelsContext(t *testing.T) {
log := slog.New(slog.NewTextHandler(os.Stderr, nil))
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
Go(ctx, log, "panicking-goroutine", cancel, func(ctx context.Context) {
defer close(done)
panic("test panic")
})
<-done
// recoverPanic calls cancel() after fn returns — wait with a short timeout.
select {
case <-ctx.Done():
case <-time.After(100 * time.Millisecond):
t.Fatal("context was not cancelled after panic")
}
}
func TestRecoverMiddleware_NoPanic(t *testing.T) {
log := slog.New(slog.NewTextHandler(os.Stderr, nil))
handler := RecoverMiddleware(log)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", rec.Code)
}
}
func TestRecoverMiddleware_Panic(t *testing.T) {
log := slog.New(slog.NewTextHandler(os.Stderr, nil))
handler := RecoverMiddleware(log)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
panic("handler panic")
}))
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/", nil)
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusInternalServerError {
t.Fatalf("expected 500, got %d", rec.Code)
}
}