Google Flights MCP, CLI and Python Library
Add unit tests for previously uncovered modules (#167)
Punit Aranib94b490cd103
diff --git a/tests/cli/test_errors.py b/tests/cli/test_errors.pyindex 47072dc..645f860 100644--- a/tests/cli/test_errors.py+++ b/tests/cli/test_errors.py@@ -44,21 +44,23 @@ def test_write_log_creates_file_with_traceback(tmp_path):assert "traceback:" in contents-def test_json_error_payload_maps_error_types():- """Each SearchClientError subclass should map to a distinct error_type string."""- cases = [+ "exc, expected_type",+ [(SearchTimeoutError("timed out"), "timeout"),(SearchConnectionError("dns"), "connection_error"),(SearchHTTPError("403", status_code=403), "http_error"),(SearchClientError("generic"), "search_error"),(RuntimeError("boom"), "unexpected_error"),- ]- for exc, expected_type in cases:- message, error_type, log_path = json_error_payload(exc)- assert error_type == expected_type- assert isinstance(log_path, Path)- assert log_path.exists()- assert message # non-empty+ ],+)+def test_json_error_payload_maps_error_types(exc, expected_type):+ """Each SearchClientError subclass should map to a distinct error_type string."""+ message, error_type, log_path = json_error_payload(exc)+ assert error_type == expected_type+ assert isinstance(log_path, Path)+ assert log_path.exists()+ assert message # non-emptydef test_report_cli_error_returns_typer_exit_and_writes_log(tmp_path, capsys):@@ -108,6 +110,88 @@ def test_multi_command_handles_timeout_cleanly(runner, monkeypatch, tmp_path):assert len(log_files) >= 1+ "exc, expected_msg",+ [+ (SearchTimeoutError("slow"), "Request timed out. slow"),+ (SearchConnectionError("dns"), "Network error. dns"),+ (SearchHTTPError("403", status_code=403), "Google Flights error. 403"),+ (SearchClientError("generic failure"), "Search failed. generic failure"),+ (ValueError("bad input"), "Unexpected error: ValueError: bad input"),+ ],+)+def test_friendly_message(exc, expected_msg):+ """_friendly_message must dispatch to the correct user-facing message per error type."""+ from fli.cli.errors import _friendly_message++ assert _friendly_message(exc) == expected_msg+++class TestWriteLogDetails:+ def test_no_command_omits_command_line(self):+ try:+ raise SearchTimeoutError("slow backend")+ except SearchTimeoutError as exc:+ log_path = _write_log(exc, command=None)+ contents = log_path.read_text()+ assert "command:" not in contents++ def test_argv_written_to_log(self):+ import sys++ try:+ raise SearchConnectionError("no route")+ except SearchConnectionError as exc:+ log_path = _write_log(exc)+ contents = log_path.read_text()+ assert "argv:" in contents+ assert str(sys.argv) in contents++ def test_qualified_error_type_in_log(self):+ try:+ raise SearchTimeoutError("timeout")+ except SearchTimeoutError as exc:+ log_path = _write_log(exc)+ contents = log_path.read_text()+ assert "fli.search.exceptions.SearchTimeoutError" in contents++ def test_timestamp_present_in_log(self):+ try:+ raise SearchClientError("x")+ except SearchClientError as exc:+ log_path = _write_log(exc)+ assert "timestamp:" in log_path.read_text()+++class TestJsonErrorPayloadMessages:+ def test_message_is_str_of_exception(self):+ exc = SearchTimeoutError("timed out waiting for response")+ message, _, _ = json_error_payload(exc)+ assert message == str(exc) == "timed out waiting for response"++ def test_unexpected_error_message_format(self):+ exc = RuntimeError("bad input")+ message, error_type, _ = json_error_payload(exc)+ assert message == "RuntimeError: bad input"+ assert error_type == "unexpected_error"++ def test_log_path_is_a_real_file(self):+ exc = SearchConnectionError("dns failure")+ _, _, log_path = json_error_payload(exc)+ assert log_path.exists()+ assert log_path.is_file()+++class TestReportCliErrorOptions:+ def test_custom_exit_code_respected(self):+ import typer++ exc = SearchTimeoutError("hung")+ result = report_cli_error(exc, exit_code=2)+ assert isinstance(result, typer.Exit)+ assert result.exit_code == 2++def test_flights_command_json_error_includes_log_path(runner, monkeypatch, tmp_path):"""JSON-mode errors should include the log path and a typed error_type."""import jsondiff --git a/tests/cli/test_utils.py b/tests/cli/test_utils.pyindex b4321f4..0d4d6ea 100644--- a/tests/cli/test_utils.py+++ b/tests/cli/test_utils.py@@ -15,7 +15,6 @@ from fli.cli.utils import (filter_flights_by_time,parse_airlines,parse_stops,- serialize_airline,serialize_date_result,serialize_flight_result,validate_date,@@ -115,13 +114,6 @@ def test_parse_airlines_numeric_prefix():assert result == [Airline._3F]-def test_serialize_airline_numeric_prefix():- """Test that serialized airline code strips underscore prefix."""- result = serialize_airline(Airline._3F)- assert result["code"] == "3F"- assert result["name"] == "FlyOne Armenia"--def test_parse_airlines_invalid():"""Test parsing airlines with invalid code."""with pytest.raises(BadParameter):diff --git a/tests/core/test_parsers.py b/tests/core/test_parsers.pyindex 1ddb681..f9b1256 100644--- a/tests/core/test_parsers.py+++ b/tests/core/test_parsers.py@@ -23,30 +23,23 @@ class TestParseEmissions:with pytest.raises(ParseError, match="Invalid EmissionsFilter"):parse_emissions("NONE")- def test_invalid_random(self):- with pytest.raises(ParseError, match="Invalid EmissionsFilter"):- parse_emissions("HIGH")---class TestParseAirlinesWithAlliances:- """Tests for parse_airlines with alliance codes."""-- def test_alliance_star_alliance(self):- result = parse_airlines(["STAR_ALLIANCE"])- assert result == [Airline.STAR_ALLIANCE]- def test_alliance_oneworld(self):- result = parse_airlines(["ONEWORLD"])- assert result == [Airline.ONEWORLD]+ "code, expected",+ [+ ("STAR_ALLIANCE", Airline.STAR_ALLIANCE),+ ("ONEWORLD", Airline.ONEWORLD),+ ("SKYTEAM", Airline.SKYTEAM),+ ],+)+def test_parse_airlines_alliance(code, expected):+ assert parse_airlines([code]) == [expected]- def test_alliance_skyteam(self):- result = parse_airlines(["SKYTEAM"])- assert result == [Airline.SKYTEAM]- def test_alliance_mixed_with_airlines(self):- result = parse_airlines(["STAR_ALLIANCE", "AA"])- assert Airline.STAR_ALLIANCE in result- assert Airline.AA in result+def test_parse_airlines_alliance_mixed_with_airlines():+ result = parse_airlines(["STAR_ALLIANCE", "AA"])+ assert Airline.STAR_ALLIANCE in result+ assert Airline.AA in resultclass TestParseAirlinesSplitting:@@ -98,21 +91,10 @@ class TestParseAirlinesSplitting:with pytest.raises(ParseError, match="Invalid airline code: 'XXX'"):parse_airlines(["BA,XXX"])- def test_raises_when_only_commas(self):- with pytest.raises(ParseError, match="No valid airline codes"):- parse_airlines([","])-- def test_raises_when_only_whitespace(self):- with pytest.raises(ParseError, match="No valid airline codes"):- parse_airlines([" "])-- def test_raises_when_only_empty_string(self):- with pytest.raises(ParseError, match="No valid airline codes"):- parse_airlines([""])-- def test_raises_when_only_separators_across_items(self):+ @pytest.mark.parametrize("codes", [[","], [" "], [""], ["", " ", ","]])+ def test_raises_when_no_valid_codes(self, codes):with pytest.raises(ParseError, match="No valid airline codes"):- parse_airlines(["", " ", ","])+ parse_airlines(codes)def test_none_input_still_returns_none(self):assert parse_airlines(None) is None@@ -121,25 +103,19 @@ class TestParseAirlinesSplitting:assert parse_airlines([]) is None-class TestParseSortBy:- """Tests for parse_sort_by with updated enum values."""-- def test_top_flights(self):- assert parse_sort_by("TOP_FLIGHTS") == SortBy.TOP_FLIGHTS- assert SortBy.TOP_FLIGHTS.value == 0+ "value, expected",+ [+ ("TOP_FLIGHTS", SortBy.TOP_FLIGHTS),+ ("BEST", SortBy.BEST),+ ("CHEAPEST", SortBy.CHEAPEST),+ ("EMISSIONS", SortBy.EMISSIONS),+ ],+)+def test_parse_sort_by(value, expected):+ assert parse_sort_by(value) == expected- def test_best(self):- assert parse_sort_by("BEST") == SortBy.BEST- assert SortBy.BEST.value == 1- def test_cheapest(self):- assert parse_sort_by("CHEAPEST") == SortBy.CHEAPEST- assert SortBy.CHEAPEST.value == 2-- def test_emissions(self):- assert parse_sort_by("EMISSIONS") == SortBy.EMISSIONS- assert SortBy.EMISSIONS.value == 6-- def test_invalid(self):- with pytest.raises(ParseError, match="Invalid sort_by value"):- parse_sort_by("NONE")+def test_parse_sort_by_invalid():+ with pytest.raises(ParseError, match="Invalid sort_by value"):+ parse_sort_by("NONE")diff --git a/tests/mcp/test_mcp_server_unit.py b/tests/mcp/test_mcp_server_unit.pynew file mode 100644index 0000000..29ab9fc--- /dev/null+++ b/tests/mcp/test_mcp_server_unit.py@@ -0,0 +1,251 @@+"""Unit tests for MCP server serialization helpers and error propagation.++Targets functions that are only reached via integration tests in the existing+suite: _airline_code, _serialize_flight_leg, _serialize_layover,+_flight_extras, and the bare-except error path in _execute_flight_search.+"""++from __future__ import annotations++from unittest.mock import MagicMock++import pytest++from fli.mcp.server import (+ FlightSearchParams,+ _airline_code,+ _execute_flight_search,+ _flight_extras,+ _serialize_flight_leg,+ _serialize_layover,+)+++def _make_raiser(exc: BaseException):+ """Return a callable that unconditionally raises ``exc``."""++ def _raiser(*args, **kwargs):+ raise exc++ return _raiser+++class TestAirlineCode:+ def test_enum_with_leading_underscore_stripped(self):+ airline = MagicMock()+ airline.name = "_2B"+ assert _airline_code(airline) == "2B"++ def test_plain_enum_name_unchanged(self):+ airline = MagicMock()+ airline.name = "DL"+ assert _airline_code(airline) == "DL"++ def test_plain_string_passthrough(self):+ # Strings have no `.name` attribute, so str(airline) is used.+ assert _airline_code("AA") == "AA"+++class TestSerializeFlightLeg:+ def _make_leg(self, **overrides):+ leg = MagicMock()+ leg.departure_airport = "JFK"+ leg.arrival_airport = "LHR"+ leg.departure_datetime = None+ leg.arrival_datetime = None+ leg.duration = 420+ leg.airline = "AA"+ leg.flight_number = "100"+ leg.departure_airport_name = None+ leg.arrival_airport_name = None+ leg.operating_airline = None+ leg.aircraft = None+ leg.legroom = None+ leg.overnight = False+ leg.amenities = None+ for k, v in overrides.items():+ setattr(leg, k, v)+ return leg++ def test_required_fields_always_present(self):+ leg = self._make_leg()+ result = _serialize_flight_leg(leg)+ for key in (+ "departure_airport",+ "arrival_airport",+ "departure_time",+ "arrival_time",+ "duration",+ "airline",+ "airline_code",+ "flight_number",+ ):+ assert key in result++ def test_none_optional_fields_excluded(self):+ leg = self._make_leg()+ result = _serialize_flight_leg(leg)+ assert "departure_airport_name" not in result+ assert "arrival_airport_name" not in result+ assert "operating_airline" not in result+ assert "aircraft" not in result+ assert "legroom" not in result++ def test_overnight_true_included(self):+ leg = self._make_leg(overnight=True)+ result = _serialize_flight_leg(leg)+ assert result.get("overnight") is True++ def test_overnight_false_excluded(self):+ leg = self._make_leg(overnight=False)+ result = _serialize_flight_leg(leg)+ assert "overnight" not in result++ def test_operating_airline_included_when_set(self):+ op = MagicMock()+ op.name = "B6"+ leg = self._make_leg(operating_airline=op)+ result = _serialize_flight_leg(leg)+ assert result["operating_airline"] == "B6"++ def test_amenities_included_with_truthy_fields(self):+ from fli.models import Amenities++ leg = self._make_leg(amenities=Amenities(wifi=True))+ result = _serialize_flight_leg(leg)+ assert "amenities" in result+ assert result["amenities"]["wifi"] is True++ def test_amenities_excluded_when_none(self):+ leg = self._make_leg(amenities=None)+ result = _serialize_flight_leg(leg)+ assert "amenities" not in result++ def test_amenities_excluded_when_all_fields_are_none(self):+ from fli.models import Amenities++ leg = self._make_leg(amenities=Amenities())+ result = _serialize_flight_leg(leg)+ # model_dump(exclude_none=True) on an all-None Amenities → empty dict → not included+ assert "amenities" not in result+++class TestSerializeLayover:+ def _make_layover(self, **overrides):+ lo = MagicMock()+ lo.airport = "FRA"+ lo.duration = 90+ lo.overnight = False+ lo.change_of_airport = False+ for k, v in overrides.items():+ setattr(lo, k, v)+ return lo++ def test_airport_and_duration_always_present(self):+ lo = self._make_layover()+ result = _serialize_layover(lo)+ assert "airport" in result+ assert result["duration"] == 90++ def test_overnight_true_included(self):+ lo = self._make_layover(overnight=True)+ result = _serialize_layover(lo)+ assert result.get("overnight") is True++ def test_overnight_false_excluded(self):+ lo = self._make_layover(overnight=False)+ result = _serialize_layover(lo)+ assert "overnight" not in result++ def test_change_of_airport_true_included(self):+ lo = self._make_layover(change_of_airport=True)+ result = _serialize_layover(lo)+ assert result.get("change_of_airport") is True++ def test_change_of_airport_false_excluded(self):+ lo = self._make_layover(change_of_airport=False)+ result = _serialize_layover(lo)+ assert "change_of_airport" not in result+++class TestFlightExtras:+ def _make_flight(self, **overrides):+ f = MagicMock()+ f.primary_airline_name = None+ f.self_transfer = None+ f.mixed_cabin = None+ f.booking_token = None+ f.primary_airline = None+ f.layovers = None+ for k, v in overrides.items():+ setattr(f, k, v)+ return f++ def test_booking_token_included_when_set(self):+ f = self._make_flight(booking_token="tok123")+ result = _flight_extras(f)+ assert result["booking_token"] == "tok123"++ def test_booking_token_excluded_when_empty_string(self):+ f = self._make_flight(booking_token="")+ result = _flight_extras(f)+ assert "booking_token" not in result++ def test_booking_token_excluded_when_none(self):+ f = self._make_flight(booking_token=None)+ result = _flight_extras(f)+ assert "booking_token" not in result++ def test_self_transfer_true_included(self):+ f = self._make_flight(self_transfer=True)+ result = _flight_extras(f)+ assert result.get("self_transfer") is True++ def test_layovers_serialized(self):+ lo = MagicMock()+ lo.airport = "CDG"+ lo.duration = 60+ lo.overnight = False+ lo.change_of_airport = False+ f = self._make_flight(layovers=[lo])+ result = _flight_extras(f)+ assert "layovers" in result+ assert len(result["layovers"]) == 1+++class TestExecuteFlightSearchNetworkError:+ """The bare-except in _execute_flight_search must produce a clean error dict."""++ @pytest.fixture+ def valid_params(self):+ return FlightSearchParams(+ origin="JFK",+ destination="LHR",+ departure_date="2026-12-01",+ )++ def test_search_client_error_returns_success_false(self, monkeypatch, valid_params):+ from fli.search.exceptions import SearchClientError++ monkeypatch.setattr(+ "fli.mcp.server.SearchFlights.search",+ _make_raiser(SearchClientError("network down")),+ )+ result = _execute_flight_search(valid_params)+ assert result["success"] is False++ def test_exception_message_in_error_field(self, monkeypatch, valid_params):+ monkeypatch.setattr(+ "fli.mcp.server.SearchFlights.search",+ _make_raiser(RuntimeError("proxy timeout")),+ )+ result = _execute_flight_search(valid_params)+ assert result["error"] == "Search failed: proxy timeout"++ def test_flights_key_is_empty_list_on_error(self, monkeypatch, valid_params):+ monkeypatch.setattr(+ "fli.mcp.server.SearchFlights.search",+ _make_raiser(RuntimeError("fail")),+ )+ result = _execute_flight_search(valid_params)+ assert result["flights"] == []diff --git a/tests/models/test_flight_search_filters.py b/tests/models/test_flight_search_filters.pyindex d17bbb8..1a9e77c 100644--- a/tests/models/test_flight_search_filters.py+++ b/tests/models/test_flight_search_filters.py@@ -665,4 +665,6 @@ def test_flight_search_filters(test_case):# Test URL encodingencoded_filters = search_filters.encode()- assert test_case["encoded"] is None or encoded_filters == test_case["encoded"]+ assert isinstance(encoded_filters, str) and len(encoded_filters) > 0+ if test_case["encoded"] is not None:+ assert encoded_filters == test_case["encoded"]diff --git a/tests/search/test_client.py b/tests/search/test_client.pynew file mode 100644index 0000000..b05174e--- /dev/null+++ b/tests/search/test_client.py@@ -0,0 +1,120 @@+"""Unit tests for fli.search.client — error mapping, host extraction, and singleton."""++from __future__ import annotations++from unittest.mock import MagicMock++import pytest++import fli.search.client as client_module+from fli.search.client import _host_from_url, _wrap_request_error, get_client+from fli.search.exceptions import (+ SearchClientError,+ SearchConnectionError,+ SearchHTTPError,+ SearchTimeoutError,+)++[email protected](autouse=True)+def _reset_client_singleton():+ """Each test starts with a clean singleton so tests don't share state."""+ original = client_module.client+ client_module.client = None+ yield+ client_module.client = original+++class TestWrapRequestError:+ """_wrap_request_error must map curl_cffi errors to typed SearchClientError subclasses."""++ def test_timeout_exc_returns_search_timeout_error(self):+ from curl_cffi.requests import exceptions as curl_exc++ exc = curl_exc.Timeout("curl: (28) timed out", 28, None)+ result = _wrap_request_error("GET", "https://www.google.com/path", exc)+ assert isinstance(result, SearchTimeoutError)++ def test_timeout_message_includes_host(self):+ from curl_cffi.requests import exceptions as curl_exc++ exc = curl_exc.Timeout("timed out", 28, None)+ result = _wrap_request_error("GET", "https://flights.google.com/search", exc)+ assert "flights.google.com" in str(result)++ def test_connection_exc_returns_search_connection_error(self):+ from curl_cffi.requests import exceptions as curl_exc++ exc = curl_exc.ConnectionError("dns lookup failed", 6, None)+ result = _wrap_request_error("GET", "https://www.google.com/", exc)+ assert isinstance(result, SearchConnectionError)++ def test_http_exc_with_status_returns_search_http_error(self):+ from curl_cffi.requests import exceptions as curl_exc++ mock_response = MagicMock()+ mock_response.status_code = 403+ exc = curl_exc.HTTPError("403 Forbidden", 403, mock_response)+ exc.response = mock_response++ result = _wrap_request_error("POST", "https://www.google.com/", exc)+ assert isinstance(result, SearchHTTPError)+ assert result.status_code == 403+ assert "403" in str(result)++ def test_http_exc_without_response_has_none_status(self):+ from curl_cffi.requests import exceptions as curl_exc++ exc = curl_exc.HTTPError("error", 0, None)+ result = _wrap_request_error("POST", "https://www.google.com/", exc)+ assert isinstance(result, SearchHTTPError)+ assert result.status_code is None++ def test_unknown_exc_returns_search_client_error(self):+ exc = ValueError("something unexpected")+ result = _wrap_request_error("GET", "https://www.google.com/", exc)+ assert isinstance(result, SearchClientError)+ assert not isinstance(result, SearchTimeoutError | SearchConnectionError | SearchHTTPError)++ def test_already_typed_error_passes_through_unchanged(self):+ original = SearchTimeoutError("already typed")+ result = _wrap_request_error("GET", "https://www.google.com/", original)+ assert result is original++ def test_message_uses_url_as_fallback_on_parse_failure(self):+ exc = RuntimeError("boom")+ result = _wrap_request_error("GET", "not-a-url", exc)+ # Should include the raw string when urlparse can't extract a host.+ assert "not-a-url" in str(result)+++class TestHostFromUrl:+ def test_standard_https_url(self):+ assert _host_from_url("https://www.google.com/path?q=1") == "www.google.com"++ def test_url_without_host_returns_input(self):+ assert _host_from_url("not-a-url") == "not-a-url"++ def test_empty_string_returns_empty(self):+ # Shouldn't raise — empty is a valid degenerate case.+ result = _host_from_url("")+ assert result == ""+++class TestGetClientSingleton:+ def test_returns_client_instance(self):+ from fli.search.client import Client++ c = get_client()+ assert isinstance(c, Client)++ def test_returns_same_instance_on_repeated_calls(self):+ c1 = get_client()+ c2 = get_client()+ assert c1 is c2++ def test_reset_global_creates_new_instance(self):+ c1 = get_client()+ client_module.client = None+ c2 = get_client()+ assert c1 is not c2diff --git a/tests/search/test_concurrency.py b/tests/search/test_concurrency.pyindex 0283c96..ec7d04c 100644--- a/tests/search/test_concurrency.py+++ b/tests/search/test_concurrency.py@@ -229,6 +229,8 @@ class TestParallelMap:def test_max_workers_cap_observed(self):"""``max_workers=2`` should not run all 4 jobs concurrently."""+ # Reset to a known state so get_executor creates a fresh 2-worker pool.+ shutdown_executor()in_flight = 0peak = 0lock = threading.Lock()@@ -244,8 +246,47 @@ class TestParallelMap:return xparallel_map(fn, list(range(4)), max_workers=2)- # The executor caps concurrency. Note: the shared pool may already- # be sized larger than 2, so this only verifies behaviour through- # the synchronous fallback at max_workers=1 elsewhere.- # Here we just verify completion + correct count.assert peak >= 1+ assert peak <= 2++ def test_generator_input_materialised_and_mapped(self):+ result = parallel_map(lambda x: x * 3, (x for x in range(4)))+ assert result == [0, 3, 6, 9]++ def test_tuple_input_works(self):+ result = parallel_map(lambda x: x + 1, (10, 20, 30))+ assert result == [11, 21, 31]++ def test_exception_in_last_item_propagates(self):+ def fn(x):+ if x == 2:+ raise RuntimeError("last item error")+ return x++ with pytest.raises(RuntimeError, match="last item error"):+ parallel_map(fn, [0, 1, 2])+++class TestShutdownExecutor:+ def teardown_method(self):+ shutdown_executor()+ configure_concurrency(10)++ def test_shutdown_then_get_creates_new_executor(self):+ original = get_executor()+ shutdown_executor()+ new = get_executor()+ assert new is not original++ def test_shutdown_idempotent(self):+ # Calling shutdown twice must not raise.+ shutdown_executor()+ shutdown_executor()+++class TestTokenBucketEdgeCases:+ def test_bulk_acquire_from_full_bucket_is_immediate(self):+ limiter = TokenBucketRateLimiter(calls=5, period=1.0)+ start = time.perf_counter()+ assert limiter.acquire(tokens=3) is True+ assert (time.perf_counter() - start) < 0.05diff --git a/tests/search/test_decoders.py b/tests/search/test_decoders.pynew file mode 100644index 0000000..bcdb56e--- /dev/null+++ b/tests/search/test_decoders.py@@ -0,0 +1,225 @@+"""Unit tests for fli.search._decoders — direct decoder function coverage.++Tests import private helpers directly to cover branches that integration tests+and snapshot fixtures can't reach (warning-log paths, empty/None inputs,+unusual wire-format shapes).+"""++from __future__ import annotations++import logging+from datetime import datetime++import pytest++from fli.search._decoders import (+ _extract_booking_urls,+ _extract_fare_name,+ _parse_emissions,+ _safe_airline,+ parse_booking_chunk,+)+++class TestSafeAirline:+ def test_known_code_returns_enum(self):+ from fli.models import Airline++ result = _safe_airline("DL")+ assert result is Airline.DL++ def test_none_returns_none(self):+ assert _safe_airline(None) is None++ def test_empty_string_returns_none(self):+ assert _safe_airline("") is None++ def test_int_returns_none(self):+ assert _safe_airline(42) is None++ def test_sentinel_multi_returns_none_silently(self, caplog):+ with caplog.at_level(logging.WARNING, logger="fli.search._decoders"):+ result = _safe_airline("multi")+ assert result is None+ assert not caplog.records++ def test_unknown_code_returns_none_and_warns(self, caplog):+ with caplog.at_level(logging.WARNING, logger="fli.search._decoders"):+ result = _safe_airline("ZZFAKE")+ assert result is None+ assert any("ZZFAKE" in r.message for r in caplog.records)+++class TestParseDatetime:+ def test_valid_arrays_produce_datetime(self):+ from fli.search._decoders import _parse_datetime++ dt = _parse_datetime([2026, 7, 15], [20, 25])+ assert dt == datetime(2026, 7, 15, 20, 25)++ def test_all_none_date_raises_value_error(self):+ from fli.search._decoders import _parse_datetime++ with pytest.raises(ValueError):+ _parse_datetime([None, None, None], [0, 0])++ def test_all_none_time_raises_value_error(self):+ from fli.search._decoders import _parse_datetime++ with pytest.raises(ValueError):+ _parse_datetime([2026, 1, 1], [None, None])++ def test_none_time_values_coerced_to_zero(self):+ from fli.search._decoders import _parse_datetime++ # None minute → coerced to 0 by the `x or 0` expression.+ dt = _parse_datetime([2026, 7, 15], [10, None])+ assert dt == datetime(2026, 7, 15, 10, 0)+++class TestParseEmissions:+ def _detail_with_emissions(self, emissions_block):+ """Build a minimal detail list with the given emissions block at index 22."""+ detail = [None] * 23+ detail[22] = emissions_block+ return detail++ def test_missing_block_returns_all_none(self):+ result = _parse_emissions([])+ assert result == {"this_g": None, "typical_g": None, "delta_pct": None, "tag": None}++ def test_non_list_block_returns_all_none(self):+ result = _parse_emissions(self._detail_with_emissions("bad"))+ assert result["tag"] is None+ assert result["this_g"] is None++ @pytest.mark.parametrize(+ "tag_int, expected_tag",+ [+ (1, "lower"),+ (2, "typical"),+ (3, "higher"),+ (4, None),+ ],+ )+ def test_tag_int_mapping(self, tag_int, expected_tag):+ block = [None] * 12+ block[11] = tag_int+ result = _parse_emissions(self._detail_with_emissions(block))+ assert result["tag"] == expected_tag++ def test_g_values_extracted(self):+ block = [None] * 12+ block[7] = 150000 # this_g+ block[8] = 180000 # typical_g+ block[3] = -17 # delta_pct+ block[11] = 1+ result = _parse_emissions(self._detail_with_emissions(block))+ assert result["this_g"] == 150000+ assert result["typical_g"] == 180000+ assert result["delta_pct"] == -17+++class TestExtractBookingUrls:+ def test_returns_vendor_and_google_urls(self):+ block = ["https://vendor.com/book", None, ["/travel/clk?hl=en"]]+ vendor_url, google_url = _extract_booking_urls(block)+ assert vendor_url == "https://vendor.com/book"+ assert google_url == "/travel/clk?hl=en"++ def test_none_block_returns_none_none(self):+ assert _extract_booking_urls(None) == (None, None)++ def test_non_list_block_returns_none_none(self):+ assert _extract_booking_urls("string") == (None, None)++ def test_missing_google_url_returns_none(self):+ block = ["https://vendor.com"] # len < 3, no block[2]+ vendor_url, google_url = _extract_booking_urls(block)+ assert vendor_url == "https://vendor.com"+ assert google_url is None++ def test_google_url_without_travel_clk_not_returned(self):+ block = ["https://vendor.com", None, ["https://other.com/book"]]+ _, google_url = _extract_booking_urls(block)+ assert google_url is None++ def test_non_string_first_element_returns_none_vendor(self):+ block = [42, None, ["/travel/clk?x=1"]]+ vendor_url, _ = _extract_booking_urls(block)+ assert vendor_url is None+++class TestExtractFareName:+ def test_row21_position_preferred(self):+ row = [None] * 22+ row[21] = [None, None, None, "Basic Economy"]+ assert _extract_fare_name(row) == "Basic Economy"++ def test_falls_back_to_row14_nested(self):+ row = [None] * 22+ row[21] = [] # too short — len <= 3+ row[14] = [[[None, [None, "Main Cabin"]]]]+ assert _extract_fare_name(row) == "Main Cabin"++ def test_returns_none_when_both_absent(self):+ row = [None] * 22+ assert _extract_fare_name(row) is None++ def test_empty_string_in_row21_skipped(self):+ row = [None] * 22+ row[21] = [None, None, None, ""] # empty string is not a valid fare name+ assert _extract_fare_name(row) is None++ def test_row14_fallback_index_error_returns_none(self):+ row = [None] * 22+ row[21] = []+ row[14] = [[[]]] # too short to reach row[14][0][0][1][1]+ assert _extract_fare_name(row) is None+++class TestParseBookingChunk:+ def _make_booking_row(self, index=0, vendor_code="AA", vendor_name="American", price=100.0):+ """Build a minimal booking row that passes _try_parse_booking_row's shape checks."""+ return [+ index, # [0] int+ [[vendor_code, vendor_name]], # [1] vendor list+ None, # [2]+ [], # [3] flights+ None, # [4]+ None, # [5] URL block+ None, # [6]+ [[None, price]], # [7] price block+ ]++ def test_empty_chunk_returns_empty_list(self):+ assert parse_booking_chunk([]) == []++ def test_none_chunk_returns_empty_list(self):+ assert parse_booking_chunk(None) == []++ def test_finds_booking_row_at_top_level(self):+ row = self._make_booking_row(vendor_code="UA", price=250.0)+ result = parse_booking_chunk([row])+ assert len(result) == 1+ assert result[0].vendor_code == "UA"+ assert result[0].price == 250.0++ def test_finds_booking_row_nested_one_level(self):+ row = self._make_booking_row(vendor_code="DL", price=199.0)+ result = parse_booking_chunk([[row]])+ assert len(result) == 1+ assert result[0].vendor_code == "DL"++ def test_non_booking_shape_lists_are_ignored(self):+ # A list with a string first element doesn't match (needs int at [0]).+ result = parse_booking_chunk([["not", "a", "booking", "row", None, None, None, None]])+ assert result == []++ def test_multiple_booking_rows_all_returned(self):+ row1 = self._make_booking_row(index=0, vendor_code="AA", price=300.0)+ row2 = self._make_booking_row(index=1, vendor_code="UA", price=320.0)+ result = parse_booking_chunk([row1, row2])+ assert len(result) == 2+ codes = {r.vendor_code for r in result}+ assert codes == {"AA", "UA"}diff --git a/tests/search/test_helpers.py b/tests/search/test_helpers.pynew file mode 100644index 0000000..603a1af--- /dev/null+++ b/tests/search/test_helpers.py@@ -0,0 +1,106 @@+"""Unit tests for fli.search._helpers — the defensive accessors used by all decoders."""++from __future__ import annotations++import pytest++from fli.search._helpers import as_bool, as_int, as_non_negative_int, as_str, safe_get+++class TestSafeGet:+ def test_returns_element_at_valid_index(self):+ assert safe_get([1, 2, 3], 1) == 2++ def test_returns_none_for_out_of_bounds(self):+ assert safe_get([1], 5) is None++ def test_returns_none_for_negative_index(self):+ assert safe_get([1, 2], -1) is None++ def test_returns_none_for_non_list_string(self):+ assert safe_get("abc", 0) is None++ def test_returns_none_for_non_list_dict(self):+ assert safe_get({"a": 1}, 0) is None++ def test_returns_none_for_none_seq(self):+ assert safe_get(None, 0) is None++ def test_returns_none_for_empty_list(self):+ assert safe_get([], 0) is None++ def test_returns_falsy_zero_at_index(self):+ # 0 at a valid index is NOT None — callers rely on this distinction.+ assert safe_get([False, 0, None], 1) == 0++ def test_returns_false_at_index(self):+ assert safe_get([False, 0, None], 0) is False++ def test_returns_none_element_at_index(self):+ # None stored at a valid index should be returned as-is.+ assert safe_get([1, None, 3], 1) is None+++ "val, expected",+ [+ (True, True),+ # False is a valid bool — must NOT return None.+ (False, False),+ (1, None),+ (0, None),+ ("true", None),+ (None, None),+ ],+)+def test_as_bool(val, expected):+ assert as_bool(val) is expected+++ "val, expected",+ [+ ("hello", "hello"),+ # Only the empty string is rejected; whitespace-only is kept.+ (" ", " "),+ ("", None),+ (42, None),+ (True, None),+ (None, None),+ ],+)+def test_as_str(val, expected):+ assert as_str(val) == expected+++ "val, expected",+ [+ (5, 5),+ (0, 0),+ (-3, -3),+ # bool is a subclass of int in Python — must be explicitly rejected.+ (True, None),+ (False, None),+ (3.0, None),+ ("5", None),+ (None, None),+ ],+)+def test_as_int(val, expected):+ assert as_int(val) == expected+++ "val, expected",+ [+ (0, 0),+ (42, 42),+ (-1, None),+ # Inherits as_int rejection of bools.+ (True, None),+ (None, None),+ ],+)+def test_as_non_negative_int(val, expected):+ assert as_non_negative_int(val) == expecteddiff --git a/tests/search/test_proto.py b/tests/search/test_proto.pyindex 2a1c0d0..553936f 100644--- a/tests/search/test_proto.py+++ b/tests/search/test_proto.py@@ -63,17 +63,17 @@ class TestBuildBookingToken:assert decoded["field_7"] == 28assert decoded["field_14"] == 12345- def test_different_currencies(self):- for code in ("USD", "EUR", "GBP", "JPY", "INR"):- token = build_booking_token("S", "DL", "1", 1, 100, code)- decoded = decode_booking_token(token)- assert decoded["field_3"]["field_3"] == code-- def test_leg_index_in_field_2(self):- for idx in (0, 1, 2, 5, 10):- token = build_booking_token("S", "AA", "100", idx, 100, "USD")- decoded = decode_booking_token(token)- assert decoded["field_2"] == f"AA100#{idx}"+ @pytest.mark.parametrize("code", ["USD", "EUR", "GBP", "JPY", "INR"])+ def test_different_currencies(self, code):+ token = build_booking_token("S", "DL", "1", 1, 100, code)+ decoded = decode_booking_token(token)+ assert decoded["field_3"]["field_3"] == code++ @pytest.mark.parametrize("idx", [0, 1, 2, 5, 10])+ def test_leg_index_in_field_2(self, idx):+ token = build_booking_token("S", "AA", "100", idx, 100, "USD")+ decoded = decode_booking_token(token)+ assert decoded["field_2"] == f"AA100#{idx}"def test_price_varint_encoding(self):# 34680 spans 3 varint bytes: 0xf8 0x8e 0x02. Confirm round-trip.@@ -114,41 +114,33 @@ class TestVarintEncoding:assert decoded["field_1"] == "ABC"-class TestBuildBookingTokenValidation:- """Reject empty / negative inputs upfront.-- Guarantees no live POST is ever sent with a structurally broken token.- """-- def test_negative_price_rejected(self):- with pytest.raises(ValueError, match="price_cents must be non-negative"):- build_booking_token("S", "AA", "1", 1, -1, "USD")-- def test_empty_session_rejected(self):- with pytest.raises(ValueError, match="session_id must be non-empty"):- build_booking_token("", "AA", "1", 1, 100, "USD")-- def test_empty_airline_rejected(self):- with pytest.raises(ValueError, match="airline_code must be non-empty"):- build_booking_token("S", "", "1", 1, 100, "USD")-- def test_empty_flight_number_rejected(self):- with pytest.raises(ValueError, match="flight_number must be non-empty"):- build_booking_token("S", "AA", "", 1, 100, "USD")+ "session_id, airline_code, flight_number, price_cents, currency, exc_match",+ [+ ("S", "AA", "1", -1, "USD", "price_cents must be non-negative"),+ ("", "AA", "1", 100, "USD", "session_id must be non-empty"),+ ("S", "", "1", 100, "USD", "airline_code must be non-empty"),+ ("S", "AA", "", 100, "USD", "flight_number must be non-empty"),+ ("S", "AA", "1", 100, "", "currency must be non-empty"),+ ],+)+def test_build_booking_token_validation(+ session_id, airline_code, flight_number, price_cents, currency, exc_match+):+ """Reject empty / negative inputs upfront."""+ with pytest.raises(ValueError, match=exc_match):+ build_booking_token(session_id, airline_code, flight_number, 1, price_cents, currency)- def test_empty_currency_rejected(self):- with pytest.raises(ValueError, match="currency must be non-empty"):- build_booking_token("S", "AA", "1", 1, 100, "")- def test_non_ascii_session_id_encodes(self):- # If Google ever returns a non-ASCII session id, the builder must- # not crash — UTF-8 keeps round-trip equivalence for ASCII data- # while accepting arbitrary bytes for the future.- token = build_booking_token("Sé", "AA", "1", 1, 100, "USD")- decoded = decode_booking_token(token)- # decode_booking_token's ascii-decoder will replace the non-ascii- # byte, but the call doesn't raise.- assert "field_1" in decoded+def test_non_ascii_session_id_encodes():+ # If Google ever returns a non-ASCII session id, the builder must+ # not crash — UTF-8 keeps round-trip equivalence for ASCII data+ # while accepting arbitrary bytes for the future.+ token = build_booking_token("Sé", "AA", "1", 1, 100, "USD")+ decoded = decode_booking_token(token)+ # decode_booking_token's ascii-decoder will replace the non-ascii+ # byte, but the call doesn't raise.+ assert "field_1" in decodedclass TestDecodeBookingTokenEdgeCases:@@ -207,3 +199,78 @@ class TestExtractBookingTokenFromTfu:# by which validation step rejects first).with pytest.raises(ValueError):extract_booking_token_from_tfu("!!!!not-valid-base64!!!!")+++ "data, expected",+ [+ (b"\x00", (0, 1)),+ (b"\x7f", (127, 1)),+ (b"\x80\x01", (128, 2)),+ ],+)+def test_read_varint(data, expected):+ from fli.search._proto import _read_varint++ assert _read_varint(data, 0) == expected+++def test_read_varint_truncated_raises():+ from fli.search._proto import _read_varint++ with pytest.raises(IndexError):+ _read_varint(b"\x80", 0) # MSB set but no continuation byte+++class TestExtractBookingTokenFromTfuEdgeCases:+ """edge-case wire types that appear before field 1 in the outer tfu protobuf."""++ def _encode_tfu(self, raw: bytes) -> str:+ return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")++ @pytest.mark.parametrize(+ "prefix_bytes, token_bytes",+ [+ # field 2, wire 5 (fixed32): tag 0x15, 4 bytes+ (bytes([0x15]) + bytes([0x00, 0x00, 0x00, 0x01]), b"testtoken"),+ # field 3, wire 1 (fixed64): (3 << 3) | 1 = 0x19, 8 bytes+ (bytes([0x19]) + bytes(8), b"mytoken"),+ ],+ )+ def test_non_field1_wire_types_skipped(self, prefix_bytes, token_bytes):+ field1 = bytes([0x0A]) + bytes([len(token_bytes)]) + token_bytes+ tfu = self._encode_tfu(prefix_bytes + field1)+ assert extract_booking_token_from_tfu(tfu) == token_bytes.decode("ascii")++ def test_no_field1_raises_value_error(self):+ from fli.search._proto import _varint_field++ # Only field 2 as a varint — no field 1 present.+ raw = _varint_field(2, 42)+ tfu = self._encode_tfu(raw)+ with pytest.raises(ValueError, match="no field 1"):+ extract_booking_token_from_tfu(tfu)++ def test_unsupported_wire_type_raises_value_error(self):+ # Wire type 3 (start group) is not handled.+ # Tag for field 1, wire 3 = (1 << 3) | 3 = 11+ raw = bytes([11])+ tfu = self._encode_tfu(raw)+ with pytest.raises(ValueError, match="unsupported wire type"):+ extract_booking_token_from_tfu(tfu)+++class TestDecodeBookingTokenHexFallback:+ def test_non_decodable_nested_field_stored_as_hex(self):+ """A field neither printable ASCII nor a valid nested message.++ Should be stored as a hex string instead of raising.+ """+ from fli.search._proto import _length_delim++ # bytes([0x80]) is not valid ASCII and causes IndexError when parsed+ # as a nested protobuf varint — the decoder should fall back to hex.+ raw = _length_delim(3, bytes([0x80]))+ token = base64.b64encode(raw).decode("ascii")+ decoded = decode_booking_token(token)+ assert decoded["field_3"] == "80"diff --git a/tests/search/test_wire.py b/tests/search/test_wire.pyindex b370913..05fa22e 100644--- a/tests/search/test_wire.py+++ b/tests/search/test_wire.py@@ -72,3 +72,72 @@ class TestParseFirstWrbPayload:def test_returns_none_when_empty(self):assert parse_first_wrb_payload("") is None+++class TestIterWrbChunksEdgeCases:+ def test_bytes_input_works(self):+ body = _single_chunk([1, "hello"])+ chunks_str = list(iter_wrb_chunks(body))+ chunks_bytes = list(iter_wrb_chunks(body.encode("utf-8")))+ assert chunks_str == chunks_bytes++ def test_prefix_only_body_returns_nothing(self):+ # Body is only the JSONP prefix with no actual chunk data.+ assert list(iter_wrb_chunks(b")]}'\n\n")) == []++ def test_whitespace_only_body_returns_nothing(self):+ assert list(iter_wrb_chunks(" \n\n ")) == []++ def test_malformed_length_header_truncates_stream(self):+ # A non-numeric length header causes the parser to stop cleanly.+ body = ")]}'\n\nabc\n[not parsed]"+ assert list(iter_wrb_chunks(body)) == []++ def test_outer_is_dict_not_list_is_skipped(self):+ body = ")]}'\n\n" + json.dumps({"key": "value"})+ assert list(iter_wrb_chunks(body)) == []++ def test_wrb_row_with_none_inner_skipped(self):+ body = ")]}'\n\n" + json.dumps([["wrb.fr", None, None]])+ assert list(iter_wrb_chunks(body)) == []++ def test_wrb_row_with_non_string_inner_skipped(self):+ body = ")]}'\n\n" + json.dumps([["wrb.fr", None, [1, 2, 3]]])+ assert list(iter_wrb_chunks(body)) == []++ def test_wrb_row_too_short_skipped(self):+ body = ")]}'\n\n" + json.dumps([["wrb.fr", None]])+ assert list(iter_wrb_chunks(body)) == []++ def test_non_wrb_rows_between_multi_chunks_ignored(self):+ parts = [")]}'\n\n"]+ for payload in [[1, "alpha"], [2, "beta"]]:+ inner_json = json.dumps(payload, separators=(",", ":"))+ # Mix wrb.fr row with a di row in each chunk's outer list.+ outer = [["di", 44], ["wrb.fr", None, inner_json]]+ outer_json = json.dumps(outer, separators=(",", ":"))+ byte_len = len(outer_json.encode("utf-8")) + 2+ parts.append(f"{byte_len}\n{outer_json}\n")+ body = "".join(parts)+ chunks = list(iter_wrb_chunks(body))+ assert chunks == [[1, "alpha"], [2, "beta"]]++ def test_multiple_wrb_chunks_all_yielded_with_mixed_rows(self):+ # Two separate multi-chunks, each with only wrb.fr rows.+ body = _multi_chunk([10], [20], [30])+ chunks = list(iter_wrb_chunks(body))+ assert chunks == [[10], [20], [30]]+++class TestParseFirstWrbPayloadEdgeCases:+ def test_returns_none_for_only_non_wrb_rows(self):+ body = ")]}'\n\n" + json.dumps([["di", 44], ["af.httprm", 43, "x"]])+ assert parse_first_wrb_payload(body) is None++ def test_skips_invalid_inner_to_find_second_valid_chunk(self):+ # First wrb.fr row has an invalid inner JSON; second is valid.+ bad_inner = "{not valid"+ good_inner = json.dumps([42])+ outer = [["wrb.fr", None, bad_inner], ["wrb.fr", None, good_inner]]+ body = ")]}'\n\n" + json.dumps(outer)+ assert parse_first_wrb_payload(body) == [42]