Skip to content

Commit

Permalink
Make Choice.shortcut_key property with setter
Browse files Browse the repository at this point in the history
Ensures that `Choice.auto_shortcut` is set to `False`
whenever `Choice.shortcut_key` is set to a `str` value
and vice versa. Add tests for fix.

Closes #340
  • Loading branch information
overhacked committed Jan 9, 2024
1 parent f246943 commit 40ef821
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
6 changes: 3 additions & 3 deletions questionary/prompts/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,12 +116,12 @@ def build(c: Union[str, "Choice", Dict[str, Any]]) -> "Choice":
)

@property
def shortcut_key() -> Optional[str]:
def shortcut_key(self) -> Optional[str]:
"""A shortcut key for the choice"""
return self.__shortcut_key

@shortcut_key.setter
def shortcut_key(key: Optional[Union[str, bool]]):
def shortcut_key(self, key: Optional[Union[str, bool]]):
if key is not None:
if isinstance(key, bool):
self.auto_shortcut = key
Expand All @@ -134,7 +134,7 @@ def shortcut_key(key: Optional[Union[str, bool]]):
self.auto_shortcut = True

@shortcut_key.deleter
def shortcut_key():
def shortcut_key(self):
self.__shortcut_key = None
self.auto_shortcut = True

Expand Down
25 changes: 25 additions & 0 deletions tests/prompts/test_select.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
# -*- coding: utf-8 -*-
from copy import copy

import pytest

from questionary import Choice
Expand Down Expand Up @@ -199,6 +201,29 @@ def test_allow_shortcut_key_with_True():
assert result == "bazz"


def test_auto_shortcut_key_stable_in_loop():
message = "Foo message"
choices = [
Choice("foo"),
Choice("bar"),
]
kwargs = {
"choices": choices,
"use_shortcuts": True,
}
text = "\r"

result, cli = feed_cli_with_input("select", message, text, **kwargs)
assert result == "foo"
result_shortcut_keys = [copy(c.shortcut_key) for c in choices]
result2, cli = feed_cli_with_input("select", message, text, **kwargs)
assert result2 == "foo"
result2_shortcut_keys = [copy(c.shortcut_key) for c in choices]
assert (
result_shortcut_keys == result2_shortcut_keys
), "Shortcut keys changed across two runs of 'select'"


def test_select_initial_choice_with_value():
message = "Foo message"
choice = Choice(title="bazz", value="bar")
Expand Down

0 comments on commit 40ef821

Please sign in to comment.