Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Changes to CLI #2401

Merged
merged 11 commits into from Mar 23, 2022
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 18 additions & 1 deletion sanic/cli/app.py
Expand Up @@ -113,6 +113,14 @@ def _get_app(self):
delimiter = ":" if ":" in self.args.module else "."
module_name, app_name = self.args.module.rsplit(delimiter, 1)

if module_name == "" and os.path.isdir(self.args.module):
raise ValueError(
"App not found.\n"
" Please use --simple if you are passing a "
"directory to sanic.\n"
f" eg. sanic {self.args.module} --simple"
)

if app_name.endswith("()"):
self.args.factory = True
app_name = app_name[:-2]
Expand All @@ -125,9 +133,18 @@ def _get_app(self):
app_type_name = type(app).__name__

if not isinstance(app, Sanic):
if callable(app):
solution = f"sanic {self.args.module} --factory"
raise ValueError(
"Module is not a Sanic app, it is a"
f"{app_type_name}\n"
" If this callable returns a"
f"Sanic instance try: \n{solution}"
)

raise ValueError(
f"Module is not a Sanic app, it is a {app_type_name}\n"
f" Perhaps you meant {self.args.module}.app?"
f" Perhaps you meant {self.args.module}:app?"
)
except ImportError as e:
if module_name.startswith(e.name):
Expand Down
6 changes: 6 additions & 0 deletions tests/fake/factory.py
@@ -0,0 +1,6 @@
from sanic import Sanic


def run():
app = Sanic("FactoryTest")
return app
16 changes: 16 additions & 0 deletions tests/test_cli.py
Expand Up @@ -57,6 +57,22 @@ def test_server_run(appname):
assert firstline == b"Goin' Fast @ http://127.0.0.1:8000"


def test_error_with_function_as_instance_without_factory_arg():
command = ["sanic", "fake.factory.run"]
out, err, exitcode = capture(command)
assert b"try: \nsanic fake.factory.run --factory" in err
assert exitcode != 1


def test_error_with_path_as_instance_without_simple_arg():
command = ["sanic", "./fake/"]
out, err, exitcode = capture(command)
assert (
b"Please use --simple if you are passing a directory to sanic." in err
)
assert exitcode != 1


@pytest.mark.parametrize(
"cmd",
(
Expand Down