Show an error if both --alias and --host are defined (#513)

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.
This commit is contained in:
Teemu R 2023-10-04 23:35:26 +02:00 committed by GitHub
parent a2444da9df
commit 84a501bcdc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 5 deletions

View File

@ -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)

View File

@ -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