Skip to content

Commit

Permalink
Improve exception if a (multi)selection prompt is used incorrectly
Browse files Browse the repository at this point in the history
Before this commit, the selection prompt would throw an `InvalidOperationException` (Sequence contains no elements) and the multi selection prompt would throw an `ArgumentOutOfRangeException` (Index was out of range. Must be non-negative and less than the size of the collection.)

Both would occur because the prompts were never meant to be empty.
  • Loading branch information
0xced authored and patriksvensson committed Sep 11, 2024
1 parent b470af1 commit c70a8b8
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/Spectre.Console/Prompts/List/ListPrompt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ public async Task<ListPromptState<T>> Show(
}

var nodes = tree.Traverse().ToList();
if (nodes.Count == 0)
{
throw new InvalidOperationException("Cannot show an empty selection prompt. Please call the AddChoice() method to configure the prompt.");
}

var state = new ListPromptState<T>(nodes, converter, _strategy.CalculatePageSize(_console, nodes.Count, requestedPageSize), wrapAround, selectionMode, skipUnselectableItems, searchEnabled);
var hook = new ListPromptRenderHook<T>(_console, () => BuildRenderable(state));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,23 @@ public void Should_Throw_When_Getting_Parents_Of_Non_Existing_Node()
// Then
action.ShouldThrow<ArgumentOutOfRangeException>();
}

[Fact] public void Should_Throw_Meaningful_Exception_For_Empty_Prompt()
{
// Given
var console = new TestConsole();
console.Profile.Capabilities.Interactive = true;
console.Input.PushKey(ConsoleKey.Spacebar);

var prompt = new MultiSelectionPrompt<string>();

// When
Action action = () => prompt.Show(console);

// Then
var exception = action.ShouldThrow<InvalidOperationException>();
exception.Message.ShouldBe("Cannot show an empty selection prompt. Please call the AddChoice() method to configure the prompt.");
}
}

file sealed class CustomItem
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,22 @@ public void Should_Search_In_Remapped_Result()
// Then
selection.ShouldBe(choices[1]);
}

[Fact] public void Should_Throw_Meaningful_Exception_For_Empty_Prompt()
{
// Given
var console = new TestConsole();
console.Profile.Capabilities.Interactive = true;

var prompt = new SelectionPrompt<string>();

// When
Action action = () => prompt.Show(console);

// Then
var exception = action.ShouldThrow<InvalidOperationException>();
exception.Message.ShouldBe("Cannot show an empty selection prompt. Please call the AddChoice() method to configure the prompt.");
}
}

file sealed class CustomSelectionItem
Expand Down

0 comments on commit c70a8b8

Please sign in to comment.