From 84a501bcdc97bedce0d87689ff9db6af880344ae Mon Sep 17 00:00:00 2001 From: Teemu R Date: Wed, 4 Oct 2023 23:35:26 +0200 Subject: [PATCH] Show an error if both --alias and --host are defined (#513) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Display an error if both --alias and --host are defined to avoid ambiguous target device: ``` ❯ kasa --host 123 --alias 123 state Usage: kasa [OPTIONS] COMMAND [ARGS]... Try 'kasa --help' for help. Error: Use either --alias or --host, not both. ``` Also, use `click.BadOptionUsage` consistently for other errors, like when only `--username` or `--password` is given. --- kasa/cli.py | 8 ++++++-- kasa/tests/test_cli.py | 24 +++++++++++++++++++++--- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/kasa/cli.py b/kasa/cli.py index f0c180c5..17b8b366 100755 --- a/kasa/cli.py +++ b/kasa/cli.py @@ -209,6 +209,9 @@ async def cli( if ctx.invoked_subcommand == "discover": return + if alias is not None and host is not None: + raise click.BadOptionUsage("alias", "Use either --alias or --host, not both.") + if alias is not None and host is None: echo(f"Alias is given, using discovery to find host {alias}") host = await find_host_from_alias(alias=alias, target=target) @@ -219,8 +222,9 @@ async def cli( return if bool(password) != bool(username): - echo("Using authentication requires both --username and --password") - return + raise click.BadOptionUsage( + "username", "Using authentication requires both --username and --password" + ) credentials = Credentials(username=username, password=password) diff --git a/kasa/tests/test_cli.py b/kasa/tests/test_cli.py index 4a47284b..7f6fa0f2 100644 --- a/kasa/tests/test_cli.py +++ b/kasa/tests/test_cli.py @@ -183,9 +183,9 @@ async def test_credentials(discovery_data: dict, mocker): @pytest.mark.parametrize("auth_param", ["--username", "--password"]) async def test_invalid_credential_params(auth_param): + """Test for handling only one of username or password supplied.""" runner = CliRunner() - # Test for handling only one of username or passowrd supplied. res = await runner.invoke( cli, [ @@ -197,7 +197,25 @@ async def test_invalid_credential_params(auth_param): "foo", ], ) - assert res.exit_code == 0 + assert res.exit_code == 2 assert ( - res.output == "Using authentication requires both --username and --password\n" + "Error: Using authentication requires both --username and --password" + in res.output ) + + +async def test_duplicate_target_device(): + """Test that defining both --host or --alias gives an error.""" + runner = CliRunner() + + res = await runner.invoke( + cli, + [ + "--host", + "127.0.0.1", + "--alias", + "foo", + ], + ) + assert res.exit_code == 2 + assert "Error: Use either --alias or --host, not both." in res.output