Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass input to click.confirm without running CLIrunner.invoke()

I have a use case where a function seeks user confirmation to proceed. This is basically:

def abc()
    response = click.confirm("Do you want to continue?")

Based on this response, it either aborts or proceeds.

The problem is to test this function abc.

@click.option('--yes', prompt=True)
def test_abc():
    with mock.patch.object(click.confirm, input="n"):
        click.echo("Aborted")
like image 691
rkatkam Avatar asked Oct 12 '25 13:10

rkatkam


1 Answers

Old question but I had the same issue, I decided to mock the click.confirm which allowed me to simulate someone selecting [y/N]

lets say your abc() looked like this:

def abc():
    if click.confirm("do you want to continue?", abort=True):
        return "Confirmed"

    return "Aborted"

and then your tests mock the click.confirm to y/n

@mock.patch("click.confirm")
def test_abc_aborted(mock_click):
    mock_click.return_value = False
    assert abc() == "Aborted"


@mock.patch("click.confirm")
def test_abc_confirmed(mock_click):
    mock_click.return_value = "y"
    assert abc() == "Confirmed"
like image 132
gardni Avatar answered Oct 14 '25 10:10

gardni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!