Improved bad factory error handling

This commit is contained in:
Armin Ronacher 2017-11-25 00:05:57 +01:00
parent d24bb9ee32
commit c23a63a185
2 changed files with 17 additions and 0 deletions

View File

@ -33,6 +33,12 @@ except ImportError:
dotenv = None
def _called_with_wrong_args(factory, exc_info):
exc_type, exc_value, tb = exc_info
return exc_type is TypeError and \
str(exc_value).startswith('%s() takes' % factory.__name__)
class NoAppException(click.UsageError):
"""Raised if an application cannot be found or loaded."""
@ -75,6 +81,8 @@ def find_best_app(script_info, module):
if isinstance(app, Flask):
return app
except TypeError:
if not _called_with_wrong_args(app_factory, sys.exc_info()):
raise
raise NoAppException(
'Detected factory "{factory}" in module "{module}", but '
'could not call it without arguments. Use '
@ -148,6 +156,8 @@ def find_app_by_string(script_info, module, app_name):
try:
app = call_factory(script_info, attr, args)
except TypeError as e:
if not _called_with_wrong_args(attr, sys.exc_info()):
raise
raise NoAppException(
'{e}\nThe factory "{app_name}" in module "{module}" could not '
'be called with the specified arguments.'.format(

View File

@ -144,6 +144,13 @@ def test_find_best_app(test_apps):
pytest.raises(NoAppException, find_best_app, script_info, Module)
class Module:
@staticmethod
def create_app():
raise TypeError('bad bad factory!')
pytest.raises(TypeError, find_best_app, script_info, Module)
@pytest.mark.parametrize('value,path,result', (
('test', cwd, 'test'),