Skip to content

Commit 9edf51d

Browse files
committed
fix: replace bare assert with user-friendly error in _guess_method
1 parent 5b604c3 commit 9edf51d

2 files changed

Lines changed: 33 additions & 1 deletion

File tree

httpie/cli/argparser.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -413,7 +413,14 @@ def _guess_method(self):
413413
"""
414414
if self.args.method is None:
415415
# Invoked as `http URL'.
416-
assert not self.args.request_items
416+
if self.args.request_items:
417+
self.error(
418+
'no HTTP method or URL detected but request items found. '
419+
'Please make sure that the URL comes right after '
420+
'the optional METHOD:\n'
421+
' http [METHOD] URL [REQUEST_ITEM ...]\n'
422+
'See https://httpie.io/docs/cli for more information.'
423+
)
417424
if self.has_input_data:
418425
self.args.method = HTTP_POST
419426
else:

tests/test_cli.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,31 @@ def test_guess_when_method_set_but_invalid_and_item_exists(self):
316316
key='old_item', value='b', sep='=', orig='old_item=b'),
317317
]
318318

319+
def test_guess_when_method_not_set_but_request_items_present(self):
320+
"""When method is None but request_items exist, _guess_method
321+
should produce a user-friendly error instead of an AssertionError.
322+
323+
This state can occur when argparse misassigns positional arguments
324+
due to intermixed optional and positional arguments (e.g.,
325+
``http POST --auth-type bearer --auth token URL``).
326+
See https://github.com/httpie/cli/issues/1614
327+
"""
328+
self.parser.args = argparse.Namespace()
329+
self.parser.args.method = None
330+
self.parser.args.url = 'http://example.com/'
331+
self.parser.args.request_items = [
332+
KeyValueArg(
333+
key='test', value='header', sep=':', orig='test:header')
334+
]
335+
self.parser.args.ignore_stdin = False
336+
self.parser.env = MockEnvironment()
337+
# Patch print_usage since the parser isn't fully initialized in
338+
# unit tests (no spec attribute).
339+
self.parser.print_usage = lambda *a, **kw: None
340+
with pytest.raises(SystemExit) as exc_info:
341+
self.parser._guess_method()
342+
assert exc_info.value.code == 2
343+
319344

320345
class TestNoOptions:
321346

0 commit comments

Comments
 (0)