Skip to content

Commit 7930b73

Browse files
committed
Improve error message for bad version specifiers in Requirement
This makes it easier to understand what the state of the parser is and what is expected at that point.
1 parent 258d252 commit 7930b73

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

packaging/_parser.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,13 @@ def _parse_requirement_details(
120120
return (url, specifier, marker)
121121

122122
marker = _parse_requirement_marker(
123-
tokenizer, span_start=specifier_start, after="version specifier"
123+
tokenizer,
124+
span_start=specifier_start,
125+
after=(
126+
"version specifier"
127+
if specifier
128+
else "name and no valid version specifier"
129+
),
124130
)
125131

126132
return (url, specifier, marker)

tests/test_requirements.py

+17-1
Original file line numberDiff line numberDiff line change
@@ -489,11 +489,27 @@ def test_error_on_missing_op_after_name(self) -> None:
489489
# THEN
490490
assert ctx.exconly() == (
491491
"packaging.requirements.InvalidRequirement: "
492-
"Expected end or semicolon (after version specifier)\n"
492+
"Expected end or semicolon (after name and no valid version specifier)\n"
493493
" name 1.0\n"
494494
" ^"
495495
)
496496

497+
def test_error_on_random_char_after_specifier(self) -> None:
498+
# GIVEN
499+
to_parse = "name >= 1.0 #"
500+
501+
# WHEN
502+
with pytest.raises(InvalidRequirement) as ctx:
503+
Requirement(to_parse)
504+
505+
# THEN
506+
assert ctx.exconly() == (
507+
"packaging.requirements.InvalidRequirement: "
508+
"Expected end or semicolon (after version specifier)\n"
509+
" name >= 1.0 #\n"
510+
" ~~~~~~~^"
511+
)
512+
497513

498514
class TestRequirementBehaviour:
499515
def test_types_with_nothing(self) -> None:

0 commit comments

Comments
 (0)