|
| 1 | +package readline |
| 2 | + |
| 3 | +import ( |
| 4 | + "strings" |
| 5 | + "testing" |
| 6 | +) |
| 7 | + |
| 8 | +// TestCommandCompletionRecoversFromPanic ensures a panic in the |
| 9 | +// application-provided completer is recovered and surfaced as a completion |
| 10 | +// message instead of propagating and crashing the shell. readline calls the |
| 11 | +// completer on nearly every keystroke, so a single bad completer or transient |
| 12 | +// state must not take down the process. |
| 13 | +func TestCommandCompletionRecoversFromPanic(t *testing.T) { |
| 14 | + rl := NewShell() |
| 15 | + rl.Completer = func([]rune, int) Completions { |
| 16 | + panic("boom") |
| 17 | + } |
| 18 | + |
| 19 | + defer func() { |
| 20 | + if r := recover(); r != nil { |
| 21 | + t.Fatalf("commandCompletion did not recover, panicked with: %v", r) |
| 22 | + } |
| 23 | + }() |
| 24 | + |
| 25 | + values := rl.commandCompletion() |
| 26 | + |
| 27 | + if values.Messages.IsEmpty() { |
| 28 | + t.Fatal("recovered completion produced no message, want a completion error message") |
| 29 | + } |
| 30 | + |
| 31 | + var found bool |
| 32 | + for _, msg := range values.Messages.Get() { |
| 33 | + if strings.Contains(msg, "completion error") && strings.Contains(msg, "boom") { |
| 34 | + found = true |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + if !found { |
| 39 | + t.Fatalf("recovered messages = %v, want one containing the panic value", values.Messages.Get()) |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +// TestCommandCompletionNilCompleter verifies the no-completer case stays a clean |
| 44 | +// no-op (empty values, no message). |
| 45 | +func TestCommandCompletionNilCompleter(t *testing.T) { |
| 46 | + rl := NewShell() |
| 47 | + rl.Completer = nil |
| 48 | + |
| 49 | + values := rl.commandCompletion() |
| 50 | + |
| 51 | + if !values.Messages.IsEmpty() { |
| 52 | + t.Fatalf("nil completer produced messages %v, want none", values.Messages.Get()) |
| 53 | + } |
| 54 | +} |
0 commit comments