Google Flights MCP, CLI and Python Library
"""Tests for SearchDates class."""
from datetime import datetime, timedelta
import pytest
from fli.models import (
Airport,
DateSearchFilters,
FlightSegment,
MaxStops,
PassengerInfo,
SeatType,
SortBy,
)
from fli.models.google_flights.base import TripType
from fli.search import SearchDates
@pytest.fixture
def search():
"""Create a reusable SearchDates instance."""
return SearchDates()
@pytest.fixture
def basic_search_params():
"""Create basic date search params for testing."""
today = datetime.now()
future_date = today + timedelta(days=30)
return DateSearchFilters(
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,
sort_by=SortBy.CHEAPEST,
from_date=(future_date - timedelta(days=30)).strftime("%Y-%m-%d"),
to_date=(future_date + timedelta(days=30)).strftime("%Y-%m-%d"),
)
@pytest.fixture
def complex_search_params():
"""Create more complex date search params for testing."""
today = datetime.now()
future_date = today + timedelta(days=60)
return DateSearchFilters(
passenger_info=PassengerInfo(
adults=2,
children=1,
infants_in_seat=0,
infants_on_lap=1,
),
flight_segments=[
FlightSegment(
departure_airport=[[Airport.JFK, 0]],
arrival_airport=[[Airport.LAX, 0]],
travel_date=future_date.strftime("%Y-%m-%d"),
)
],
stops=MaxStops.ONE_STOP_OR_FEWER,
seat_type=SeatType.FIRST,
sort_by=SortBy.TOP_FLIGHTS,
from_date=(future_date - timedelta(days=30)).strftime("%Y-%m-%d"),
to_date=(future_date + timedelta(days=30)).strftime("%Y-%m-%d"),
)
@pytest.fixture
def round_trip_search_params():
"""Create basic round trip search params for testing."""
today = datetime.now()
outbound_date = today + timedelta(days=30)
return_date = outbound_date + timedelta(days=7)
return DateSearchFilters(
passenger_info=PassengerInfo(
adults=1,
children=0,
infants_in_seat=0,
infants_on_lap=0,
),
flight_segments=[
FlightSegment(
departure_airport=[[Airport.SFO, 0]],
arrival_airport=[[Airport.JFK, 0]],
travel_date=outbound_date.strftime("%Y-%m-%d"),
),
FlightSegment(
departure_airport=[[Airport.JFK, 0]],
arrival_airport=[[Airport.SFO, 0]],
travel_date=return_date.strftime("%Y-%m-%d"),
),
],
stops=MaxStops.NON_STOP,
seat_type=SeatType.ECONOMY,
sort_by=SortBy.CHEAPEST,
trip_type=TripType.ROUND_TRIP,
from_date=(outbound_date - timedelta(days=30)).strftime("%Y-%m-%d"),
to_date=(outbound_date + timedelta(days=30)).strftime("%Y-%m-%d"),
)
@pytest.fixture
def complex_round_trip_params():
"""Create more complex round trip search params for testing."""
today = datetime.now()
outbound_date = today + timedelta(days=60)
return_date = outbound_date + timedelta(days=14)
return DateSearchFilters(
passenger_info=PassengerInfo(
adults=2,
children=1,
infants_in_seat=0,
infants_on_lap=1,
),
flight_segments=[
FlightSegment(
departure_airport=[[Airport.LAX, 0]],
arrival_airport=[[Airport.ORD, 0]],
travel_date=outbound_date.strftime("%Y-%m-%d"),
),
FlightSegment(
departure_airport=[[Airport.ORD, 0]],
arrival_airport=[[Airport.LAX, 0]],
travel_date=return_date.strftime("%Y-%m-%d"),
),
],
stops=MaxStops.ONE_STOP_OR_FEWER,
seat_type=SeatType.BUSINESS,
sort_by=SortBy.TOP_FLIGHTS,
trip_type=TripType.ROUND_TRIP,
from_date=(outbound_date - timedelta(days=30)).strftime("%Y-%m-%d"),
to_date=(outbound_date + timedelta(days=30)).strftime("%Y-%m-%d"),
)
# Infant searches themselves work: the ``tfs`` passenger codes are verified
# against Google's own pricing (1=adult, 2=child, 3=lap infant, 4=infant in
# seat — see TestPassengerCodes in test_tfs.py and TestLapInfantPricing in
# test_search_flights_new_filters_live.py), and JFK->LHR economy with a lap
# infant returns 15 rows.
#
# What still comes back empty is this particular combination. Probed live
# 2026-09-20, one-stop-or-fewer, 60 days out:
#
# 2a+1c FIRST JFK->LAX 22 rows
# 1a ECONOMY JFK->LAX 35 rows
# 1a FIRST JFK->LHR 10 rows
# 2a+1c+1lap FIRST JFK->LAX 0 rows <- this fixture
# 2a+1c+1lap ECONOMY JFK->LAX 0 rows
# 2a+1c+1seat ECONOMY JFK->LAX 0 rows
# 2a+1c+1lap ECONOMY JFK->LHR 15 rows
# 2a+1c+1lap FIRST JFK->LHR 0 rows
#
# So any infant on JFK->LAX, and any lap infant in FIRST, yields a page with
# no results grid, while the same passenger mix on other route/cabin pairs is
# served normally. Nothing in the request is rejected — Google simply inlines
# no rows — which reads as inventory rather than encoding. Non-strict so a
# change on Google's side surfaces as an unexpected pass.
INFANT_RESULTS_MISSING = pytest.mark.xfail(
reason=(
"Google inlines no results for JFK-LAX / LAX-ORD with a lap infant in "
"FIRST or BUSINESS (0 rows); the same query without the infant returns "
"22, and JFK-LHR economy with the same lap infant returns 15 — so the "
"tfs passenger codes are correct and this is Google-side"
),
strict=False,
)
# The `search` fixture above is a bare SearchDates() with no HTTP mocking,
# so every test below that uses it hits the real Google Flights network.
@pytest.mark.live
@pytest.mark.parametrize(
"search_params_fixture",
[
"basic_search_params",
pytest.param("complex_search_params", marks=INFANT_RESULTS_MISSING),
],
)
def test_search_functionality(search, search_params_fixture, request):
"""Test date search functionality with different data sets."""
search_params = request.getfixturevalue(search_params_fixture)
results = search.search(search_params)
assert isinstance(results, list)
@pytest.mark.live
@INFANT_RESULTS_MISSING
def test_multiple_searches(search, basic_search_params, complex_search_params):
"""Test performing multiple searches with the same SearchDates instance."""
# First search
results1 = search.search(basic_search_params)
assert isinstance(results1, list)
# Second search with different data
results2 = search.search(complex_search_params)
assert isinstance(results2, list)
# Third search reusing first search data
results3 = search.search(basic_search_params)
assert isinstance(results3, list)
@pytest.mark.live
def test_date_price_sorting(search, basic_search_params):
"""Test that date prices are sorted chronologically."""
results = search.search(basic_search_params)
assert len(results) > 0
# Verify dates are sorted
dates = [result.date[0] for result in results] # Get first date from tuple
assert dates == sorted(dates)
SHOPPING_TOKEN = (
"CjRIQktCNmV1UjNqNjhBR043X0FCRy0tLS0tLS0tLS12dGpkN0FBQUFBR25JcWZNS2pGTTBBEgZV"
"QTIyMDkaCgjcWxACGgNVU0Q4HHDcWw=="
)
CALENDAR_ITEM = ["2026-04-28", None, [[None, 118], SHOPPING_TOKEN], 1]
def test_parse_currency_from_calendar_item():
"""Calendar rows should expose the returned currency code."""
assert SearchDates._SearchDates__parse_currency(CALENDAR_ITEM) == "USD"
def test_parse_price_from_calendar_item():
"""Calendar rows should keep using the numeric display price."""
assert SearchDates._SearchDates__parse_price(CALENDAR_ITEM) == 118.0
@pytest.mark.live
def test_basic_round_trip_search(search, round_trip_search_params):
"""Test basic round trip date search functionality."""
results = search.search(round_trip_search_params)
assert isinstance(results, list)
assert len(results) > 0
# Verify date range
from_date = datetime.strptime(round_trip_search_params.from_date, "%Y-%m-%d")
to_date = datetime.strptime(round_trip_search_params.to_date, "%Y-%m-%d")
for result in results:
# For round trips, date is a tuple of (outbound_date, return_date)
outbound_date, return_date = result.date
assert from_date.date() <= outbound_date.date() <= to_date.date()
assert outbound_date.date() <= return_date.date() # Return can be same day or later
assert hasattr(result, "price")
assert result.price > 0
@pytest.mark.live
def test_complex_round_trip_search(search, complex_round_trip_params):
"""Test complex round trip date search with multiple passengers and stops."""
results = search.search(complex_round_trip_params)
assert isinstance(results, list)
assert len(results) > 0
# Verify date range
from_date = datetime.strptime(complex_round_trip_params.from_date, "%Y-%m-%d")
to_date = datetime.strptime(complex_round_trip_params.to_date, "%Y-%m-%d")
for result in results:
# For round trips, date is a tuple of (outbound_date, return_date)
outbound_date, return_date = result.date
assert from_date.date() <= outbound_date.date() <= to_date.date()
assert outbound_date.date() <= return_date.date() # Return can be same day or later
assert hasattr(result, "price")
assert result.price > 0
@pytest.mark.live
@pytest.mark.parametrize(
"search_params_fixture",
[
"round_trip_search_params",
"complex_round_trip_params",
],
)
def test_round_trip_result_structure(search, search_params_fixture, request):
"""Test the structure of round trip date search results with different parameters."""
search_params = request.getfixturevalue(search_params_fixture)
results = search.search(search_params)
assert isinstance(results, list)
assert len(results) > 0
# Verify chronological order of outbound dates
outbound_dates = [result.date[0] for result in results]
assert outbound_dates == sorted(outbound_dates)
# Verify result structure
for result in results:
assert isinstance(result.date, tuple)
assert len(result.date) == 2 # Should have outbound and return dates
outbound_date, return_date = result.date
assert isinstance(outbound_date, datetime)
assert isinstance(return_date, datetime)
assert outbound_date <= return_date # Return can be same day or later
assert hasattr(result, "price")
assert result.price > 0
class TestRoundTripDurationFallback:
"""A round trip with no explicit ``duration`` still prices a return leg.
``DateSearchFilters.duration`` is optional and its validator doesn't run
on the default, so round-trip filters can reach the search with it unset.
The return date then comes from the gap between the two segments.
"""
def test_return_date_derived_from_segments(self, monkeypatch, round_trip_search_params):
import base64
from pathlib import Path
from fli.search._wire import iter_wrb_chunks
from tests.search._pages import as_search_page
assert round_trip_search_params.duration is None
page = as_search_page(
next(
iter_wrb_chunks(
(
Path(__file__).parent / "fixtures" / "flight_search_jfk_lax_oneway_usd.bin"
).read_text()
)
)
)
urls: list[str] = []
def _fake_get(url, **kwargs):
urls.append(url)
return type("R", (), {"text": page, "raise_for_status": lambda s: None})()
search = SearchDates()
monkeypatch.setattr(search.client, "get", _fake_get)
results = search.search(round_trip_search_params)
assert results and all(len(r.date) == 2 for r in results)
# Outbound and return are 7 days apart in the fixture's segments.
assert all((r.date[1] - r.date[0]).days == 7 for r in results)
# The date sweep prices every candidate date on the shared thread
# pool (see fli/search/_concurrency.py), so `urls` fills in whatever
# order the fetches happen to complete in — NOT the order `results`
# ends up in (which is sorted after the fact). `urls[0]` is
# therefore not guaranteed to be the request that produced
# `results[0]`; decode every recorded URL and look up the one whose
# `tfs` token actually encodes the result under test instead.
def _decode_tfs(url: str) -> str:
tfs = url.split("tfs=")[1].split("&")[0]
return base64.urlsafe_b64decode(tfs + "=" * (-len(tfs) % 4)).decode("latin-1")
decoded_urls = [_decode_tfs(u) for u in urls]
for r in results[:1]:
outbound_str = r.date[0].strftime("%Y-%m-%d")
return_str = r.date[1].strftime("%Y-%m-%d")
assert any(outbound_str in d and return_str in d for d in decoded_urls), (
f"no fetched URL encoded both {outbound_str} and {return_str} "
f"(checked {len(decoded_urls)} URLs)"
)