|
| 1 | +package debug_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "testing" |
| 6 | + "time" |
| 7 | + |
| 8 | + "github.com/trebent/kerberos/internal/composer/debug" |
| 9 | +) |
| 10 | + |
| 11 | +func TestGetDebugger_defaultIsNoop(t *testing.T) { |
| 12 | + d := debug.GetDebugger() |
| 13 | + if d == nil { |
| 14 | + t.Fatal("expected non-nil Debugger") |
| 15 | + } |
| 16 | + |
| 17 | + // The default noop debugger must not panic. |
| 18 | + action := d.StartAction(context.Background(), "test-component") |
| 19 | + if action == nil { |
| 20 | + t.Fatal("expected non-nil Action") |
| 21 | + } |
| 22 | + |
| 23 | + action.End(debug.Outcome{StatusCode: 200, Duration: time.Millisecond}) |
| 24 | +} |
| 25 | + |
| 26 | +func TestSetDebugger_replacesGlobal(t *testing.T) { |
| 27 | + original := debug.GetDebugger() |
| 28 | + t.Cleanup(func() { debug.SetDebugger(original) }) |
| 29 | + |
| 30 | + called := false |
| 31 | + debug.SetDebugger(&spyDebugger{onStartAction: func() { called = true }}) |
| 32 | + |
| 33 | + debug.GetDebugger().StartAction(context.Background(), "component"). |
| 34 | + End(debug.Outcome{StatusCode: 200}) |
| 35 | + |
| 36 | + if !called { |
| 37 | + t.Fatal("expected custom debugger to be called") |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +func TestSetDebugger_nilNoPanic(t *testing.T) { |
| 42 | + original := debug.GetDebugger() |
| 43 | + t.Cleanup(func() { debug.SetDebugger(original) }) |
| 44 | + |
| 45 | + // Setting a nil Debugger should not panic; retrieving and calling it may |
| 46 | + // panic depending on usage, but the set operation itself must be safe. |
| 47 | + debug.SetDebugger(nil) |
| 48 | +} |
| 49 | + |
| 50 | +// spyDebugger is a test helper that records StartAction calls. |
| 51 | +type spyDebugger struct { |
| 52 | + onStartAction func() |
| 53 | +} |
| 54 | + |
| 55 | +func (s *spyDebugger) StartAction(_ context.Context, _ string) debug.Action { |
| 56 | + if s.onStartAction != nil { |
| 57 | + s.onStartAction() |
| 58 | + } |
| 59 | + return &spyAction{} |
| 60 | +} |
| 61 | + |
| 62 | +type spyAction struct{} |
| 63 | + |
| 64 | +func (s *spyAction) End(_ debug.Outcome) {} |
| 65 | + |
| 66 | +// BenchmarkNoopDebugger verifies that the noop path causes zero heap allocations. |
| 67 | +func BenchmarkNoopDebugger(b *testing.B) { |
| 68 | + ctx := context.Background() |
| 69 | + b.ReportAllocs() |
| 70 | + for b.Loop() { |
| 71 | + action := debug.GetDebugger().StartAction(ctx, "test-component") |
| 72 | + action.End(debug.Outcome{StatusCode: 200, Duration: time.Millisecond}) |
| 73 | + } |
| 74 | +} |
0 commit comments