Skip to content

armgit / fli

Public Imported from GitHub
0

Google Flights MCP, CLI and Python Library

fix(cli): an empty result no longer reports "Unexpected error: Exit: 1" or writes a traceback log (#253)

Punit Arani122ef6455938
diff --git a/fli/cli/commands/dates.py b/fli/cli/commands/dates.py
index 1a996fa..993c39e 100644
--- a/fli/cli/commands/dates.py
+++ b/fli/cli/commands/dates.py
@@ -598,6 +598,13 @@ def dates(
raise typer.Exit(1) from e
typer.echo(f"Error: {str(e)}")
raise typer.Exit(1) from e
+ except (typer.Exit, typer.Abort):
+ # click.exceptions.Exit/Abort are RuntimeError subclasses, so without
+ # this clause the broad except below would catch the deliberate
+ # `raise typer.Exit(1)` above (empty results) and report it as a
+ # crash: bogus "Unexpected error" text plus a traceback log file for
+ # a perfectly normal "no flights matched" outcome.
+ raise
except Exception as e: # noqa: BLE001 — fall back to clean reporting
if output_format == OutputFormat.JSON:
payload_info = json_error_payload(e, command="dates")
diff --git a/fli/cli/commands/flights.py b/fli/cli/commands/flights.py
index d2b941b..9726848 100644
--- a/fli/cli/commands/flights.py
+++ b/fli/cli/commands/flights.py
@@ -346,6 +346,13 @@ def _search_flights_core(
emit_json(payload)
raise typer.Exit(1) from e
raise report_cli_error(e, command="flights") from e
+ except (typer.Exit, typer.Abort):
+ # click.exceptions.Exit/Abort are RuntimeError subclasses, so without
+ # this clause the broad except below would catch the deliberate
+ # `raise typer.Exit(1)` above (empty results) and report it as a
+ # crash: bogus "Unexpected error" text plus a traceback log file for
+ # a perfectly normal "no flights matched" outcome.
+ raise
except Exception as e: # noqa: BLE001 — fall back to clean reporting
if output_format == OutputFormat.JSON:
payload_info = json_error_payload(e, command="flights")
diff --git a/fli/cli/commands/multi.py b/fli/cli/commands/multi.py
index 2a231c1..28719ef 100644
--- a/fli/cli/commands/multi.py
+++ b/fli/cli/commands/multi.py
@@ -213,5 +213,12 @@ def multi(
raise typer.Exit(1) from e
except SearchClientError as e:
raise report_cli_error(e, command="multi") from e
+ except (typer.Exit, typer.Abort):
+ # click.exceptions.Exit/Abort are RuntimeError subclasses, so without
+ # this clause the broad except below would catch either of the
+ # deliberate `raise typer.Exit(1)` calls above (too few legs, empty
+ # results) and report it as a crash: bogus "Unexpected error" text
+ # plus a traceback log file for a perfectly normal outcome.
+ raise
except Exception as e: # noqa: BLE001 — fall back to clean reporting
raise report_cli_error(e, command="multi") from e
diff --git a/tests/cli/test_empty_result_exit.py b/tests/cli/test_empty_result_exit.py
new file mode 100644
index 0000000..92718ab
--- /dev/null
+++ b/tests/cli/test_empty_result_exit.py
@@ -0,0 +1,220 @@
+"""An ordinary empty search result must exit clean, not report a crash.
+
+`typer.Exit(1)` — raised in the empty-result branch of `flights`, `dates`, and
+`multi` once the search legitimately returns nothing — is `click.exceptions.Exit`,
+a `RuntimeError` subclass. Each command's broad `except Exception` handler used to
+catch that control-flow exception too, so a perfectly normal "no flights matched"
+outcome also printed a bogus "Unexpected error: Exit: 1" line and wrote a
+traceback log file under `~/.fli/logs/`.
+
+These tests pin down two things per command: the empty-result path exits clean
+with exactly its own message (no extra "Unexpected error" text, no log file),
+and a genuine unexpected exception is still caught and reported exactly as
+before (message + log file) — the fix must not blind the broad handler.
+
+Kept in a new file rather than appended to test_flights.py /test_dates.py /
+test_multi.py: another branch in flight also touches those files, and this
+avoids conflicting with it.
+"""
+
+import json
+from datetime import datetime, timedelta
+from pathlib import Path
+
+import pytest
+from typer.testing import CliRunner
+
+from fli.cli.main import app
+
+
+def runner() -> CliRunner:
+ """Return a CliRunner instance."""
+ return CliRunner()
+
+
[email protected](autouse=True)
+def _isolated_tmp_log_dir(monkeypatch, tmp_path):
+ """Redirect _LOG_DIR so log files land under tmp_path instead of ~/.fli/logs/.
+
+ The target subdirectory does not exist until `_write_log` creates it, so
+ "no log file was written" can be asserted as "the directory was never
+ created" — a bug that silently creates-and-writes would fail that check,
+ while a test that merely looked for zero *known* filenames would not.
+ """
+ monkeypatch.setattr("fli.cli.errors._LOG_DIR", tmp_path / "fli-logs")
+
+
+def _log_dir(tmp_path: Path) -> Path:
+ return tmp_path / "fli-logs"
+
+
+def _future_date(days_ahead: int) -> str:
+ """Return a future date string in YYYY-MM-DD format, relative to today."""
+ return (datetime.now() + timedelta(days=days_ahead)).strftime("%Y-%m-%d")
+
+
+# ---------------------------------------------------------------------------
+# flights
+# ---------------------------------------------------------------------------
+
+
+def test_flights_empty_result_exits_clean(runner, mock_search_flights, mock_console, tmp_path):
+ """An ordinary empty flight search exits 1 with only the empty-result message."""
+ mock_search_flights.search.return_value = []
+
+ result = runner.invoke(app, ["flights", "JFK", "LHR", _future_date(40)])
+
+ assert result.exit_code == 1
+ assert result.output.count("No flights found.") == 1
+ assert "Unexpected error" not in result.output
+ assert "Exit: 1" not in result.output
+ assert "Full traceback" not in result.output
+ assert not _log_dir(tmp_path).exists()
+
+
+def test_flights_json_empty_result_unchanged(runner, mock_search_flights, mock_console):
+ """`--format json` still exits 0 with an empty flights[] payload, untouched by the fix."""
+ mock_search_flights.search.return_value = []
+
+ result = runner.invoke(app, ["flights", "JFK", "LHR", _future_date(40), "--format", "json"])
+
+ assert result.exit_code == 0
+ payload = json.loads(result.stdout)
+ assert payload["success"] is True
+ assert payload["count"] == 0
+ assert payload["flights"] == []
+
+
+def test_flights_unexpected_exception_still_reported(
+ runner, mock_search_flights, mock_console, tmp_path
+):
+ """A genuine crash still goes through the broad handler: message + log file."""
+ mock_search_flights.search.side_effect = RuntimeError("boom")
+
+ result = runner.invoke(app, ["flights", "JFK", "LHR", _future_date(40)])
+
+ assert result.exit_code == 1
+ assert "Unexpected error: RuntimeError: boom" in result.output
+ assert "Full traceback written to" in result.output
+ log_dir = _log_dir(tmp_path)
+ assert log_dir.exists()
+ assert list(log_dir.iterdir())
+
+
+# ---------------------------------------------------------------------------
+# dates
+# ---------------------------------------------------------------------------
+
+
+def test_dates_empty_result_exits_clean(runner, mock_search_dates, mock_console, tmp_path):
+ """An ordinary empty dates search exits 1 with only the empty-result message."""
+ mock_search_dates.search.return_value = []
+
+ result = runner.invoke(app, ["dates", "JFK", "LHR"])
+
+ assert result.exit_code == 1
+ assert result.output.count("No flights found for these dates.") == 1
+ assert "Unexpected error" not in result.output
+ assert "Exit: 1" not in result.output
+ assert "Full traceback" not in result.output
+ assert not _log_dir(tmp_path).exists()
+
+
+def test_dates_empty_result_for_selected_days_exits_clean(
+ runner, mock_search_dates, mock_console, tmp_path
+):
+ """The "selected days" empty-result variant is equally clean."""
+ mock_search_dates.search.return_value = []
+
+ result = runner.invoke(app, ["dates", "JFK", "LHR", "--monday"])
+
+ assert result.exit_code == 1
+ assert result.output.count("No flights found for the selected days.") == 1
+ assert "Unexpected error" not in result.output
+ assert "Exit: 1" not in result.output
+ assert "Full traceback" not in result.output
+ assert not _log_dir(tmp_path).exists()
+
+
+def test_dates_json_empty_result_unchanged(runner, mock_search_dates, mock_console):
+ """`--format json` still exits 0 with an empty dates[] payload, untouched by the fix."""
+ mock_search_dates.search.return_value = []
+
+ result = runner.invoke(app, ["dates", "JFK", "LHR", "--format", "json"])
+
+ assert result.exit_code == 0
+ payload = json.loads(result.stdout)
+ assert payload["success"] is True
+ assert payload["count"] == 0
+ assert payload["dates"] == []
+
+
+def test_dates_unexpected_exception_still_reported(
+ runner, mock_search_dates, mock_console, tmp_path
+):
+ """A genuine crash still goes through the broad handler: message + log file."""
+ mock_search_dates.search.side_effect = RuntimeError("boom")
+
+ result = runner.invoke(app, ["dates", "JFK", "LHR"])
+
+ assert result.exit_code == 1
+ assert "Unexpected error: RuntimeError: boom" in result.output
+ assert "Full traceback written to" in result.output
+ log_dir = _log_dir(tmp_path)
+ assert log_dir.exists()
+ assert list(log_dir.iterdir())
+
+
+# ---------------------------------------------------------------------------
+# multi
+# ---------------------------------------------------------------------------
+
+
+def test_multi_empty_result_exits_clean(runner, mock_search_flights, mock_console, tmp_path):
+ """An ordinary empty multi-city search exits 1 with only the empty-result message."""
+ mock_search_flights.search.return_value = []
+
+ result = runner.invoke(
+ app,
+ ["multi", "--leg", f"SEA,HKG,{_future_date(40)}", "--leg", f"HKG,SEA,{_future_date(47)}"],
+ )
+
+ assert result.exit_code == 1
+ assert result.output.count("No flights found.") == 1
+ assert "Unexpected error" not in result.output
+ assert "Exit: 1" not in result.output
+ assert "Full traceback" not in result.output
+ assert not _log_dir(tmp_path).exists()
+
+
+def test_multi_too_few_legs_exits_clean(runner, mock_search_flights, mock_console, tmp_path):
+ """The "requires at least 2 legs" guard is control flow too, not a crash."""
+ result = runner.invoke(app, ["multi", "--leg", f"SEA,HKG,{_future_date(40)}"])
+
+ assert result.exit_code == 1
+ assert result.output.count("Error: multi-city search requires at least 2 legs") == 1
+ assert "Unexpected error" not in result.output
+ assert "Exit: 1" not in result.output
+ assert "Full traceback" not in result.output
+ assert not _log_dir(tmp_path).exists()
+ mock_search_flights.search.assert_not_called()
+
+
+def test_multi_unexpected_exception_still_reported(
+ runner, mock_search_flights, mock_console, tmp_path
+):
+ """A genuine crash still goes through the broad handler: message + log file."""
+ mock_search_flights.search.side_effect = RuntimeError("boom")
+
+ result = runner.invoke(
+ app,
+ ["multi", "--leg", f"SEA,HKG,{_future_date(40)}", "--leg", f"HKG,SEA,{_future_date(47)}"],
+ )
+
+ assert result.exit_code == 1
+ assert "Unexpected error: RuntimeError: boom" in result.output
+ assert "Full traceback written to" in result.output
+ log_dir = _log_dir(tmp_path)
+ assert log_dir.exists()
+ assert list(log_dir.iterdir())
diff --git a/tests/conftest.py b/tests/conftest.py
index ccecd13..70a3de9 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -61,6 +61,27 @@ def _scrub_ca_bundle_env(monkeypatch):
monkeypatch.delenv("REQUESTS_CA_BUNDLE", raising=False)
[email protected](autouse=True)
+def _isolate_cli_error_log_dir(monkeypatch, tmp_path):
+ """Redirect ``fli.cli.errors._LOG_DIR`` under ``tmp_path`` for every test.
+
+ ``_LOG_DIR`` is ``Path.home() / ".fli" / "logs"`` — a module-level
+ constant, read once at import time. Any test that exercises
+ ``report_cli_error`` / ``json_error_payload``, directly or indirectly
+ (a CLI command hitting an error path, a search helper whose error
+ surfaces through the CLI reporter), calls ``_write_log()``, which
+ creates that directory and drops a full traceback file into it. Left
+ unpatched, running the suite writes real files into the developer's
+ actual ``~/.fli/logs/`` on every run — tests must never touch that
+ directory. Autouse, suite-wide, so no test file has to remember to opt
+ in; a test whose assertions depend on the exact redirected path (e.g.
+ to check the directory is never created for a control-flow exit) can
+ still set its own ``monkeypatch.setattr("fli.cli.errors._LOG_DIR", ...)``
+ — defined closer to the test, it runs after this one and wins.
+ """
+ monkeypatch.setattr("fli.cli.errors._LOG_DIR", tmp_path / "fli-logs")
+
+
def pytest_addoption(parser) -> None:
"""Add options to pytest."""
parser.addoption("--fuzz", action="store_true", help="Run fuzz tests")