Google Flights MCP, CLI and Python Library
Add JSON output format to CLI (#77)
Punit Araniccf7ac9ffcaf
diff --git a/README.md b/README.mdindex 6d653ff..46bcc98 100644--- a/README.md+++ b/README.md@@ -144,6 +144,14 @@ fli flights JFK LHR 2025-10-25 \--sort DURATION # Sort by duration```+> ⚠️ **Experimental**+> `--format json` is experimental. The JSON schema may change while the machine-readable CLI contract settles.+>+> ```bash+> # Return machine-readable flight results+> fli flights JFK LHR 2025-10-25 --format json+> ```+### Find Cheapest Dates```bash@@ -157,6 +165,14 @@ fli dates JFK LHR \--monday --friday # Only Mondays and Fridays```+> ⚠️ **Experimental**+> `--format json` is experimental for date searches as well.+>+> ```bash+> # Return machine-readable date search results+> fli dates JFK LHR --from 2025-01-01 --to 2025-02-01 --format json+> ```+### CLI Options#### Flights Command (`fli flights`)@@ -168,6 +184,7 @@ fli dates JFK LHR \| `--class, -c` | Cabin class | `ECONOMY`, `BUSINESS` || `--stops, -s` | Maximum stops | `NON_STOP`, `ONE_STOP` || `--sort, -o` | Sort results by | `CHEAPEST`, `DURATION` |+| `--format` | Output format | `text`, `json` |#### Dates Command (`fli dates`)@@ -178,6 +195,7 @@ fli dates JFK LHR \| `--class, -c` | Cabin class | `ECONOMY`, `BUSINESS` || `--stops, -s` | Maximum stops | `NON_STOP`, `ONE_STOP` || `--[day]` | Day filters | `--monday`, `--friday` |+| `--format` | Output format | `text`, `json` |## MCP Server Integrationdiff --git a/docs/guides/quickstart.md b/docs/guides/quickstart.mdindex 73d7dec..7da7bac 100644--- a/docs/guides/quickstart.md+++ b/docs/guides/quickstart.md@@ -48,6 +48,17 @@ fli flights JFK LHR 2025-06-01 \fli dates JFK LHR --from 2025-06-01 --to 2025-06-30```+!!! warning "Experimental"+ `--format json` is experimental.+ The JSON schema is intended for agents and tools such as `jq`, but it may evolve in future releases.++5. Return machine-readable JSON:++```bash+fli flights JFK LHR 2025-06-01 --format json+fli dates JFK LHR --from 2025-06-01 --to 2025-06-30 --format json+```+### MCP Server (for AI Assistants)Run the MCP server for use with Claude Desktop or other MCP clients:diff --git a/docs/index.md b/docs/index.mdindex ba2b717..37a65c6 100644--- a/docs/index.md+++ b/docs/index.md@@ -28,6 +28,7 @@ flights and analyze pricing data.* Various cabin classes* Stop preferences* Custom result sorting+* Experimental JSON CLI output for agents and tools like `jq`### 💰 Price Analysis@@ -62,6 +63,16 @@ See the [MCP Guide](guides/mcp.md) for Claude Desktop configuration.### Basic Usage+### CLI JSON Output++!!! warning "Experimental"+ The `--format json` CLI output is experimental. The schema is intended for agents and tools such as `jq`, but may evolve in future releases.++```bash+fli flights JFK LHR 2025-06-01 --format json+fli dates JFK LHR --from 2025-06-01 --to 2025-06-30 --format json+```+```pythonfrom datetime import datetime, timedeltafrom fli.models import (diff --git a/fli/cli/commands/dates.py b/fli/cli/commands/dates.pyindex fbccc76..baf5321 100644--- a/fli/cli/commands/dates.py+++ b/fli/cli/commands/dates.py@@ -5,12 +5,16 @@ from typing import Annotatedimport typer-from fli.cli.enums import DayOfWeek+from fli.cli.enums import DayOfWeek, OutputFormatfrom fli.cli.utils import (+ build_json_error_response,+ build_json_success_response,display_date_results,+ emit_json,filter_dates_by_days,- validate_date,- validate_time_range,+ normalize_cli_date,+ normalize_cli_time_range,+ serialize_date_result,)from fli.core import (build_date_search_segments,@@ -29,16 +33,45 @@ from fli.models import (from fli.search import SearchDates+def _build_selected_days(+ *,+ monday: bool,+ tuesday: bool,+ wednesday: bool,+ thursday: bool,+ friday: bool,+ saturday: bool,+ sunday: bool,+) -> list[DayOfWeek]:+ """Build the selected day filters list."""+ selected_days = []+ if monday:+ selected_days.append(DayOfWeek.MONDAY)+ if tuesday:+ selected_days.append(DayOfWeek.TUESDAY)+ if wednesday:+ selected_days.append(DayOfWeek.WEDNESDAY)+ if thursday:+ selected_days.append(DayOfWeek.THURSDAY)+ if friday:+ selected_days.append(DayOfWeek.FRIDAY)+ if saturday:+ selected_days.append(DayOfWeek.SATURDAY)+ if sunday:+ selected_days.append(DayOfWeek.SUNDAY)+ return selected_days++def dates(origin: Annotated[str, typer.Argument(help="Departure airport IATA code (e.g., JFK)")],destination: Annotated[str, typer.Argument(help="Arrival airport IATA code (e.g., LHR)")],start_date: Annotated[str,- typer.Option("--from", help="Start date (YYYY-MM-DD)", callback=validate_date),+ typer.Option("--from", help="Start date (YYYY-MM-DD)"),] = (datetime.now() + timedelta(days=1)).strftime("%Y-%m-%d"),- end_date: Annotated[- str, typer.Option("--to", help="End date (YYYY-MM-DD)", callback=validate_date)- ] = (datetime.now() + timedelta(days=60)).strftime("%Y-%m-%d"),+ end_date: Annotated[str, typer.Option("--to", help="End date (YYYY-MM-DD)")] = (+ datetime.now() + timedelta(days=60)+ ).strftime("%Y-%m-%d"),trip_duration: Annotated[int,typer.Option(@@ -148,9 +181,16 @@ def dates("--time","-time",help="Departure time window in 24h format (e.g., 6-20)",- callback=validate_time_range,),] = None,+ output_format: Annotated[+ OutputFormat,+ typer.Option(+ "--format",+ help="Output format",+ case_sensitive=False,+ ),+ ] = OutputFormat.TEXT,):"""Find the cheapest dates to fly between two airports.@@ -159,6 +199,10 @@ def dates("""try:+ start_date = normalize_cli_date(start_date)+ end_date = normalize_cli_date(end_date)+ departure_window = normalize_cli_time_range(departure_window)+# Parse parameters using shared utilitiesorigin_airport = resolve_airport(origin)destination_airport = resolve_airport(destination)@@ -166,14 +210,36 @@ def dates(stops = parse_max_stops(max_stops)seat_type = parse_cabin_class(cabin_class)parsed_airlines = parse_airlines(airlines)+ selected_days = _build_selected_days(+ monday=monday,+ tuesday=tuesday,+ wednesday=wednesday,+ thursday=thursday,+ friday=friday,+ saturday=saturday,+ sunday=sunday,+ )+ query = {+ "origin": origin_airport.name,+ "destination": destination_airport.name,+ "start_date": start_date,+ "end_date": end_date,+ "trip_duration": trip_duration,+ "is_round_trip": is_round_trip,+ "cabin_class": seat_type.name,+ "max_stops": stops.name,+ "departure_window": (+ f"{departure_window[0]}-{departure_window[1]}" if departure_window else None+ ),+ "airlines": [airline.name for airline in parsed_airlines] if parsed_airlines else None,+ "sort_by_price": sort_by_price,+ "days": [day.value for day in selected_days],+ }# Build time restrictions from tupletime_restrictions = Noneif departure_window:- if isinstance(departure_window, tuple):- start_hour, end_hour = departure_window- else:- start_hour, end_hour = map(int, departure_window.split("-"))+ start_hour, end_hour = departure_windowtime_restrictions = TimeRestrictions(earliest_departure=start_hour,latest_departure=end_hour,@@ -209,45 +275,118 @@ def dates(results = search_client.search(filters)if not results:- typer.echo("No flights found for these dates.")- raise typer.Exit(1)-- # Filter by days if any day filters are specified- selected_days = []- if monday:- selected_days.append(DayOfWeek.MONDAY)- if tuesday:- selected_days.append(DayOfWeek.TUESDAY)- if wednesday:- selected_days.append(DayOfWeek.WEDNESDAY)- if thursday:- selected_days.append(DayOfWeek.THURSDAY)- if friday:- selected_days.append(DayOfWeek.FRIDAY)- if saturday:- selected_days.append(DayOfWeek.SATURDAY)- if sunday:- selected_days.append(DayOfWeek.SUNDAY)+ results = []if selected_days:results = filter_dates_by_days(results, selected_days, trip_type)- if not results:- typer.echo("No flights found for the selected days.")- raise typer.Exit(1)-# Sort dates by price if sort flag is enabledif sort_by_price:results.sort(key=lambda x: x.price)- # Display results+ if output_format == OutputFormat.JSON:+ emit_json(+ build_json_success_response(+ search_type="dates",+ trip_type=trip_type,+ query=query,+ results_key="dates",+ results=[serialize_date_result(result, trip_type) for result in results],+ )+ )+ return++ if not results:+ message = (+ "No flights found for the selected days."+ if selected_days+ else "No flights found for these dates."+ )+ typer.echo(message)+ raise typer.Exit(1)+display_date_results(results, trip_type)except ParseError as e:+ if output_format == OutputFormat.JSON:+ emit_json(+ build_json_error_response(+ search_type="dates",+ message=str(e),+ query={+ "origin": origin,+ "destination": destination,+ "start_date": start_date,+ "end_date": end_date,+ "trip_duration": trip_duration,+ "is_round_trip": is_round_trip,+ "cabin_class": cabin_class,+ "max_stops": max_stops,+ "departure_window": (+ f"{departure_window[0]}-{departure_window[1]}"+ if isinstance(departure_window, tuple)+ else departure_window+ ),+ "airlines": airlines,+ "sort_by_price": sort_by_price,+ "days": [+ day.value+ for day in _build_selected_days(+ monday=monday,+ tuesday=tuesday,+ wednesday=wednesday,+ thursday=thursday,+ friday=friday,+ saturday=saturday,+ sunday=sunday,+ )+ ],+ },+ )+ )+ raise typer.Exit(1) from etyper.echo(f"Error: {str(e)}")raise typer.Exit(1) from eexcept (AttributeError, ValueError) as e:if "module 'fli.search' has no attribute 'SearchDates'" in str(e):raise+ if output_format == OutputFormat.JSON:+ emit_json(+ build_json_error_response(+ search_type="dates",+ message=str(e),+ error_type="search_error",+ query={+ "origin": origin,+ "destination": destination,+ "start_date": start_date,+ "end_date": end_date,+ "trip_duration": trip_duration,+ "is_round_trip": is_round_trip,+ "cabin_class": cabin_class,+ "max_stops": max_stops,+ "departure_window": (+ f"{departure_window[0]}-{departure_window[1]}"+ if isinstance(departure_window, tuple)+ else departure_window+ ),+ "airlines": airlines,+ "sort_by_price": sort_by_price,+ "days": [+ day.value+ for day in _build_selected_days(+ monday=monday,+ tuesday=tuesday,+ wednesday=wednesday,+ thursday=thursday,+ friday=friday,+ saturday=saturday,+ sunday=sunday,+ )+ ],+ },+ )+ )+ raise typer.Exit(1) from etyper.echo(f"Error: {str(e)}")raise typer.Exit(1) from ediff --git a/fli/cli/commands/flights.py b/fli/cli/commands/flights.pyindex b8c99e3..afcc20a 100644--- a/fli/cli/commands/flights.py+++ b/fli/cli/commands/flights.py@@ -1,10 +1,19 @@"""Flight search CLI command."""-from typing import Annotated+from typing import Annotated, Anyimport typer-from fli.cli.utils import display_flight_results, validate_date, validate_time_range+from fli.cli.enums import OutputFormat+from fli.cli.utils import (+ build_json_error_response,+ build_json_success_response,+ display_flight_results,+ emit_json,+ normalize_cli_date,+ normalize_cli_time_range,+ serialize_flight_result,+)from fli.core import (build_flight_segments,parse_airlines,@@ -26,14 +35,36 @@ def _search_flights_core(destination: str,departure_date: str,return_date: str | None = None,- departure_window: tuple[int, int] | None = None,+ departure_window: str | tuple[int, int] | None = None,airlines: list[str] | None = None,cabin_class: str = "ECONOMY",max_stops: str = "ANY",sort_by: str = "CHEAPEST",-):+ output_format: OutputFormat = OutputFormat.TEXT,+) -> None:"""Core flight search functionality."""+ query: dict[str, Any] = {+ "origin": origin.upper(),+ "destination": destination.upper(),+ "departure_date": departure_date,+ "return_date": return_date,+ "departure_window": None,+ "airlines": [airline.upper() for airline in airlines] if airlines else None,+ "cabin_class": cabin_class.upper(),+ "max_stops": max_stops.upper(),+ "sort_by": sort_by.upper(),+ }+try:+ departure_date = normalize_cli_date(departure_date)+ return_date = normalize_cli_date(return_date)+ departure_window = normalize_cli_time_range(departure_window)+ query["departure_date"] = departure_date+ query["return_date"] = return_date+ query["departure_window"] = (+ f"{departure_window[0]}-{departure_window[1]}" if departure_window else None+ )+# Parse parameters using shared utilitiesorigin_airport = resolve_airport(origin)destination_airport = resolve_airport(destination)@@ -77,16 +108,60 @@ def _search_flights_core(results = search_client.search(filters)if not results:+ if output_format == OutputFormat.JSON:+ emit_json(+ build_json_success_response(+ search_type="flights",+ trip_type=trip_type,+ query=query,+ results_key="flights",+ results=[],+ )+ )+ return+typer.echo("No flights found.")raise typer.Exit(1)- # Display results+ if output_format == OutputFormat.JSON:+ emit_json(+ build_json_success_response(+ search_type="flights",+ trip_type=trip_type,+ query=query,+ results_key="flights",+ results=[serialize_flight_result(result) for result in results],+ )+ )+ return+display_flight_results(results)except ParseError as e:+ if output_format == OutputFormat.JSON:+ emit_json(+ build_json_error_response(+ search_type="flights",+ message=str(e),+ query=query,+ )+ )+ raise typer.Exit(1) from e+typer.echo(f"Error: {str(e)}")raise typer.Exit(1) from eexcept (AttributeError, ValueError) as e:+ if output_format == OutputFormat.JSON:+ emit_json(+ build_json_error_response(+ search_type="flights",+ message=str(e),+ error_type="search_error",+ query=query,+ )+ )+ raise typer.Exit(1) from e+typer.echo(f"Error: {str(e)}")raise typer.Exit(1) from e@@ -94,16 +169,13 @@ def _search_flights_core(def flights(origin: Annotated[str, typer.Argument(help="Departure airport IATA code (e.g., JFK)")],destination: Annotated[str, typer.Argument(help="Arrival airport IATA code (e.g., LHR)")],- departure_date: Annotated[- str, typer.Argument(help="Travel date (YYYY-MM-DD)", callback=validate_date)- ],+ departure_date: Annotated[str, typer.Argument(help="Travel date (YYYY-MM-DD)")],return_date: Annotated[str | None,typer.Option("--return","-r",help="Return date (YYYY-MM-DD)",- callback=validate_date,),] = None,departure_window: Annotated[@@ -112,7 +184,6 @@ def flights("--time","-t",help="Departure time window in 24h format (e.g., 6-20)",- callback=validate_time_range,),] = None,airlines: Annotated[@@ -147,11 +218,20 @@ def flights(help="Sort results by (CHEAPEST, DURATION, DEPARTURE_TIME, ARRIVAL_TIME)",),] = "CHEAPEST",+ output_format: Annotated[+ OutputFormat,+ typer.Option(+ "--format",+ help="Output format: text or json",+ case_sensitive=False,+ ),+ ] = OutputFormat.TEXT,):"""Search for flights on a specific date.Example:fli flights JFK LHR 2025-10-25 --time 6-20 --airlines BA KL --stops NON_STOP+ fli flights JFK LHR 2025-10-25 --format json"""_search_flights_core(@@ -164,4 +244,5 @@ def flights(cabin_class=cabin_class,max_stops=max_stops,sort_by=sort_by,+ output_format=output_format,)diff --git a/fli/cli/enums.py b/fli/cli/enums.pyindex fc7315c..451efc6 100644--- a/fli/cli/enums.py+++ b/fli/cli/enums.py@@ -11,3 +11,10 @@ class DayOfWeek(Enum):FRIDAY = "friday"SATURDAY = "saturday"SUNDAY = "sunday"+++class OutputFormat(str, Enum):+ """Supported CLI output formats."""++ TEXT = "text"+ JSON = "json"diff --git a/fli/cli/utils.py b/fli/cli/utils.pyindex ed3aafe..d561a19 100644--- a/fli/cli/utils.py+++ b/fli/cli/utils.py@@ -1,5 +1,8 @@"""CLI utility functions for display and validation."""+import json+from typing import Any+import plotext as pltimport typerfrom click import Context, Parameter@@ -17,6 +20,8 @@ from fli.core.parsers import parse_airlines as core_parse_airlinesfrom fli.core.parsers import parse_max_stops as core_parse_max_stopsfrom fli.models import Airline, Airport, MaxStops, TripType+DEFAULT_CURRENCY = "USD"+def validate_date(ctx: Context, param: Parameter, value: str) -> str | None:"""Validate date format for typer callbacks."""@@ -45,6 +50,36 @@ def validate_time_range(raise typer.BadParameter("Time range must be in format 'start-end' (e.g., 6-20)") from e+def normalize_cli_date(value: str | None) -> str | None:+ """Normalize a CLI date value or raise a parse error."""+ if value is None:+ return None++ try:+ return normalize_date(value)+ except ValueError as e:+ raise ParseError("Date must be in YYYY-MM-DD format") from e+++def normalize_cli_time_range(value: str | tuple[int, int] | None) -> tuple[int, int] | None:+ """Normalize a CLI time range or raise a parse error."""+ if value is None:+ return None++ if isinstance(value, tuple):+ start, end = value+ else:+ try:+ start, end = map(int, value.split("-"))+ except ValueError as e:+ raise ParseError("Time range must be in format 'start-end' (e.g., 6-20)") from e++ if not (0 <= start <= 23 and 0 <= end <= 23):+ raise ParseError("Time range must be in format 'start-end' (e.g., 6-20)")++ return start, end++def parse_airlines(airlines: list[str] | None) -> list[Airline] | None:"""Parse airlines from list of airline codes.@@ -128,6 +163,118 @@ def format_duration(minutes: int) -> str:return f"{hours}h {mins}m"+def serialize_airport(airport: Airport) -> dict[str, str]:+ """Serialize an airport for machine-readable output."""+ return {"code": airport.name, "name": airport.value}+++def serialize_airline(airline: Airline) -> dict[str, str]:+ """Serialize an airline for machine-readable output."""+ return {"code": airline.name, "name": airline.value}+++def serialize_flight_leg(leg: Any) -> dict[str, Any]:+ """Serialize a flight leg using Google Flights-style field names."""+ return {+ "departure_airport": serialize_airport(leg.departure_airport),+ "arrival_airport": serialize_airport(leg.arrival_airport),+ "departure_time": leg.departure_datetime.isoformat(),+ "arrival_time": leg.arrival_datetime.isoformat(),+ "duration": leg.duration,+ "airline": serialize_airline(leg.airline),+ "flight_number": leg.flight_number,+ }+++def _serialize_flight_segment_result(flight: Any, *, include_price: bool = False) -> dict[str, Any]:+ """Serialize a one-direction flight result."""+ payload = {+ "duration": flight.duration,+ "stops": flight.stops,+ "legs": [serialize_flight_leg(leg) for leg in flight.legs],+ }+ if include_price:+ payload["price"] = flight.price+ payload["currency"] = DEFAULT_CURRENCY+ return payload+++def serialize_flight_result(flight_data: Any) -> dict[str, Any]:+ """Serialize a flight result or round-trip pair for JSON output."""+ if isinstance(flight_data, tuple):+ outbound, return_flight = flight_data+ return {+ "price": outbound.price,+ "currency": DEFAULT_CURRENCY,+ "duration": outbound.duration + return_flight.duration,+ "stops": outbound.stops + return_flight.stops,+ "outbound": _serialize_flight_segment_result(outbound),+ "return": _serialize_flight_segment_result(return_flight),+ }++ return _serialize_flight_segment_result(flight_data, include_price=True)+++def serialize_date_result(date_result: Any, trip_type: TripType) -> dict[str, Any]:+ """Serialize a date search result for JSON output."""+ payload = {+ "departure_date": date_result.date[0].date().isoformat(),+ "return_date": None,+ "price": date_result.price,+ "currency": DEFAULT_CURRENCY,+ }+ if trip_type == TripType.ROUND_TRIP and len(date_result.date) > 1:+ payload["return_date"] = date_result.date[1].date().isoformat()+ return payload+++def build_json_success_response(+ *,+ search_type: str,+ trip_type: TripType,+ query: dict[str, Any],+ results_key: str,+ results: list[dict[str, Any]],+) -> dict[str, Any]:+ """Build a JSON success payload for CLI commands."""+ return {+ "success": True,+ "data_source": "google_flights",+ "search_type": search_type,+ "trip_type": trip_type.name,+ "query": query,+ "count": len(results),+ results_key: results,+ }+++def build_json_error_response(+ *,+ search_type: str,+ message: str,+ error_type: str = "validation_error",+ query: dict[str, Any] | None = None,+) -> dict[str, Any]:+ """Build a JSON error payload for CLI commands."""+ payload = {+ "success": False,+ "data_source": "google_flights",+ "search_type": search_type,+ "error": {+ "type": error_type,+ "message": message,+ },+ }+ if query is not None:+ payload["query"] = query+ return payload+++def emit_json(payload: dict[str, Any]) -> None:+ """Emit a JSON payload to stdout."""+ typer.echo(json.dumps(payload, indent=2))++def display_flight_results(flights: list):"""Display flight results in a beautiful format.diff --git a/tests/cli/test_dates.py b/tests/cli/test_dates.pyindex 162625c..22ba94d 100644--- a/tests/cli/test_dates.py+++ b/tests/cli/test_dates.py@@ -1,5 +1,6 @@"""Tests for the dates CLI command."""+import jsonfrom datetime import datetime, timedeltaimport pytest@@ -217,3 +218,63 @@ def test_dates_round_trip_with_duration(runner, mock_search_dates, mock_console)args, _ = mock_search_dates.search.call_argsassert args[0].trip_type == TripType.ROUND_TRIPassert args[0].duration == 14+++def test_dates_json_output(runner, mock_search_dates, mock_console):+ """Test dates search JSON output."""+ departure_date = datetime.now() + timedelta(days=1)+ return_date = departure_date + timedelta(days=7)+ mock_search_dates.search.return_value = [+ DatePrice(+ date=(departure_date, return_date),+ price=599.98,+ )+ ]++ result = runner.invoke(+ app,+ ["dates", "JFK", "LAX", "--round", "--format", "json"],+ )++ assert result.exit_code == 0+ payload = json.loads(result.stdout)+ assert payload["success"] is True+ assert payload["search_type"] == "dates"+ assert payload["trip_type"] == "ROUND_TRIP"+ assert payload["count"] == 1+ assert payload["query"]["is_round_trip"] is True+ assert payload["dates"][0]["departure_date"] == departure_date.date().isoformat()+ assert payload["dates"][0]["return_date"] == return_date.date().isoformat()+ assert payload["dates"][0]["price"] == 599.98+ assert payload["dates"][0]["currency"] == "USD"+++def test_dates_json_invalid_date(runner, mock_search_dates, mock_console):+ """Test dates JSON output for invalid date input."""+ result = runner.invoke(+ app,+ ["dates", "JFK", "LAX", "--from", "2024-13-45", "--format", "json"],+ )++ assert result.exit_code == 1+ payload = json.loads(result.stdout)+ assert payload["success"] is False+ assert payload["search_type"] == "dates"+ assert payload["error"]["type"] == "validation_error"+ assert payload["error"]["message"] == "Date must be in YYYY-MM-DD format"+++def test_dates_json_empty_results(runner, mock_search_dates, mock_console):+ """Test dates JSON output when no results are found."""+ mock_search_dates.search.return_value = []++ result = runner.invoke(+ app,+ ["dates", "JFK", "LAX", "--format", "json"],+ )++ assert result.exit_code == 0+ payload = json.loads(result.stdout)+ assert payload["success"] is True+ assert payload["count"] == 0+ assert payload["dates"] == []diff --git a/tests/cli/test_flights.py b/tests/cli/test_flights.pyindex e9a8c65..3418a9c 100644--- a/tests/cli/test_flights.py+++ b/tests/cli/test_flights.py@@ -1,11 +1,13 @@"""Tests for the flights CLI command."""+import jsonfrom datetime import datetime, timedeltaimport pytestfrom typer.testing import CliRunnerfrom fli.cli.main import app+from fli.models import Airline, Airport, FlightLeg, FlightResultfrom fli.models.google_flights.base import TripType@@ -105,7 +107,7 @@ def test_flights_invalid_airport(runner, mock_search_flights, mock_console):def test_flights_invalid_date(runner, mock_search_flights, mock_console):"""Test flights search with invalid date format."""result = runner.invoke(app, ["flights", "JFK", "LAX", "2024-13-45"])- assert result.exit_code == 2+ assert result.exit_code == 1assert "Error" in result.output@@ -187,3 +189,121 @@ def test_round_trip_invalid_dates(runner, mock_search_flights, mock_console):)assert result.exit_code == 1assert "Error" in result.stdout+++def test_flights_json_output(runner, mock_search_flights, mock_console):+ """Test flights search with JSON output."""+ result = runner.invoke(+ app,+ ["flights", "JFK", "LAX", datetime.now().strftime("%Y-%m-%d"), "--format", "json"],+ )++ assert result.exit_code == 0+ payload = json.loads(result.stdout)+ assert payload["success"] is True+ assert payload["data_source"] == "google_flights"+ assert payload["search_type"] == "flights"+ assert payload["trip_type"] == "ONE_WAY"+ assert payload["count"] == 2+ assert payload["query"]["origin"] == "JFK"+ assert payload["query"]["destination"] == "LAX"+ assert payload["flights"][0]["price"] == 299.99+ assert payload["flights"][0]["currency"] == "USD"+ assert payload["flights"][0]["legs"][0]["departure_airport"]["code"] == "JFK"+ assert payload["flights"][0]["legs"][0]["arrival_airport"]["code"] == "LAX"+++def test_flights_json_round_trip_output(runner, mock_search_flights, mock_console):+ """Test round-trip flights JSON output preserves outbound and return sections."""+ now = datetime.now()+ mock_search_flights.search.return_value = [+ (+ FlightResult(+ price=599.98,+ duration=180,+ 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=3),+ duration=180,+ )+ ],+ ),+ FlightResult(+ price=599.98,+ duration=200,+ stops=1,+ legs=[+ FlightLeg(+ airline=Airline.DL,+ flight_number="DL456",+ departure_airport=Airport.LAX,+ arrival_airport=Airport.JFK,+ departure_datetime=now + timedelta(days=7),+ arrival_datetime=now + timedelta(days=7, hours=4),+ duration=200,+ )+ ],+ ),+ )+ ]++ result = runner.invoke(+ app,+ [+ "flights",+ "JFK",+ "LAX",+ now.strftime("%Y-%m-%d"),+ "--return",+ (now + timedelta(days=7)).strftime("%Y-%m-%d"),+ "--format",+ "json",+ ],+ )++ assert result.exit_code == 0+ payload = json.loads(result.stdout)+ assert payload["trip_type"] == "ROUND_TRIP"+ assert payload["count"] == 1+ assert payload["flights"][0]["price"] == 599.98+ assert payload["flights"][0]["duration"] == 380+ assert payload["flights"][0]["stops"] == 1+ assert payload["flights"][0]["outbound"]["legs"][0]["flight_number"] == "DL123"+ assert payload["flights"][0]["return"]["legs"][0]["flight_number"] == "DL456"+++def test_flights_json_invalid_date(runner, mock_search_flights, mock_console):+ """Test flights JSON output for invalid dates."""+ result = runner.invoke(+ app,+ ["flights", "JFK", "LAX", "2024-13-45", "--format", "json"],+ )++ assert result.exit_code == 1+ payload = json.loads(result.stdout)+ assert payload["success"] is False+ assert payload["search_type"] == "flights"+ assert payload["error"]["type"] == "validation_error"+ assert "YYYY-MM-DD" in payload["error"]["message"]+++def test_flights_json_no_results(runner, mock_search_flights, mock_console):+ """Test flights JSON output when no results are found."""+ mock_search_flights.search.return_value = []++ result = runner.invoke(+ app,+ ["flights", "JFK", "LAX", datetime.now().strftime("%Y-%m-%d"), "--format", "json"],+ )++ assert result.exit_code == 0+ payload = json.loads(result.stdout)+ assert payload["success"] is True+ assert payload["count"] == 0+ assert payload["flights"] == []diff --git a/tests/cli/test_utils.py b/tests/cli/test_utils.pyindex be6ec80..73b1748 100644--- a/tests/cli/test_utils.py+++ b/tests/cli/test_utils.py@@ -14,6 +14,8 @@ from fli.cli.utils import (filter_flights_by_time,parse_airlines,parse_stops,+ serialize_date_result,+ serialize_flight_result,validate_date,validate_time_range,)@@ -259,3 +261,45 @@ def test_display_round_trip_price_asymmetric():assert "$400.00" in outputassert "$750.00" not in output+++def test_serialize_flight_result_one_way():+ """JSON flight serialization should use machine-readable nested fields."""+ flight = _make_flight_result(price=159.0)++ payload = serialize_flight_result(flight)++ assert payload["price"] == 159.0+ assert payload["currency"] == "USD"+ assert payload["legs"][0]["departure_airport"]["code"] == "JFK"+ assert payload["legs"][0]["airline"]["code"] == "DL"+++def test_serialize_flight_result_round_trip():+ """Round-trip JSON serialization should expose outbound and return segments."""+ outbound = _make_flight_result(price=317.0, flight_number="DL100")+ return_flight = _make_flight_result(price=317.0, flight_number="DL200")++ payload = serialize_flight_result((outbound, return_flight))++ assert payload["price"] == 317.0+ assert payload["currency"] == "USD"+ assert payload["outbound"]["legs"][0]["flight_number"] == "DL100"+ assert payload["return"]["legs"][0]["flight_number"] == "DL200"+++def test_serialize_date_result_round_trip():+ """Date serialization should include the return date for round-trip searches."""+ result = DatePrice(+ date=(datetime(2026, 5, 1), datetime(2026, 5, 8)),+ price=599.98,+ )++ payload = serialize_date_result(result, TripType.ROUND_TRIP)++ assert payload == {+ "departure_date": "2026-05-01",+ "return_date": "2026-05-08",+ "price": 599.98,+ "currency": "USD",+ }