Google Flights MCP, CLI and Python Library
Improve google flights filter validation
Punit Arani52ca1c65115c
diff --git a/fli/models/google_flights.py b/fli/models/google_flights.pyindex 4226984..7f2dd2a 100644--- a/fli/models/google_flights.py+++ b/fli/models/google_flights.py@@ -9,7 +9,15 @@ import urllib.parsefrom datetime import datetimefrom enum import Enum-from pydantic import BaseModel, NonNegativeFloat, NonNegativeInt, PositiveInt+from pydantic import (+ BaseModel,+ NonNegativeFloat,+ NonNegativeInt,+ PositiveInt,+ ValidationInfo,+ field_validator,+ model_validator,+)from .airline import Airlinefrom .airport import Airport@@ -72,6 +80,25 @@ class TimeRestrictions(BaseModel):earliest_arrival: NonNegativeInt | None = Nonelatest_arrival: PositiveInt | None = None+ @field_validator("latest_departure", "latest_arrival")+ @classmethod+ def validate_latest_times(+ cls, v: PositiveInt | None, info: ValidationInfo+ ) -> PositiveInt | None:+ """Validate and adjust the latest time restrictions."""+ if v is None:+ return v++ # Get "departure" or "arrival" from field name+ field_prefix = "earliest_" + info.field_name[7:]+ earliest = info.data.get(field_prefix)++ # Swap values to ensure that `from` is always before `to`+ if earliest is not None and earliest > v:+ info.data[field_prefix] = v+ return earliest+ return v+class PassengerInfo(BaseModel):"""Passenger configuration for flight search."""@@ -109,6 +136,40 @@ class FlightSegment(BaseModel):travel_date: strtime_restrictions: TimeRestrictions | None = None+ @property+ def parsed_travel_date(self) -> datetime:+ """Parse the travel date string into a datetime object."""+ return datetime.strptime(self.travel_date, "%Y-%m-%d")++ @field_validator("travel_date")+ @classmethod+ def validate_travel_date(cls, v: str) -> str:+ """Validate that the travel date is not in the past."""+ travel_date = datetime.strptime(v, "%Y-%m-%d").date()+ if travel_date < datetime.now().date():+ raise ValueError("Travel date cannot be in the past")+ return v++ @model_validator(mode="after")+ def validate_airports(self) -> "FlightSegment":+ """Validate that departure and arrival airports are different."""+ if not self.departure_airport or not self.arrival_airport:+ raise ValueError("Both departure and arrival airports must be specified")++ # Get first airport from each nested list+ dep_airport = (+ self.departure_airport[0][0]+ if isinstance(self.departure_airport[0][0], Airport)+ else None+ )+ arr_airport = (+ self.arrival_airport[0][0] if isinstance(self.arrival_airport[0][0], Airport) else None+ )++ if dep_airport and arr_airport and dep_airport == arr_airport:+ raise ValueError("Departure and arrival airports must be different")+ return self+class FlightLeg(BaseModel):"""A single flight leg (segment) with airline and timing details."""@@ -306,6 +367,61 @@ class DateSearchFilters(BaseModel):from_date: strto_date: str+ @property+ def parsed_from_date(self) -> datetime:+ """Parse the from_date string into a datetime object."""+ return datetime.strptime(self.from_date, "%Y-%m-%d")++ @property+ def parsed_to_date(self) -> datetime:+ """Parse the to_date string into a datetime object."""+ return datetime.strptime(self.to_date, "%Y-%m-%d")++ @field_validator("from_date", "to_date")+ @classmethod+ def validate_date_order(cls, v: str, info: ValidationInfo) -> str:+ """Validate and adjust the date range constraints."""+ if info.field_name == "from_date":+ # If from_date is in the past, set it to today+ from_date = datetime.strptime(v, "%Y-%m-%d").date()+ if from_date < datetime.now().date():+ return datetime.now().date().strftime("%Y-%m-%d")+ return v++ # For to_date, check if it's after from_date+ if "from_date" in info.data:+ from_date = datetime.strptime(info.data["from_date"], "%Y-%m-%d").date()+ to_date = datetime.strptime(v, "%Y-%m-%d").date()+ if from_date > to_date:+ # Swap dates by returning the from_date+ info.data["from_date"] = v+ return from_date.strftime("%Y-%m-%d")+ return v++ @field_validator("to_date")+ @classmethod+ def validate_to_date(cls, v: str) -> str:+ """Validate that to_date is in the future."""+ to_date = datetime.strptime(v, "%Y-%m-%d").date()+ if to_date <= datetime.now().date():+ raise ValueError("To date must be in the future")+ return v++ @model_validator(mode="after")+ def validate_segments_within_range(self) -> "DateSearchFilters":+ """Validate that flight segments' travel dates are within the search range."""+ from_date = self.parsed_from_date.date()+ to_date = self.parsed_to_date.date()++ for segment in self.flight_segments:+ segment_date = segment.parsed_travel_date.date()+ if not (from_date <= segment_date <= to_date):+ raise ValueError(+ f"Flight segment travel date {segment.travel_date} "+ f"must be within the search date range"+ )+ return self+def format(self) -> list:"""Format filters into Google Flights API structure.diff --git a/tests/models/test_date_search_filters_validation.py b/tests/models/test_date_search_filters_validation.pynew file mode 100644index 0000000..34c4c31--- /dev/null+++ b/tests/models/test_date_search_filters_validation.py@@ -0,0 +1,160 @@+"""Tests for DateSearchFilters validation and auto-correction."""++from datetime import datetime, timedelta++import pytest++from fli.models import (+ Airport,+ DateSearchFilters,+ FlightSegment,+ MaxStops,+ PassengerInfo,+ SeatType,+)+++def future_date():+ """Get a date 30 days in the future."""+ return datetime.now() + timedelta(days=30)+++def basic_search_params(future_date):+ """Create basic search params for testing."""+ return {+ "passenger_info": PassengerInfo(+ adults=1,+ children=0,+ infants_in_seat=0,+ infants_on_lap=0,+ ),+ "flight_segments": [+ FlightSegment(+ departure_airport=[[Airport.PHX, 0]],+ arrival_airport=[[Airport.SFO, 0]],+ travel_date=future_date.strftime("%Y-%m-%d"),+ )+ ],+ "stops": MaxStops.NON_STOP,+ "seat_type": SeatType.ECONOMY,+ }+++def test_date_search_normal_dates(basic_search_params, future_date):+ """Test DateSearchFilters with normal date range."""+ from_date = future_date - timedelta(days=7)+ to_date = future_date + timedelta(days=7)++ filters = DateSearchFilters(+ **basic_search_params,+ from_date=from_date.strftime("%Y-%m-%d"),+ to_date=to_date.strftime("%Y-%m-%d"),+ )++ assert filters.from_date == from_date.strftime("%Y-%m-%d")+ assert filters.to_date == to_date.strftime("%Y-%m-%d")+++def test_date_search_past_from_date(basic_search_params, future_date):+ """Test DateSearchFilters auto-corrects past from_date to today."""+ past_date = datetime.now() - timedelta(days=7)+ to_date = future_date + timedelta(days=7)++ filters = DateSearchFilters(+ **basic_search_params,+ from_date=past_date.strftime("%Y-%m-%d"),+ to_date=to_date.strftime("%Y-%m-%d"),+ )++ assert filters.from_date == datetime.now().date().strftime("%Y-%m-%d")+ assert filters.to_date == to_date.strftime("%Y-%m-%d")+++def test_date_search_reversed_dates(basic_search_params, future_date):+ """Test DateSearchFilters auto-corrects reversed dates."""+ earlier_date = future_date+ later_date = future_date + timedelta(days=7)++ # Create with reversed dates+ filters = DateSearchFilters(+ **basic_search_params,+ from_date=later_date.strftime("%Y-%m-%d"),+ to_date=earlier_date.strftime("%Y-%m-%d"),+ )++ # Verify dates were swapped+ assert filters.from_date == earlier_date.strftime("%Y-%m-%d")+ assert filters.to_date == later_date.strftime("%Y-%m-%d")+++def test_date_search_past_to_date(basic_search_params):+ """Test DateSearchFilters raises error for past to_date."""+ from_date = datetime.now() - timedelta(days=7)+ to_date = datetime.now() - timedelta(days=1)++ with pytest.raises(ValueError, match="To date must be in the future"):+ DateSearchFilters(+ **basic_search_params,+ from_date=from_date.strftime("%Y-%m-%d"),+ to_date=to_date.strftime("%Y-%m-%d"),+ )++ # Even if the from and to dates are reversed, the to date should still be in the future+ with pytest.raises(ValueError, match="To date must be in the future"):+ DateSearchFilters(+ **basic_search_params,+ from_date=to_date.strftime("%Y-%m-%d"),+ to_date=from_date.strftime("%Y-%m-%d"),+ )+++def test_date_search_today_to_date(basic_search_params, future_date):+ """Test DateSearchFilters raises error for today's to_date."""+ today = datetime.now()+ from_date = today - timedelta(days=7)++ with pytest.raises(ValueError, match="To date must be in the future"):+ DateSearchFilters(+ **basic_search_params,+ from_date=from_date.strftime("%Y-%m-%d"),+ to_date=today.strftime("%Y-%m-%d"),+ )++ # Even if the from and to dates are reversed, the to date should still be in the future+ with pytest.raises(ValueError, match="To date must be in the future"):+ DateSearchFilters(+ **basic_search_params,+ from_date=today.strftime("%Y-%m-%d"),+ to_date=from_date.strftime("%Y-%m-%d"),+ )+++def test_date_search_segment_outside_range(basic_search_params, future_date):+ """Test DateSearchFilters validates flight segment dates are within range."""+ from_date = future_date+ to_date = future_date + timedelta(days=7)+ outside_date = future_date + timedelta(days=14)++ # Update flight segment to be outside the date range+ basic_search_params["flight_segments"][0].travel_date = outside_date.strftime("%Y-%m-%d")++ with pytest.raises(+ ValueError, match="Flight segment travel date .* must be within the search date range"+ ):+ DateSearchFilters(+ **basic_search_params,+ from_date=from_date.strftime("%Y-%m-%d"),+ to_date=to_date.strftime("%Y-%m-%d"),+ )++ # Even if the from and to dates are reversed, the to date should still be in the future+ with pytest.raises(+ ValueError, match="Flight segment travel date .* must be within the search date range"+ ):+ DateSearchFilters(+ **basic_search_params,+ from_date=to_date.strftime("%Y-%m-%d"),+ to_date=from_date.strftime("%Y-%m-%d"),+ )diff --git a/tests/models/test_flight_segment_validation.py b/tests/models/test_flight_segment_validation.pynew file mode 100644index 0000000..c57d5df--- /dev/null+++ b/tests/models/test_flight_segment_validation.py@@ -0,0 +1,112 @@+"""Tests for FlightSegment validation."""++from datetime import datetime, timedelta++import pytest++from fli.models import Airport, FlightSegment, TimeRestrictions+++def future_date():+ """Get a date 30 days in the future."""+ return datetime.now() + timedelta(days=30)+++def test_flight_segment_normal():+ """Test FlightSegment with valid data."""+ future = datetime.now() + timedelta(days=30)+ segment = FlightSegment(+ departure_airport=[[Airport.PHX, 0]],+ arrival_airport=[[Airport.SFO, 0]],+ travel_date=future.strftime("%Y-%m-%d"),+ )+ assert segment.departure_airport == [[Airport.PHX, 0]]+ assert segment.arrival_airport == [[Airport.SFO, 0]]+ assert segment.travel_date == future.strftime("%Y-%m-%d")+++def test_flight_segment_past_date():+ """Test FlightSegment rejects past travel dates."""+ past = datetime.now() - timedelta(days=1)+ with pytest.raises(ValueError, match="Travel date cannot be in the past"):+ FlightSegment(+ departure_airport=[[Airport.PHX, 0]],+ arrival_airport=[[Airport.SFO, 0]],+ travel_date=past.strftime("%Y-%m-%d"),+ )+++def test_flight_segment_today():+ """Test FlightSegment accepts today's date."""+ today = datetime.now()+ segment = FlightSegment(+ departure_airport=[[Airport.PHX, 0]],+ arrival_airport=[[Airport.SFO, 0]],+ travel_date=today.strftime("%Y-%m-%d"),+ )+ assert segment.travel_date == today.strftime("%Y-%m-%d")+++def test_flight_segment_same_airports():+ """Test FlightSegment rejects same departure and arrival airports."""+ future = datetime.now() + timedelta(days=30)+ with pytest.raises(ValueError, match="Departure and arrival airports must be different"):+ FlightSegment(+ departure_airport=[[Airport.PHX, 0]],+ arrival_airport=[[Airport.PHX, 0]], # Same as departure+ travel_date=future.strftime("%Y-%m-%d"),+ )+++def test_flight_segment_missing_airports():+ """Test FlightSegment rejects missing airports."""+ future = datetime.now() + timedelta(days=30)+ with pytest.raises(ValueError, match="Both departure and arrival airports must be specified"):+ FlightSegment(+ departure_airport=[],+ arrival_airport=[[Airport.SFO, 0]],+ travel_date=future.strftime("%Y-%m-%d"),+ )++ with pytest.raises(ValueError, match="Both departure and arrival airports must be specified"):+ FlightSegment(+ departure_airport=[[Airport.PHX, 0]],+ arrival_airport=[],+ travel_date=future.strftime("%Y-%m-%d"),+ )+++def test_flight_segment_with_time_restrictions(future_date):+ """Test FlightSegment with TimeRestrictions."""+ # Normal order+ segment1 = FlightSegment(+ departure_airport=[[Airport.PHX, 0]],+ arrival_airport=[[Airport.SFO, 0]],+ travel_date=future_date.strftime("%Y-%m-%d"),+ time_restrictions=TimeRestrictions(+ earliest_departure=9,+ latest_departure=20,+ earliest_arrival=13,+ latest_arrival=21,+ ),+ )+ assert segment1.time_restrictions.earliest_departure == 9+ assert segment1.time_restrictions.latest_departure == 20++ # Reversed order (should be auto-corrected by TimeRestrictions)+ segment2 = FlightSegment(+ departure_airport=[[Airport.PHX, 0]],+ arrival_airport=[[Airport.SFO, 0]],+ travel_date=future_date.strftime("%Y-%m-%d"),+ time_restrictions=TimeRestrictions(+ earliest_departure=20, # Later than latest_departure+ latest_departure=9, # Earlier than earliest_departure+ earliest_arrival=21, # Later than latest_arrival+ latest_arrival=13, # Earlier than earliest_arrival+ ),+ )+ assert segment2.time_restrictions.earliest_departure == 9 # Swapped+ assert segment2.time_restrictions.latest_departure == 20 # Swapped+ assert segment2.time_restrictions.earliest_arrival == 13 # Swapped+ assert segment2.time_restrictions.latest_arrival == 21 # Swappeddiff --git a/tests/models/test_time_restrictions.py b/tests/models/test_time_restrictions.pynew file mode 100644index 0000000..cb89cc6--- /dev/null+++ b/tests/models/test_time_restrictions.py@@ -0,0 +1,101 @@+"""Tests for TimeRestrictions model."""++from fli.models import TimeRestrictions+++def test_time_restrictions_no_swap_needed():+ """Test TimeRestrictions when times are in correct order."""+ tr = TimeRestrictions(+ earliest_departure=9,+ latest_departure=20,+ earliest_arrival=13,+ latest_arrival=21,+ )+ assert tr.earliest_departure == 9+ assert tr.latest_departure == 20+ assert tr.earliest_arrival == 13+ assert tr.latest_arrival == 21+++def test_time_restrictions_departure_swap():+ """Test TimeRestrictions auto-swaps departure times when out of order."""+ tr = TimeRestrictions(+ earliest_departure=20, # Later than latest_departure+ latest_departure=9, # Earlier than earliest_departure+ earliest_arrival=13,+ latest_arrival=21,+ )+ assert tr.earliest_departure == 9 # Swapped+ assert tr.latest_departure == 20 # Swapped+ assert tr.earliest_arrival == 13 # Unchanged+ assert tr.latest_arrival == 21 # Unchanged+++def test_time_restrictions_arrival_swap():+ """Test TimeRestrictions auto-swaps arrival times when out of order."""+ tr = TimeRestrictions(+ earliest_departure=9,+ latest_departure=20,+ earliest_arrival=21, # Later than latest_arrival+ latest_arrival=13, # Earlier than earliest_arrival+ )+ assert tr.earliest_departure == 9 # Unchanged+ assert tr.latest_departure == 20 # Unchanged+ assert tr.earliest_arrival == 13 # Swapped+ assert tr.latest_arrival == 21 # Swapped+++def test_time_restrictions_both_swap():+ """Test TimeRestrictions auto-swaps both departure and arrival times when out of order."""+ tr = TimeRestrictions(+ earliest_departure=20, # Later than latest_departure+ latest_departure=9, # Earlier than earliest_departure+ earliest_arrival=21, # Later than latest_arrival+ latest_arrival=13, # Earlier than earliest_arrival+ )+ assert tr.earliest_departure == 9 # Swapped+ assert tr.latest_departure == 20 # Swapped+ assert tr.earliest_arrival == 13 # Swapped+ assert tr.latest_arrival == 21 # Swapped+++def test_time_restrictions_partial_values():+ """Test TimeRestrictions with partial time restrictions."""+ # Only departure times+ tr1 = TimeRestrictions(+ earliest_departure=20,+ latest_departure=9,+ )+ assert tr1.earliest_departure == 9 # Swapped+ assert tr1.latest_departure == 20 # Swapped+ assert tr1.earliest_arrival is None+ assert tr1.latest_arrival is None++ # Only arrival times+ tr2 = TimeRestrictions(+ earliest_arrival=21,+ latest_arrival=13,+ )+ assert tr2.earliest_departure is None+ assert tr2.latest_departure is None+ assert tr2.earliest_arrival == 13 # Swapped+ assert tr2.latest_arrival == 21 # Swapped+++def test_time_restrictions_single_values():+ """Test TimeRestrictions with single values (no swapping needed)."""+ tr1 = TimeRestrictions(earliest_departure=9)+ assert tr1.earliest_departure == 9+ assert tr1.latest_departure is None++ tr2 = TimeRestrictions(latest_departure=20)+ assert tr2.earliest_departure is None+ assert tr2.latest_departure == 20++ tr3 = TimeRestrictions(earliest_arrival=13)+ assert tr3.earliest_arrival == 13+ assert tr3.latest_arrival is None++ tr4 = TimeRestrictions(latest_arrival=21)+ assert tr4.earliest_arrival is None+ assert tr4.latest_arrival == 21