diff --git a/src/black/ranges.py b/src/black/ranges.py index d7e003db83f..a1771f80834 100644 --- a/src/black/ranges.py +++ b/src/black/ranges.py @@ -36,6 +36,16 @@ def parse_line_ranges(line_ranges: Sequence[str]) -> list[tuple[int, int]]: f" {lines_str!r}" ) from None else: + if start < 1 or end < 1: + raise ValueError( + "Incorrect --line-ranges value, " + f"expect positive integers, found {lines_str!r}" + ) + if start > end: + raise ValueError( + "Incorrect --line-ranges value, expect START <= END, " + f"found {lines_str!r}" + ) lines.append((start, end)) return lines diff --git a/tests/test_ranges.py b/tests/test_ranges.py index 0ed0e989123..dd85123a574 100644 --- a/tests/test_ranges.py +++ b/tests/test_ranges.py @@ -2,7 +2,33 @@ import pytest -from black.ranges import adjusted_lines, sanitized_lines +from black.ranges import adjusted_lines, parse_line_ranges, sanitized_lines + + +@pytest.mark.parametrize( + "lines_str, expected", + [ + (["1-5"], [(1, 5)]), + (["1-1"], [(1, 1)]), + (["1-3", "5-7"], [(1, 3), (5, 7)]), + ], +) +def test_parse_line_ranges_valid(lines_str, expected): + assert parse_line_ranges(lines_str) == expected + + +@pytest.mark.parametrize( + "lines_str", + [ + ["5-3"], + ["0-5"], + ["-1-5"], + ["5-0"], + ], +) +def test_parse_line_ranges_invalid(lines_str): + with pytest.raises(ValueError, match="Incorrect --line-ranges"): + parse_line_ranges(lines_str) @pytest.mark.parametrize(