From b01704cce13bbb65e60b809ccb9fd58b6a8821ee Mon Sep 17 00:00:00 2001 From: CrazyMerlyn Date: Sun, 2 Sep 2018 20:42:47 +0000 Subject: [PATCH] Fix exit code for command line errors Fixes #3913 --- AUTHORS | 1 + changelog/3913.bugfix.rst | 1 + src/_pytest/config/argparsing.py | 15 +++++++++++++++ testing/acceptance_test.py | 5 +++++ 4 files changed, 22 insertions(+) create mode 100644 changelog/3913.bugfix.rst diff --git a/AUTHORS b/AUTHORS index cb207eb71..144eb19db 100644 --- a/AUTHORS +++ b/AUTHORS @@ -46,6 +46,7 @@ Christian Boelsen Christian Theunert Christian Tismer Christopher Gilling +CrazyMerlyn Cyrus Maden Dhiren Serai Daniel Grana diff --git a/changelog/3913.bugfix.rst b/changelog/3913.bugfix.rst new file mode 100644 index 000000000..33ed4ce28 --- /dev/null +++ b/changelog/3913.bugfix.rst @@ -0,0 +1 @@ +Pytest now returns with correct exit code (EXIT_USAGEERROR, 4) when called with unknown arguments. diff --git a/src/_pytest/config/argparsing.py b/src/_pytest/config/argparsing.py index 3a2a11af4..784b2b212 100644 --- a/src/_pytest/config/argparsing.py +++ b/src/_pytest/config/argparsing.py @@ -2,8 +2,13 @@ import six import warnings import argparse +from gettext import gettext as _ +import sys as _sys + import py +from ..main import EXIT_USAGEERROR + FILE_OR_DIR = "file_or_dir" @@ -329,6 +334,16 @@ class MyOptionParser(argparse.ArgumentParser): # an usage error to provide more contextual information to the user self.extra_info = extra_info + def error(self, message): + """error(message: string) + + Prints a usage message incorporating the message to stderr and + exits. + Overrides the method in parent class to change exit code""" + self.print_usage(_sys.stderr) + args = {"prog": self.prog, "message": message} + self.exit(EXIT_USAGEERROR, _("%(prog)s: error: %(message)s\n") % args) + def parse_args(self, args=None, namespace=None): """allow splitting of positional arguments""" args, argv = self.parse_known_args(args, namespace) diff --git a/testing/acceptance_test.py b/testing/acceptance_test.py index 428ac464c..8a9585be2 100644 --- a/testing/acceptance_test.py +++ b/testing/acceptance_test.py @@ -1061,3 +1061,8 @@ def test_fixture_mock_integration(testdir): p = testdir.copy_example("acceptance/fixture_mock_integration.py") result = testdir.runpytest(p) result.stdout.fnmatch_lines("*1 passed*") + + +def test_usage_error_code(testdir): + result = testdir.runpytest("-unknown-option-") + assert result.ret == EXIT_USAGEERROR