make context.exit raise a custom exception
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This exception is caught in Command.main where we turn this into either an exception or a system exit. This allows context.exit to work when standalone_mode=False.
authored by Joe Jevnik · committed by Stephen Rosen · parent a0e0328 · Browse files · 3 files·+65 added−10 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+65 added−10 removed
- tests:+25 added−1 removed
- other:+40 added−9 removed
Provenance
- Commit
4308336- Tree
f820f96- Author
Joe Jevnik <joe@quantopian.com>- Committer
Stephen Rosen <sirosen@uchicago.edu>- Parent
a0e0328
3 files changed+65 added−10 removed
modified:click/core.py+8 added-2 removed
7 unmodified lines8 9 from .types import convert_type, IntRange, BOOL10 from .utils import make_str, make_default_short_help, echo, get_os_args11 from .exceptions import ClickException, UsageError, BadParameter, Abort, \12- MissingParameter12+ MissingParameter, Exit13 from .termui import prompt, confirm, style14 from .formatting import HelpFormatter, join_options15 from .parser import OptionParser, split_opt16 from .globals import push_context, pop_context480 unmodified lines497 raise Abort()498 499 def exit(self, code=0):500 """Exits the application with a given exit code."""501- sys.exit(code)501+ raise Exit(code, self)502 503 def get_usage(self):504 """Helper method to get formatted usage string for the current505 context and command.211 unmodified lines717 ctx.exit()718 except (EOFError, KeyboardInterrupt):719 echo(file=sys.stderr)720 raise Abort()721+ except Exit as e:722+ if not standalone_mode:723+ if e.exit_code:724+ raise725+ return None726+ sys.exit(e.exit_code)727 except ClickException as e:728 if not standalone_mode:729 raise730 e.show()1106 unmodified linesmodified:click/exceptions.py+32 added-7 removed
11 unmodified lines12 """An exception that Click can handle and show to the user."""13 14 #: The exit code for this exception15 exit_code = 116+ show_prefix = 'Error: '17 18 def __init__(self, message):19 ctor_msg = message20 if PY2:16 unmodified lines37 38 def show(self, file=None):39 if file is None:40 file = get_text_stderr()40- echo('Error: %s' % self.format_message(), file=file)41+ echo('%s%s' % (self.show_prefix, self.format_message()), file=file)42 43 43-class UsageError(ClickException):44- """An internal exception that signals a usage error. This typically45- aborts any further handling.44+class ContextAwareException(ClickException):45+ """An exception that knows how to use a :class:`~click.Context` object46+ to properly display itself.47 48 :param message: the error message to display.49 :param ctx: optionally the context that caused this error. Click will50 fill in the context automatically in some situations.51 """51- exit_code = 252-52 def __init__(self, message, ctx=None):53 ClickException.__init__(self, message)54 self.ctx = ctx55 self.cmd = self.ctx and self.ctx.command or None9 unmodified lines65 % (self.ctx.command_path, self.ctx.help_option_names[0]))66 if self.ctx is not None:67 color = self.ctx.color68 echo(self.ctx.get_usage() + '\n%s' % hint, file=file, color=color)70- echo('Error: %s' % self.format_message(), file=file, color=color)69+ echo('%s%s' % (self.show_prefix, self.format_message()), file=file, color=color)70 71 72+class Exit(ContextAwareException):73+ """An exception that indicates that the application should exit with some74+ status code.75+76+ :param code: the status code to exit with.77+ :param ctx: optionally the context that caused this error. Click will78+ fill in the context automatically in some situations.79+ """80+ show_prefix = 'Exit: '81+82+ def __init__(self, code, ctx=None):83+ ContextAwareException.__init__(self, str(code), ctx=None)84+ self.exit_code = code85+86+87+class UsageError(ContextAwareException):88+ """An internal exception that signals a usage error. This typically89+ aborts any further handling.90+91+ :param message: the error message to display.92+ :param ctx: optionally the context that caused this error. Click will93+ fill in the context automatically in some situations.94+ """95+ exit_code = 296+97+98 class BadParameter(UsageError):99 """An exception that formats out a standardized error message for a100 bad parameter. This is useful when thrown from a callback or type as101 Click will attach contextual information to it (for instance, which149 unmodified linesmodified:tests/test_context.py+25 added-1 removed
1 # -*- coding: utf-8 -*-2+import pytest3+4 import click5 6 7 def test_ensure_context_objects(runner):197 unmodified lines205 assert not result.exception206 assert result.output == 'aha!\n'207 assert called == [True]208 207-209 def test_make_pass_decorator_args(runner):210 """211 Test to check that make_pass_decorator doesn't consume arguments based on212 invocation order.26 unmodified lines239 240 result = runner.invoke(cli, ['test2'])241 assert not result.exception242 assert result.output == 'foocmd\n'243+244+def test_exit_not_standalone_failure():245+ @click.command()246+ @click.pass_context247+ def cli(ctx):248+ ctx.exit(1)249+250+ with pytest.raises(click.exceptions.Exit) as e:251+ cli.main([], 'test_exit_not_standalone', standalone_mode=False)252+ assert e.value.exit_code == 1253+254+255+def test_exit_not_standalone_success():256+ @click.command()257+ @click.pass_context258+ def cli(ctx):259+ ctx.exit(0)260+261+ assert cli.main(262+ [],263+ 'test_exit_not_standalone',264+ standalone_mode=False,265+ ) is None