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
11 changes: 8 additions & 3 deletions src/itzi/itzi.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
from itzi.providers.grass_interface import GrassInterface


def main(argv=None):
def main(argv: list[str] | None = None) -> int | None:
"""argv: alternative CLI arguments, used for testing (default to sys.argv)"""
args = build_parser().parse_args(argv)

Expand All @@ -60,8 +60,11 @@ def main(argv=None):
"version": itzi_version,
}

# args.command is the name of the subcommand
command_mapper[args.command](args)
try:
# args.command is the name of the subcommand
command_mapper[args.command](args)
except msgr.FatalError:
return 1


class SimulationRunner:
Expand Down Expand Up @@ -211,6 +214,8 @@ def sim_runner_worker(conf_file: str, hotstart_file: str | None):
hotstart_file,
)
sim_runner.run().finalize()
except msgr.FatalError:
return
except Exception:
msgr.warning("Error during execution: {}".format(traceback.format_exc()))

Expand Down
6 changes: 5 additions & 1 deletion src/itzi/messenger.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ class VerbosityLevel:
DEBUG = 4


class FatalError(RuntimeError):
"""An expected fatal error that has already been shown to the user."""


def verbosity():
"""Return the current verbosity as integer"""
try:
Expand Down Expand Up @@ -99,7 +103,7 @@ def fatal(self, msg: str) -> NoReturn:
"""Log fatal error and raise or exit"""
self.logger.error(f"ERROR: {msg}")
if raise_on_error:
raise RuntimeError(msg)
raise FatalError(msg)
else:
sys.exit(f"ERROR: {msg}")

Expand Down
17 changes: 17 additions & 0 deletions tests/cli/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from io import StringIO

import pytest

import itzi.messenger as msgr


@pytest.fixture
def itzi_stderr(monkeypatch):
console_handler = next(
handler
for handler in msgr._itzi_logger.logger.handlers
if getattr(handler, "_itzi_console_handler", False)
)
stream = StringIO()
monkeypatch.setattr(console_handler, "stream", stream)
return stream
46 changes: 45 additions & 1 deletion tests/cli/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,15 @@

import pytest

from itzi.itzi import main, itzi_run, reconcile_hotstart_commands, VerbosityLevel
import itzi.messenger as msgr
from itzi.cli_parser import build_parser
from itzi.itzi import (
VerbosityLevel,
itzi_run,
main,
reconcile_hotstart_commands,
sim_runner_worker,
)


def test_run_parser_accepts_multiple_config_files():
Expand Down Expand Up @@ -43,6 +50,43 @@ def test_prints_version(monkeypatch, capsys):
assert capsys.readouterr().out.strip() == "22.2"


def test_main_returns_error_status_for_fatal_error(monkeypatch, itzi_stderr):
def fail(_):
msgr.fatal("expected failure")

monkeypatch.setattr("itzi.itzi.itzi_run", fail)

assert main(["run", "a.ini"]) == 1
stderr = itzi_stderr.getvalue()
assert stderr.count("ERROR: expected failure") == 1
assert "Traceback" not in stderr


def test_main_propagates_unexpected_error(monkeypatch):
def fail(_):
raise ValueError("unexpected")

monkeypatch.setattr("itzi.itzi.itzi_run", fail)

with pytest.raises(ValueError, match="unexpected"):
main(["run", "a.ini"])


def test_worker_does_not_format_fatal_error_as_traceback(monkeypatch, itzi_stderr):
def fail(_):
msgr.fatal("expected worker failure")

monkeypatch.setenv("ITZI_VERBOSE", str(VerbosityLevel.QUIET))
monkeypatch.setattr("itzi.itzi.ConfigReader", fail)

sim_runner_worker("a.ini", None)

stderr = itzi_stderr.getvalue()
assert stderr.count("ERROR: expected worker failure") == 1
assert "Traceback" not in stderr
assert "WARNING: Error during execution" not in stderr


def test_reconcile_hotstart_commands_accepts_single_resume_for_single_config():
assert reconcile_hotstart_commands(["/tmp/a.ini"], [(None, "restart_a.zip")]) == [
("/tmp/a.ini", "restart_a.zip"),
Expand Down
12 changes: 12 additions & 0 deletions tests/cli/test_messenger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import pytest

import itzi.messenger as msgr


def test_fatal_raises_runtime_compatible_error(itzi_stderr):
with pytest.raises(msgr.FatalError, match="expected failure") as error:
msgr.fatal("expected failure")

assert isinstance(error.value, RuntimeError)
assert str(error.value) == "expected failure"
assert itzi_stderr.getvalue().count("ERROR: expected failure") == 1