cleaner message when CLI can't load app
Before adoption: this commit came in with the history the project adopted, so no landing records it.
When loading the app fails for the --help command, only the error message is shown, then the help text. The full traceback is shown for other exceptions. Also show the message when loading fails while getting a command, instead of only "command not found". The error message goes to stderr to match other error behavior, and is in red with an extra newline to make it more obvious next to the help text. Also fixes an issue with the test_apps fixture that caused an imported app to still be importable after the test was over and the path was reset. Now the module cache is reset as well.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+58 added−37 removed
- tests:+34 added−13 removed
- other:+24 added−24 removed
Provenance
- Commit
2535707- Tree
ac0e99b- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
fd0a608
4 files changed+58 added−37 removed
modified:src/flask/cli.py+22 added-24 removed
534 unmodified lines535 self._loaded_plugin_commands = True536 537 def get_command(self, ctx, name):538 self._load_plugin_commands()539+ # Look up built-in and plugin commands, which should be540+ # available even if the app fails to load.541+ rv = super().get_command(ctx, name)542 540- # We load built-in commands first as these should always be the541- # same no matter what the app does. If the app does want to542- # override this it needs to make a custom instance of this group543- # and not attach the default commands.544- #545- # This also means that the script stays functional in case the546- # application completely fails.547- rv = AppGroup.get_command(self, ctx, name)543 if rv is not None:544 return rv545 546 info = ctx.ensure_object(ScriptInfo)547+548+ # Look up commands provided by the app, showing an error and549+ # continuing if the app couldn't be loaded.550 try:553- rv = info.load_app().cli.get_command(ctx, name)554- if rv is not None:555- return rv556- except NoAppException:557- pass551+ return info.load_app().cli.get_command(ctx, name)552+ except NoAppException as e:553+ click.secho(f"Error: {e.format_message()}\n", err=True, fg="red")554 555 def list_commands(self, ctx):556 self._load_plugin_commands()561-562- # The commands available is the list of both the application (if563- # available) plus the builtin commands.564- rv = set(click.Group.list_commands(self, ctx))557+ # Start with the built-in and plugin commands.558+ rv = set(super().list_commands(ctx))559 info = ctx.ensure_object(ScriptInfo)560+561+ # Add commands provided by the app, showing an error and562+ # continuing if the app couldn't be loaded.563 try:564 rv.update(info.load_app().cli.list_commands(ctx))565+ except NoAppException as e:566+ # When an app couldn't be loaded, show the error message567+ # without the traceback.568+ click.secho(f"Error: {e.format_message()}\n", err=True, fg="red")569 except Exception:569- # Here we intentionally swallow all exceptions as we don't570- # want the help page to break if the app does not exist.571- # If someone attempts to use the command we try to create572- # the app again and this will give us the error.573- # However, we will not do so silently because that would confuse574- # users.575- traceback.print_exc()570+ # When any other errors occurred during loading, show the571+ # full traceback.572+ click.secho(f"{traceback.format_exc()}\n", err=True, fg="red")573+574 return sorted(rv)575 576 def main(self, *args, **kwargs):577 # Set a global flag that indicates that we were invoked from the385 unmodified linesmodified:tests/conftest.py+9 added-3 removed
71 unmodified lines72 73 74 @pytest.fixture75 def test_apps(monkeypatch):76- monkeypatch.syspath_prepend(77- os.path.abspath(os.path.join(os.path.dirname(__file__), "test_apps"))78- )76+ monkeypatch.syspath_prepend(os.path.join(os.path.dirname(__file__), "test_apps"))77+ original_modules = set(sys.modules.keys())78 79+ yield80 81+ # Remove any imports cached during the test. Otherwise "import app"82+ # will work in the next test even though it's no longer on the path.83+ for key in sys.modules.keys() - original_modules:84+ sys.modules.pop(key)85+86+87 @pytest.fixture(autouse=True)88 def leak_detector():89 yield90 107 unmodified linesmodified:tests/test_cli.py+25 added-10 removed
237 unmodified lines238 with pytest.raises(NoAppException):239 locate_app(info, iname, aname)240 241 242-def test_locate_app_suppress_raise():242+def test_locate_app_suppress_raise(test_apps):243 info = ScriptInfo()244 app = locate_app(info, "notanapp.py", None, raise_if_not_found=False)245 assert app is None246 148 unmodified lines395 assert result.exit_code == 0396 assert result.output == f"{not set_debug_flag}\n"397 398 399-def test_print_exceptions(runner):400- """Print the stacktrace if the CLI."""399+def test_no_command_echo_loading_error():400+ from flask.cli import cli401 402+ runner = CliRunner(mix_stderr=False)403+ result = runner.invoke(cli, ["missing"])404+ assert result.exit_code == 2405+ assert "FLASK_APP" in result.stderr406+ assert "Usage:" in result.stderr407+408+409+def test_help_echo_loading_error():410+ from flask.cli import cli411+412+ runner = CliRunner(mix_stderr=False)413+ result = runner.invoke(cli, ["--help"])414+ assert result.exit_code == 0415+ assert "FLASK_APP" in result.stderr416+ assert "Usage:" in result.stdout417+418+419+def test_help_echo_exception():420 def create_app():421 raise Exception("oh no")404- return Flask("flaskgroup")422 406- @click.group(cls=FlaskGroup, create_app=create_app)407- def cli(**params):408- pass409-423+ cli = FlaskGroup(create_app=create_app)424+ runner = CliRunner(mix_stderr=False)425 result = runner.invoke(cli, ["--help"])426 assert result.exit_code == 0412- assert "Exception: oh no" in result.output413- assert "Traceback" in result.output427+ assert "Exception: oh no" in result.stderr428+ assert "Usage:" in result.stdout429 430 431 class TestRoutes:432 @pytest.fixture229 unmodified linesmodified:CHANGES.rst+2 added
10 unmodified lines11 - The ``encoding`` option to JSON functions is deprecated. :pr:`3562`12 - Passing ``script_info`` to app factory functions is deprecated. This13 was not portable outside the ``flask`` command. Use14 ``click.get_current_context().obj`` if it's needed. :issue:`3552`15+- The CLI shows better error messages when the app failed to load16+ when looking up commands. :issue:`2741`17 - Add :meth:`sessions.SessionInterface.get_cookie_name` to allow18 setting the session cookie name dynamically. :pr:`3369`19 - Add :meth:`Config.from_file` to load config using arbitrary file20 loaders, such as ``toml.load`` or ``json.load``.1043 unmodified lines