From 9bb1c13327bd33005c02eb400762ffed849b0b03 Mon Sep 17 00:00:00 2001 From: dex-the-ai Date: Thu, 19 Nov 2026 03:16:52 +0000 Subject: [PATCH] Propagate hotel search errors instead of masking them as empty results CouchbaseClient.search_by_name/filter wrapped the search in a broad try/except that only printed the error. The SDK runs the search lazily in rows(), so a missing hotel_search index (or any search failure) came back as 200 []. An earlier failure raised UnboundLocalError instead. The router already maps exceptions to 500, so the client now lets them propagate. Also: POST /hotel/filter with no body now returns [] instead of a 500 AttributeError on None.model_dump(). Adds offline tests (fake scope + dependency override) for the search seam. They need no cluster. Co-Authored-By: Claude Opus 5.5 --- app/db.py | 90 +++++++++++------------- app/routers/hotel.py | 5 +- app/tests/test_hotel_search_errors.py | 98 +++++++++++++++++++++++++++ 3 files changed, 141 insertions(+), 52 deletions(-) create mode 100644 app/tests/test_hotel_search_errors.py diff --git a/app/db.py b/app/db.py index c9bf379..cf1fc23 100644 --- a/app/db.py +++ b/app/db.py @@ -147,57 +147,49 @@ def query(self, sql_query, *options, **kwargs): return self.scope.query(sql_query, *options, **kwargs) def search_by_name(self, name): - """Perform a full-text search for hotel names using the given name""" - try: - searchQuery = search.SearchRequest.create( - search.MatchQuery(name, field="name") - ) - searchResult = self.scope.search( - self.index_name, searchQuery, SearchOptions(limit=50, fields=["name"]) - ) - names = [] - for row in searchResult.rows(): - hotel = row.fields - names.append(hotel.get("name", "")) - except Exception as e: - print("Error while performing fts search", {e}) - return names + """Perform a full-text search for hotel names using the given name. + + Search errors (for example, a missing ``hotel_search`` index) are + raised to the caller instead of being swallowed, so the API can + report them rather than returning an empty result. + """ + search_query = search.SearchRequest.create( + search.MatchQuery(name, field="name") + ) + search_result = self.scope.search( + self.index_name, search_query, SearchOptions(limit=50, fields=["name"]) + ) + # rows() executes the request lazily, so errors surface here + return [row.fields.get("name", "") for row in search_result.rows()] def filter(self, filter: dict, limit, offset): - """Perform a full-text search with filters and pagination""" - try: - conjuncts = [] - - match_query_terms = ["description", "name", "title"] - conjuncts.extend( - [ - MatchQuery(filter[t], field=t) - for t in match_query_terms - if t in filter - ] - ) - term_query_terms = ["city", "country", "state"] - conjuncts.extend( - [TermQuery(filter[t], field=t) for t in term_query_terms if t in filter] - ) - - if conjuncts: - query = ConjunctionQuery(*conjuncts) - else: - return [] - - options = SearchOptions(fields=["*"], limit=limit, skip=offset) - - result = self.scope.search( - self.index_name, search.SearchRequest.create(query), options - ) - hotels = [] - for row in result.rows(): - hotel = row.fields - hotels.append(hotel) - except Exception as e: - print("Error while performing fts search", {e}) - return hotels + """Perform a full-text search with filters and pagination. + + Returns an empty list when no filter fields are given. Search errors + are raised to the caller. + """ + conjuncts = [] + + match_query_terms = ["description", "name", "title"] + conjuncts.extend( + [MatchQuery(filter[t], field=t) for t in match_query_terms if t in filter] + ) + term_query_terms = ["city", "country", "state"] + conjuncts.extend( + [TermQuery(filter[t], field=t) for t in term_query_terms if t in filter] + ) + + if not conjuncts: + return [] + + query = ConjunctionQuery(*conjuncts) + options = SearchOptions(fields=["*"], limit=limit, skip=offset) + + result = self.scope.search( + self.index_name, search.SearchRequest.create(query), options + ) + # rows() executes the request lazily, so errors surface here + return [row.fields for row in result.rows()] @cache diff --git a/app/routers/hotel.py b/app/routers/hotel.py index df18761..ae91492 100644 --- a/app/routers/hotel.py +++ b/app/routers/hotel.py @@ -90,9 +90,8 @@ def hotel_filter( ) -> List[Hotel]: """Hotel filter with various filters""" try: - hotels = db.filter( - hotel.model_dump(exclude_none=True), limit=limit, offset=offset - ) + filters = hotel.model_dump(exclude_none=True) if hotel else {} + hotels = db.filter(filters, limit=limit, offset=offset) return hotels except Exception as e: raise HTTPException(status_code=500, detail=f"Unexpected error: {e}") diff --git a/app/tests/test_hotel_search_errors.py b/app/tests/test_hotel_search_errors.py new file mode 100644 index 0000000..4ebca83 --- /dev/null +++ b/app/tests/test_hotel_search_errors.py @@ -0,0 +1,98 @@ +"""Offline tests for the hotel search seam (no Couchbase cluster needed). + +They check that search failures reach the API as errors instead of being +masked as empty results. +""" + +from types import SimpleNamespace + +import pytest +from fastapi.testclient import TestClient + +from app.db import CouchbaseClient, get_db +from app.main import app + + +class SearchIndexMissing(Exception): + pass + + +class _LazyFailingResult: + """Mimics the SDK: the search request only executes (and fails) in rows().""" + + def rows(self): + raise SearchIndexMissing("index hotel_search not found") + + +class _FakeScope: + def __init__(self, result): + self._result = result + + def search(self, *args, **kwargs): + return self._result + + +class _RowsResult: + def __init__(self, fields_list): + self._rows = [SimpleNamespace(fields=f) for f in fields_list] + + def rows(self): + return iter(self._rows) + + +def _client_with_scope(scope) -> CouchbaseClient: + client = CouchbaseClient.__new__(CouchbaseClient) # skip connect() + client.index_name = "hotel_search" + client.scope = scope + return client + + +class TestCouchbaseClientSearch: + def test_search_by_name_returns_names(self): + client = _client_with_scope( + _FakeScope(_RowsResult([{"name": "Seal View"}, {}])) + ) + assert client.search_by_name("Seal") == ["Seal View", ""] + + def test_search_by_name_propagates_lazy_search_error(self): + client = _client_with_scope(_FakeScope(_LazyFailingResult())) + with pytest.raises(SearchIndexMissing): + client.search_by_name("Seal") + + def test_filter_propagates_lazy_search_error(self): + client = _client_with_scope(_FakeScope(_LazyFailingResult())) + with pytest.raises(SearchIndexMissing): + client.filter({"city": "Santa Margarita"}, limit=10, offset=0) + + def test_filter_without_fields_returns_empty_without_searching(self): + client = _client_with_scope(None) # scope.search would fail if called + assert client.filter({}, limit=10, offset=0) == [] + + +@pytest.fixture +def failing_search_api(): + failing = _client_with_scope(_FakeScope(_LazyFailingResult())) + app.dependency_overrides[get_db] = lambda: failing + yield TestClient(app) + app.dependency_overrides.pop(get_db, None) + + +class TestHotelSearchErrorsReachApi: + def test_autocomplete_returns_500_when_search_fails(self, failing_search_api): + response = failing_search_api.get( + "/api/v1/hotel/autocomplete", params={"name": "Seal"} + ) + assert response.status_code == 500 + assert "hotel_search" in response.json()["detail"] + + def test_filter_returns_500_when_search_fails(self, failing_search_api): + response = failing_search_api.post( + "/api/v1/hotel/filter", json={"city": "Santa Margarita"} + ) + assert response.status_code == 500 + assert "hotel_search" in response.json()["detail"] + + def test_filter_without_body_returns_empty_list(self, failing_search_api): + response = failing_search_api.post("/api/v1/hotel/filter") + assert response.status_code == 200 + assert response.json() == []