Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Currently, a placeholder until the real CLI will be added.

import sys
import traceback
from collections.abc import Sequence
from typing import Annotated, NoReturn

import cyclopts.types
Expand Down Expand Up @@ -66,13 +67,21 @@ def _fail(exc: Exception, code: int) -> NoReturn:
sys.exit(code)


def main() -> None:
"""Run the CLI, reporting failures and mapping them onto exit codes."""
def main(tokens: Sequence[str] | None = None) -> None:
"""Run the CLI, reporting failures and mapping them onto exit codes.

Args:
tokens: The command line to parse. Defaults to `sys.argv[1:]`.
"""
try:
# Tokens are passed explicitly because cyclopts warns when invoked with none
app(sys.argv[1:], exit_on_error=False)
# `tokens` is a parameter so that tests can pass a command line here.
# Under pytest, a bare `app()` warns, since it would parse pytest's own
# argv, and a test that does so passes while testing nothing.
app(tokens, exit_on_error=False)
except CycloptsError:
# Cyclopts has already printed its own error panel.
# Cyclopts has already printed its own error panel. Cyclopts >=5 exits 2
# on parse errors itself, so once the dependency requires it, this clause
# and `exit_on_error=False` above can both go.
sys.exit(EX_USAGE)
# Nothing reports the errors below, so without `_fail` the CLI would exit on
# a bare code and no output. Match on the exception rather than on
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import sys

import pytest

from {{ package_name }} import __version__, cli
Expand All @@ -20,15 +18,16 @@ def test_app(capsys: pytest.CaptureFixture[str]) -> None:
assert "path/to/file" in capsys.readouterr().out


def test_main_usage_error(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(sys, "argv", ["{{ project_name }}", "--not-an-option"])
def test_main_usage_error() -> None:
with pytest.raises(SystemExit) as exc_info:
main()
main(["--not-an-option"])
assert exc_info.value.code == EX_USAGE


def test_main_unhandled_error(monkeypatch: pytest.MonkeyPatch) -> None:
def explode(**_kwargs: object) -> None:
# Accept the call that `main` makes, so that the RuntimeError below is what
# reaches it, rather than a TypeError over the signature.
def explode(*_args: object, **_kwargs: object) -> None:
raise RuntimeError

monkeypatch.setattr(cli, "app", explode)
Expand Down