Skip to content

Commit 192d5ef

Browse files
committed
Suggest possibly misspelled arguments, e.g.
> locust -extra-files locust: error: unrecognized arguments: -extra-files Did you mean '--extra-files'?
1 parent 604bb33 commit 192d5ef

File tree

2 files changed

+19
-2
lines changed

2 files changed

+19
-2
lines changed

locust/argument_parser.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import argparse
88
import ast
99
import atexit
10+
import difflib
1011
import json
1112
import os
1213
import platform
@@ -60,6 +61,18 @@ class LocustArgumentParser(configargparse.ArgumentParser):
6061
optionally exclude arguments from the UI.
6162
"""
6263

64+
def error(self, message):
65+
# Extract the unknown option from the error message
66+
if "unrecognized arguments:" in message:
67+
bad_arg = message.split("unrecognized arguments:")[1].strip().split()[0]
68+
# Compare with known arguments
69+
options = [action.option_strings for action in self._actions]
70+
options = [opt for sublist in options for opt in sublist] # flatten
71+
suggestion = difflib.get_close_matches(bad_arg, options, n=1)
72+
if suggestion:
73+
message += f"\nDid you mean '{suggestion[0]}'?"
74+
self.exit(2, f"{self.prog}: error: {message}\n")
75+
6376
def add_argument(self, *args, **kwargs) -> configargparse.Action:
6477
"""
6578
This method supports the same args as ArgumentParser.add_argument(..)

locust/test/test_parser.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -294,8 +294,9 @@ def test_parse_locustfile_invalid_directory_error(self):
294294
)
295295

296296
def test_unknown_command_line_arg(self):
297+
err = StringIO()
297298
with self.assertRaises(SystemExit):
298-
with mock.patch("sys.stderr", new=StringIO()):
299+
with mock.patch("sys.stderr", new=err):
299300
parse_options(
300301
args=[
301302
"-f",
@@ -309,10 +310,13 @@ def test_unknown_command_line_arg(self):
309310
"--reset-stats",
310311
"--stop-timeout",
311312
"5",
312-
"--unknown-flag",
313+
"--unknown-flag-extra-files",
313314
"MyUserClass",
314315
]
315316
)
317+
err.seek(0)
318+
stderr = err.read()
319+
self.assertIn("Did you mean '--extra-files'", stderr)
316320

317321
def test_custom_argument(self):
318322
@locust.events.init_command_line_parser.add_listener

0 commit comments

Comments
 (0)