Skip to content

Commit

Permalink
Ensure non-zero exit code when startup fails (#1278)
Browse files Browse the repository at this point in the history
* Ensure non-zero exit code when startup fails

* Make sure it only works on standalone uvicorn run

* Fix test

* Rename constant name
  • Loading branch information
Kludex committed Dec 6, 2021
1 parent 63a10e5 commit 825aeba
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
2 changes: 1 addition & 1 deletion tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def test_cli_call_server_run() -> None:
with mock.patch.object(Server, "run") as mock_run:
result = runner.invoke(cli, ["tests.test_cli:App"])

assert result.exit_code == 0
assert result.exit_code == 3
mock_run.assert_called_once()


Expand Down
12 changes: 12 additions & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,15 @@ def test_run_invalid_app_config_combination(caplog: pytest.LogCaptureFixture) ->
"You must pass the application as an import string to enable "
"'reload' or 'workers'."
)


def test_run_startup_failure(caplog: pytest.LogCaptureFixture) -> None:
async def app(scope, receive, send):
assert scope["type"] == "lifespan"
message = await receive()
if message["type"] == "lifespan.startup":
raise RuntimeError("Startup failed")

with pytest.raises(SystemExit) as exit_exception:
run(app, lifespan="on")
assert exit_exception.value.code == 3
5 changes: 5 additions & 0 deletions uvicorn/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
LOOP_CHOICES = click.Choice([key for key in LOOP_SETUPS.keys() if key != "none"])
INTERFACE_CHOICES = click.Choice(INTERFACES)

STARTUP_FAILURE = 3

logger = logging.getLogger("uvicorn.error")


Expand Down Expand Up @@ -449,6 +451,9 @@ def run(app: typing.Union[ASGIApplication, str], **kwargs: typing.Any) -> None:
if config.uds:
os.remove(config.uds) # pragma: py-win32

if not server.started and not config.should_reload and config.workers == 1:
sys.exit(STARTUP_FAILURE)


if __name__ == "__main__":
main() # pragma: no cover

0 comments on commit 825aeba

Please sign in to comment.