Skip to content

Commit 29bfa5e

Browse files
authored
Merge pull request #3925 from crazymerlyn/fix-exit-code
Fix exit code for command line errors
2 parents 01df368 + b01704c commit 29bfa5e

File tree

4 files changed

+22
-0
lines changed

4 files changed

+22
-0
lines changed

AUTHORS

+1
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ Christian Boelsen
4646
Christian Theunert
4747
Christian Tismer
4848
Christopher Gilling
49+
CrazyMerlyn
4950
Cyrus Maden
5051
Dhiren Serai
5152
Daniel Grana

changelog/3913.bugfix.rst

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Pytest now returns with correct exit code (EXIT_USAGEERROR, 4) when called with unknown arguments.

src/_pytest/config/argparsing.py

+15
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,13 @@
22
import warnings
33
import argparse
44

5+
from gettext import gettext as _
6+
import sys as _sys
7+
58
import py
69

10+
from ..main import EXIT_USAGEERROR
11+
712
FILE_OR_DIR = "file_or_dir"
813

914

@@ -329,6 +334,16 @@ def __init__(self, parser, extra_info=None):
329334
# an usage error to provide more contextual information to the user
330335
self.extra_info = extra_info
331336

337+
def error(self, message):
338+
"""error(message: string)
339+
340+
Prints a usage message incorporating the message to stderr and
341+
exits.
342+
Overrides the method in parent class to change exit code"""
343+
self.print_usage(_sys.stderr)
344+
args = {"prog": self.prog, "message": message}
345+
self.exit(EXIT_USAGEERROR, _("%(prog)s: error: %(message)s\n") % args)
346+
332347
def parse_args(self, args=None, namespace=None):
333348
"""allow splitting of positional arguments"""
334349
args, argv = self.parse_known_args(args, namespace)

testing/acceptance_test.py

+5
Original file line numberDiff line numberDiff line change
@@ -1061,3 +1061,8 @@ def test_fixture_mock_integration(testdir):
10611061
p = testdir.copy_example("acceptance/fixture_mock_integration.py")
10621062
result = testdir.runpytest(p)
10631063
result.stdout.fnmatch_lines("*1 passed*")
1064+
1065+
1066+
def test_usage_error_code(testdir):
1067+
result = testdir.runpytest("-unknown-option-")
1068+
assert result.ret == EXIT_USAGEERROR

0 commit comments

Comments
 (0)