Skip to content

Commit

Permalink
Allow app-dir parameter on the run() function (#1271)
Browse files Browse the repository at this point in the history
* Allow app-dir parameter on the run() function

* Add default value to pop() call

* Update GitHub templates with new forms

* Add test
  • Loading branch information
Kludex committed Dec 6, 2021
1 parent 9c1b88c commit edb6454
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
23 changes: 23 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import platform
import sys
from pathlib import Path
from textwrap import dedent
from unittest import mock

import pytest
Expand Down Expand Up @@ -159,3 +160,25 @@ def test_mistmatch_env_variables(load_env_h11_protocol: None):
runner.invoke(cli, ["tests.test_cli:App", "--http=httptools"])
_, kwargs = mock_run.call_args
assert kwargs["http"] == "httptools"


def test_app_dir(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
app_dir = tmp_path / "dir" / "app_dir"
app_file = app_dir / "main.py"
app_dir.mkdir(parents=True)
app_file.touch()
app_file.write_text(
dedent(
"""
async def app(scope, receive, send):
...
"""
)
)
runner = CliRunner()
with mock.patch.object(Server, "run") as mock_run:
result = runner.invoke(cli, ["main:app", "--app-dir", f"{str(app_dir)}"])

assert result.exit_code == 3
mock_run.assert_called_once()
assert sys.path[0] == str(app_dir)
8 changes: 5 additions & 3 deletions uvicorn/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,6 @@ def print_version(ctx: click.Context, param: click.Parameter, value: bool) -> No
)
@click.option(
"--app-dir",
"app_dir",
default=".",
show_default=True,
help="Look for APP in the specified directory, by adding this to the PYTHONPATH."
Expand Down Expand Up @@ -379,8 +378,6 @@ def main(
app_dir: str,
factory: bool,
) -> None:
sys.path.insert(0, app_dir)

kwargs = {
"host": host,
"port": port,
Expand Down Expand Up @@ -424,11 +421,16 @@ def main(
"headers": [header.split(":", 1) for header in headers],
"use_colors": use_colors,
"factory": factory,
"app_dir": app_dir,
}
run(app, **kwargs)


def run(app: typing.Union[ASGIApplication, str], **kwargs: typing.Any) -> None:
app_dir = kwargs.pop("app_dir", None)
if app_dir is not None:
sys.path.insert(0, app_dir)

config = Config(app, **kwargs)
server = Server(config=config)

Expand Down

0 comments on commit edb6454

Please sign in to comment.