From 6aa3fa51931377a01d21bdb496bfc5a01dc2c92f Mon Sep 17 00:00:00 2001 From: chelsealong Date: Mon, 10 Aug 2026 11:18:33 +0800 Subject: [PATCH] fix: catch ValueError instead of bare except in account CLI commands (#40356) --- api/commands/account.py | 4 +- .../commands/test_account_commands.py | 38 +++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 api/tests/unit_tests/commands/test_account_commands.py diff --git a/api/commands/account.py b/api/commands/account.py index 9ea52dfd248..6751361a1a0 100644 --- a/api/commands/account.py +++ b/api/commands/account.py @@ -33,7 +33,7 @@ def reset_password(email, new_password, password_confirm): try: valid_password(new_password) - except: + except ValueError: click.echo(click.style(f"Invalid password. Must match {password_pattern}", fg="red")) return @@ -75,7 +75,7 @@ def reset_email(email, new_email, email_confirm): try: email_validate(normalized_new_email) - except: + except ValueError: click.echo(click.style(f"Invalid email: {new_email}", fg="red")) return diff --git a/api/tests/unit_tests/commands/test_account_commands.py b/api/tests/unit_tests/commands/test_account_commands.py new file mode 100644 index 00000000000..bbcc5d3e704 --- /dev/null +++ b/api/tests/unit_tests/commands/test_account_commands.py @@ -0,0 +1,38 @@ +from unittest.mock import Mock + +import pytest +from click.testing import CliRunner + +from commands.account import reset_email, reset_password + + +def test_reset_password_does_not_swallow_keyboard_interrupt(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr( + "commands.account.AccountService.get_account_by_email_with_case_fallback", + Mock(return_value=Mock()), + ) + monkeypatch.setattr("commands.account.valid_password", Mock(side_effect=KeyboardInterrupt)) + + result = CliRunner().invoke( + reset_password, + ["--email", "a@example.com", "--new-password", "whatever", "--password-confirm", "whatever"], + ) + + assert not isinstance(result.exception, SystemExit) or result.exception.code != 0 + assert "Invalid password" not in result.output + + +def test_reset_email_does_not_swallow_keyboard_interrupt(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr( + "commands.account.AccountService.get_account_by_email_with_case_fallback", + Mock(return_value=Mock()), + ) + monkeypatch.setattr("commands.account.email_validate", Mock(side_effect=KeyboardInterrupt)) + + result = CliRunner().invoke( + reset_email, + ["--email", "a@example.com", "--new-email", "b@example.com", "--email-confirm", "b@example.com"], + ) + + assert not isinstance(result.exception, SystemExit) or result.exception.code != 0 + assert "Invalid email" not in result.output