Skip to content

Commit

Permalink
Fix variables with null default not being required (#1919) (#1920)
Browse files Browse the repository at this point in the history
* Fix variables with null default not being required (#1919)

* Got rid of walrus operator to support Python 3.7
  • Loading branch information
limtis0 committed Sep 21, 2023
1 parent 6434fd8 commit f4faa86
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
8 changes: 7 additions & 1 deletion cookiecutter/prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,13 @@ def read_user_variable(var_name, default_value, prompts=None, prefix=""):
if prompts and var_name in prompts.keys() and prompts[var_name]
else var_name
)
return Prompt.ask(f"{prefix}{question}", default=default_value)

while True:
variable = Prompt.ask(f"{prefix}{question}", default=default_value)
if variable is not None:
break

return variable


class YesNoPrompt(Confirm):
Expand Down
26 changes: 22 additions & 4 deletions tests/test_read_user_variable.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,36 @@
"""test_read_user_variable."""
import pytest
from cookiecutter.prompt import read_user_variable

VARIABLE = 'project_name'
DEFAULT = 'Kivy Project'


def test_click_invocation(mocker):
@pytest.fixture
def mock_prompt(mocker):
"""Return a mocked version of the 'Prompt.ask' function."""
return mocker.patch('rich.prompt.Prompt.ask')


def test_click_invocation(mock_prompt):
"""Test click function called correctly by cookiecutter.
Test for string type invocation.
"""
prompt = mocker.patch('rich.prompt.Prompt.ask')
prompt.return_value = DEFAULT
mock_prompt.return_value = DEFAULT

assert read_user_variable(VARIABLE, DEFAULT) == DEFAULT

prompt.assert_called_once_with(VARIABLE, default=DEFAULT)
mock_prompt.assert_called_once_with(VARIABLE, default=DEFAULT)


def test_input_loop_with_null_default_value(mock_prompt):
"""Test `Prompt.ask` is run repeatedly until a valid answer is provided.
Test for `default_value` parameter equal to None.
"""
# Simulate user providing None input initially and then a valid input
mock_prompt.side_effect = [None, DEFAULT]

assert read_user_variable(VARIABLE, None) == DEFAULT
assert mock_prompt.call_count == 2

0 comments on commit f4faa86

Please sign in to comment.