Skip to content

armgit / fli

Public Imported from GitHub
0

Google Flights MCP, CLI and Python Library

Add cli tests

Punit Aranif5737403acf8
diff --git a/tests/cli/__init__.py b/tests/cli/__init__.py
new file mode 100644
index 0000000..6bfb427
--- /dev/null
+++ b/tests/cli/__init__.py
@@ -0,0 +1 @@
+"""CLI test package."""
diff --git a/tests/cli/conftest.py b/tests/cli/conftest.py
new file mode 100644
index 0000000..5ca8ca8
--- /dev/null
+++ b/tests/cli/conftest.py
@@ -0,0 +1,80 @@
+from datetime import datetime, timedelta
+from unittest.mock import MagicMock
+
+import pytest
+
+from fli.models import (
+ Airline,
+ Airport,
+ FlightLeg,
+ FlightResult,
+)
+
+
+def mock_search_flights(monkeypatch):
+ """Mock the SearchFlights class."""
+ mock = MagicMock()
+ mock.search.return_value = [
+ FlightResult(
+ price=299.99,
+ duration=180,
+ stops=0,
+ legs=[
+ FlightLeg(
+ airline=Airline.DL,
+ flight_number="DL123",
+ departure_airport=Airport.JFK,
+ arrival_airport=Airport.LAX,
+ departure_datetime=datetime.now(),
+ arrival_datetime=datetime.now() + timedelta(hours=3),
+ duration=180,
+ )
+ ],
+ ),
+ FlightResult(
+ price=399.99,
+ duration=240,
+ stops=1,
+ legs=[
+ FlightLeg(
+ airline=Airline.UA,
+ flight_number="UA456",
+ departure_airport=Airport.JFK,
+ arrival_airport=Airport.ORD,
+ departure_datetime=datetime.now(),
+ arrival_datetime=datetime.now() + timedelta(hours=2),
+ duration=120,
+ ),
+ FlightLeg(
+ airline=Airline.UA,
+ flight_number="UA789",
+ departure_airport=Airport.ORD,
+ arrival_airport=Airport.LAX,
+ departure_datetime=datetime.now() + timedelta(hours=3),
+ arrival_datetime=datetime.now() + timedelta(hours=4),
+ duration=120,
+ ),
+ ],
+ ),
+ ]
+ monkeypatch.setattr("fli.search.flights.SearchFlights.__new__", lambda cls: mock)
+ monkeypatch.setattr("fli.search.SearchFlights.__new__", lambda cls: mock)
+ return mock
+
+
+def mock_search_dates(monkeypatch):
+ """Mock SearchDates class."""
+ mock = MagicMock()
+ monkeypatch.setattr("fli.search.dates.SearchDates.__new__", lambda cls: mock)
+ monkeypatch.setattr("fli.search.SearchDates.__new__", lambda cls: mock)
+ return mock
+
+
+def mock_console(monkeypatch):
+ """Mock the rich console to prevent output during tests."""
+ mock = MagicMock()
+ monkeypatch.setattr("fli.cli.utils.console", mock)
+ return mock
diff --git a/tests/cli/test_cheap.py b/tests/cli/test_cheap.py
new file mode 100644
index 0000000..731e7b7
--- /dev/null
+++ b/tests/cli/test_cheap.py
@@ -0,0 +1,173 @@
+from datetime import datetime, timedelta
+
+import pytest
+from typer.testing import CliRunner
+
+from fli.cli.main import app
+from fli.search import DatePrice
+
+
+def runner():
+ """Return a CliRunner instance."""
+ return CliRunner()
+
+
+def test_basic_cheap_search(runner, mock_search_dates, mock_console):
+ """Test basic cheap flight search."""
+ mock_search_dates.search.return_value = [
+ DatePrice(
+ date=(datetime.now() + timedelta(days=1),),
+ price=299.99,
+ ),
+ ]
+ result = runner.invoke(app, ["cheap", "JFK", "LAX"])
+ assert result.exit_code == 0
+ mock_search_dates.search.assert_called_once()
+
+
+def test_cheap_with_date_range(runner, mock_search_dates, mock_console):
+ """Test cheap search with custom date range."""
+ from_date = datetime.now().strftime("%Y-%m-%d")
+ to_date = (datetime.now() + timedelta(days=30)).strftime("%Y-%m-%d")
+
+ mock_search_dates.search.return_value = [
+ DatePrice(
+ date=(datetime.now() + timedelta(days=1),),
+ price=299.99,
+ ),
+ ]
+ result = runner.invoke(
+ app,
+ ["cheap", "JFK", "LAX", "--from", from_date, "--to", to_date],
+ )
+ assert result.exit_code == 0
+ mock_search_dates.search.assert_called_once()
+
+
+def test_cheap_with_days(runner, mock_search_dates, mock_console):
+ """Test cheap search with specific days."""
+ # Get next Monday
+ today = datetime.now()
+ days_until_monday = (7 - today.weekday()) % 7
+ next_monday = today + timedelta(days=days_until_monday)
+
+ mock_search_dates.search.return_value = [
+ DatePrice(
+ date=(next_monday,),
+ price=299.99,
+ ),
+ ]
+ result = runner.invoke(
+ app,
+ ["cheap", "JFK", "LAX", "--monday", "--friday"],
+ )
+ assert result.exit_code == 0
+ mock_search_dates.search.assert_called_once()
+
+
+def test_cheap_with_airlines(runner, mock_search_dates, mock_console):
+ """Test cheap search with airline filter."""
+ mock_search_dates.search.return_value = [
+ DatePrice(
+ date=(datetime.now() + timedelta(days=1),),
+ price=299.99,
+ ),
+ ]
+ result = runner.invoke(
+ app,
+ ["cheap", "JFK", "LAX", "-a", "DL", "-a", "UA"],
+ )
+ assert result.exit_code == 0
+ mock_search_dates.search.assert_called_once()
+
+
+def test_cheap_with_seat_type(runner, mock_search_dates, mock_console):
+ """Test cheap search with seat type."""
+ mock_search_dates.search.return_value = [
+ DatePrice(
+ date=(datetime.now() + timedelta(days=1),),
+ price=299.99,
+ ),
+ ]
+ result = runner.invoke(
+ app,
+ ["cheap", "JFK", "LAX", "--class", "BUSINESS"],
+ )
+ assert result.exit_code == 0
+ mock_search_dates.search.assert_called_once()
+
+
+def test_cheap_with_stops(runner, mock_search_dates, mock_console):
+ """Test cheap search with stops filter."""
+ mock_search_dates.search.return_value = [
+ DatePrice(
+ date=(datetime.now() + timedelta(days=1),),
+ price=299.99,
+ ),
+ ]
+ result = runner.invoke(
+ app,
+ ["cheap", "JFK", "LAX", "--stops", "NON_STOP"],
+ )
+ assert result.exit_code == 0
+ mock_search_dates.search.assert_called_once()
+
+
+def test_cheap_with_time(runner, mock_search_dates, mock_console):
+ """Test cheap search with time filter."""
+ mock_search_dates.search.return_value = [
+ DatePrice(
+ date=(datetime.now() + timedelta(days=1),),
+ price=299.99,
+ ),
+ ]
+ result = runner.invoke(
+ app,
+ ["cheap", "JFK", "LAX", "--time", "6-20"],
+ )
+ assert result.exit_code == 0
+ mock_search_dates.search.assert_called_once()
+
+
+def test_cheap_with_sort(runner, mock_search_dates, mock_console):
+ """Test cheap search with sort option."""
+ mock_search_dates.search.return_value = [
+ DatePrice(
+ date=(datetime.now() + timedelta(days=1),),
+ price=299.99,
+ ),
+ ]
+ result = runner.invoke(
+ app,
+ ["cheap", "JFK", "LAX", "--sort"],
+ )
+ assert result.exit_code == 0
+ mock_search_dates.search.assert_called_once()
+
+
+def test_cheap_invalid_airport(runner, mock_search_dates, mock_console):
+ """Test cheap search with invalid airport code."""
+ result = runner.invoke(app, ["cheap", "XXX", "LAX"])
+ assert result.exit_code == 1
+ assert "Error" in result.stdout
+
+
+def test_cheap_invalid_date_range(runner, mock_search_dates, mock_console):
+ """Test cheap search with invalid date range."""
+ result = runner.invoke(
+ app,
+ ["cheap", "JFK", "LAX", "--from", "2024-01-01", "--to", "2023-12-31"],
+ )
+ assert result.exit_code == 1
+ assert "Error" in result.stdout
+
+
+def test_cheap_no_results(runner, mock_search_dates, mock_console):
+ """Test cheap search with no results."""
+ # Override the mock to return an empty list
+ mock_search_dates.search.return_value = []
+
+ result = runner.invoke(app, ["cheap", "JFK", "LAX"])
+ assert result.exit_code == 1
+ assert "No flights found" in result.stdout
diff --git a/tests/cli/test_search.py b/tests/cli/test_search.py
new file mode 100644
index 0000000..e663b95
--- /dev/null
+++ b/tests/cli/test_search.py
@@ -0,0 +1,119 @@
+from datetime import datetime
+
+import pytest
+from typer.testing import CliRunner
+
+from fli.cli.main import app
+
+
+def runner():
+ """Return a CliRunner instance."""
+ return CliRunner()
+
+
+def test_basic_search(runner, mock_search_flights, mock_console):
+ """Test basic flight search with required parameters."""
+ result = runner.invoke(app, ["search", "JFK", "LAX", datetime.now().strftime("%Y-%m-%d")])
+ assert result.exit_code == 0
+ mock_search_flights.search.assert_called_once()
+
+
+def test_search_with_time_filter(runner, mock_search_flights, mock_console):
+ """Test search with time filter."""
+ result = runner.invoke(
+ app,
+ [
+ "search",
+ "JFK",
+ "LAX",
+ datetime.now().strftime("%Y-%m-%d"),
+ "--time",
+ "6-20",
+ ],
+ )
+ assert result.exit_code == 0
+ mock_search_flights.search.assert_called_once()
+
+
+def test_search_with_airlines(runner, mock_search_flights, mock_console):
+ """Test search with airline filter."""
+ result = runner.invoke(
+ app,
+ [
+ "search",
+ "JFK",
+ "LAX",
+ datetime.now().strftime("%Y-%m-%d"),
+ "-a",
+ "DL",
+ "-a",
+ "UA",
+ ],
+ )
+ assert result.exit_code == 0
+ mock_search_flights.search.assert_called_once()
+
+
+def test_search_with_seat_type(runner, mock_search_flights, mock_console):
+ """Test search with seat type."""
+ result = runner.invoke(
+ app,
+ [
+ "search",
+ "JFK",
+ "LAX",
+ datetime.now().strftime("%Y-%m-%d"),
+ "--class",
+ "BUSINESS",
+ ],
+ )
+ assert result.exit_code == 0
+ mock_search_flights.search.assert_called_once()
+
+
+def test_search_with_stops(runner, mock_search_flights, mock_console):
+ """Test search with stops filter."""
+ result = runner.invoke(
+ app,
+ [
+ "search",
+ "JFK",
+ "LAX",
+ datetime.now().strftime("%Y-%m-%d"),
+ "--stops",
+ "NON_STOP",
+ ],
+ )
+ assert result.exit_code == 0
+ mock_search_flights.search.assert_called_once()
+
+
+def test_search_invalid_airport(runner, mock_search_flights, mock_console):
+ """Test search with invalid airport code."""
+ result = runner.invoke(
+ app,
+ ["search", "XXX", "LAX", datetime.now().strftime("%Y-%m-%d")],
+ )
+ assert result.exit_code == 1
+ assert "Error" in result.stdout
+
+
+def test_search_invalid_date(runner, mock_search_flights, mock_console):
+ """Test search with invalid date format."""
+ result = runner.invoke(app, ["search", "JFK", "LAX", "2024-13-45"])
+ assert result.exit_code == 2
+ assert "Error" in result.stdout
+
+
+def test_search_no_results(runner, mock_search_flights, mock_console):
+ """Test search with no results."""
+ # Override the mock to return no results
+ mock_search_flights.search.return_value = []
+
+ result = runner.invoke(
+ app,
+ ["search", "JFK", "LAX", datetime.now().strftime("%Y-%m-%d")],
+ )
+ assert result.exit_code == 1
+ assert "No flights found" in result.stdout
diff --git a/tests/cli/test_utils.py b/tests/cli/test_utils.py
new file mode 100644
index 0000000..0f09c55
--- /dev/null
+++ b/tests/cli/test_utils.py
@@ -0,0 +1,188 @@
+from datetime import datetime, timedelta
+from unittest.mock import MagicMock
+
+import pytest
+from typer import BadParameter
+
+from fli.cli.enums import DayOfWeek
+from fli.cli.utils import (
+ filter_dates_by_days,
+ filter_flights_by_airlines,
+ filter_flights_by_time,
+ parse_airlines,
+ parse_stops,
+ validate_date,
+ validate_time_range,
+)
+from fli.models import Airline, Airport, FlightLeg, FlightResult, MaxStops
+from fli.models.google_flights.base import TripType
+from fli.search.dates import DatePrice
+
+
+def mock_context():
+ """Mock click Context."""
+ return MagicMock()
+
+
+def mock_param():
+ """Mock click Parameter."""
+ return MagicMock()
+
+
+def test_validate_date_valid(mock_context, mock_param):
+ """Test date validation with valid date."""
+ date = "2024-12-25"
+ result = validate_date(mock_context, mock_param, date)
+ assert result == date
+
+
+def test_validate_date_invalid(mock_context, mock_param):
+ """Test date validation with invalid date."""
+ with pytest.raises(BadParameter):
+ validate_date(mock_context, mock_param, "2024-13-45")
+
+
+def test_validate_time_range_valid(mock_context, mock_param):
+ """Test time range validation with valid range."""
+ time_range = "6-20"
+ result = validate_time_range(mock_context, mock_param, time_range)
+ assert result == (6, 20)
+
+
+def test_validate_time_range_invalid(mock_context, mock_param):
+ """Test time range validation with invalid range."""
+ with pytest.raises(BadParameter):
+ validate_time_range(mock_context, mock_param, "25-30")
+
+
+def test_validate_time_range_none(mock_context, mock_param):
+ """Test time range validation with None value."""
+ result = validate_time_range(mock_context, mock_param, None)
+ assert result is None
+
+
+def test_parse_stops_numeric():
+ """Test parsing stops with numeric values."""
+ assert parse_stops("0") == MaxStops.NON_STOP
+ assert parse_stops("1") == MaxStops.ONE_STOP_OR_FEWER
+ assert parse_stops("2") == MaxStops.TWO_OR_FEWER_STOPS
+
+
+def test_parse_stops_string():
+ """Test parsing stops with string values."""
+ assert parse_stops("NON_STOP") == MaxStops.NON_STOP
+ assert parse_stops("ANY") == MaxStops.ANY
+
+
+def test_parse_stops_invalid():
+ """Test parsing stops with invalid value."""
+ with pytest.raises(BadParameter):
+ parse_stops("INVALID")
+
+
+def test_parse_airlines_valid():
+ """Test parsing airlines with valid codes."""
+ result = parse_airlines(["DL", "UA"])
+ assert len(result) == 2
+ assert Airline.DL in result
+ assert Airline.UA in result
+
+
+def test_parse_airlines_none():
+ """Test parsing airlines with None value."""
+ result = parse_airlines(None)
+ assert result is None
+
+
+def test_parse_airlines_invalid():
+ """Test parsing airlines with invalid code."""
+ with pytest.raises(BadParameter):
+ parse_airlines(["INVALID"])
+
+
+def test_filter_flights_by_time():
+ """Test filtering flights by time range."""
+ now = datetime.now().replace(hour=10) # Set to 10 AM
+ flights = [
+ FlightResult(
+ price=100,
+ duration=120,
+ stops=0,
+ legs=[
+ FlightLeg(
+ airline=Airline.DL,
+ flight_number="DL123",
+ departure_airport=Airport.JFK,
+ arrival_airport=Airport.LAX,
+ departure_datetime=now,
+ arrival_datetime=now + timedelta(hours=2),
+ duration=120,
+ )
+ ],
+ )
+ ]
+
+ # Flight should be included (within range)
+ result = filter_flights_by_time(flights, 8, 12)
+ assert len(result) == 1
+
+ # Flight should be excluded (outside range)
+ result = filter_flights_by_time(flights, 12, 14)
+ assert len(result) == 0
+
+
+def test_filter_flights_by_airlines():
+ """Test filtering flights by airlines."""
+ now = datetime.now()
+ flights = [
+ FlightResult(
+ price=100,
+ duration=120,
+ stops=0,
+ legs=[
+ FlightLeg(
+ airline=Airline.DL,
+ flight_number="DL123",
+ departure_airport=Airport.JFK,
+ arrival_airport=Airport.LAX,
+ departure_datetime=now,
+ arrival_datetime=now + timedelta(hours=2),
+ duration=120,
+ )
+ ],
+ )
+ ]
+
+ # Flight should be included (matching airline)
+ result = filter_flights_by_airlines(flights, [Airline.DL])
+ assert len(result) == 1
+
+ # Flight should be excluded (non-matching airline)
+ result = filter_flights_by_airlines(flights, [Airline.UA])
+ assert len(result) == 0
+
+
+def test_filter_dates_by_days():
+ """Test filtering dates by days of the week."""
+ # Create a date that falls on a Monday
+ monday_date = datetime(2024, 1, 1) # January 1, 2024 was a Monday
+ dates = [
+ DatePrice(date=(monday_date,), price=100),
+ DatePrice(date=(monday_date.replace(day=2),), price=200), # Tuesday
+ ]
+
+ # Filter for Monday only
+ result = filter_dates_by_days(dates, [DayOfWeek.MONDAY], TripType.ONE_WAY)
+ assert len(result) == 1
+ assert result[0].date[0] == monday_date
+
+ # Filter for Tuesday only
+ result = filter_dates_by_days(dates, [DayOfWeek.TUESDAY], TripType.ONE_WAY)
+ assert len(result) == 1
+ assert result[0].date[0] == monday_date.replace(day=2)
+
+ # No day filters should return all dates
+ result = filter_dates_by_days(dates, [], TripType.ONE_WAY)
+ assert len(result) == 2