Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion fixit/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def run_wc(args: argparse.Namespace) -> None:
def run_convert(args: argparse.Namespace) -> None:
try:
result = CONVERSIONS[args.kind](args.value)
print(result)
print(round(result, args.decimals))
except KeyError:
raise ValueError(f"Error: unknown conversion '{args.kind}'")

Expand Down Expand Up @@ -222,6 +222,9 @@ def build_parser() -> argparse.ArgumentParser:
cv = sub.add_parser("convert", help="convert units")
cv.add_argument("value", type=finite_float)
cv.add_argument("kind", choices=sorted(CONVERSIONS))
cv.add_argument(
"--decimals", type=int, default=2, help="digits after the decimal point (default: 2)"
)

pw = sub.add_parser("password", help="generate a password")
pw.add_argument("--length", type=int, default=12)
Expand Down
21 changes: 21 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,27 @@ def test_roman_invalid_numeral(capsys):
assert "not a valid Roman numeral" in capsys.readouterr().err


def test_convert_rounds_to_two_decimals_by_default(capsys):
result = main(["convert", "100", "f2c"])

assert result == 0
assert capsys.readouterr().out.strip() == "37.78"


def test_convert_decimals_option(capsys):
result = main(["convert", "100", "f2c", "--decimals", "4"])

assert result == 0
assert capsys.readouterr().out.strip() == "37.7778"


def test_convert_whole_result_keeps_trailing_zero(capsys):
result = main(["convert", "100", "c2f"])

assert result == 0
assert capsys.readouterr().out.strip() == "212.0"


@pytest.mark.parametrize("value", ["nan", "inf"])
def test_convert_rejects_non_finite_values(value):
with pytest.raises(SystemExit):
Expand Down
Loading