From c8478602c19c5cb9a3a6daa70083e79e9920af8f Mon Sep 17 00:00:00 2001 From: dex-the-ai Date: Wed, 18 Nov 2026 15:27:46 +0000 Subject: [PATCH] Let hotel search errors reach the API layer instead of masking them CouchbaseClient.search_by_name and filter caught every exception, printed it, and fell through. A missing/broken hotel_search index (the SDK raises while streaming rows) therefore returned HTTP 200 [] and looked like "no hotels"; an error raised before the result list existed crashed with UnboundLocalError instead of the real Couchbase error. The client adapter now lets search errors propagate, so error handling lives in one place: the hotel routes, which already map exceptions to 500. Those routes use hotel_ns.abort so the message is not mangled by marshal_with. Adds cluster-free unit tests for both failure modes. Co-Authored-By: Claude Opus 5.5 --- src/api/hotel.py | 4 +- src/db.py | 87 +++++++++++++----------------- src/tests/test_db_search_errors.py | 58 ++++++++++++++++++++ 3 files changed, 98 insertions(+), 51 deletions(-) create mode 100644 src/tests/test_db_search_errors.py diff --git a/src/api/hotel.py b/src/api/hotel.py index fdc4322..94f8828 100644 --- a/src/api/hotel.py +++ b/src/api/hotel.py @@ -44,7 +44,7 @@ def get(self): result = couchbase_db.search_by_name(name=name) return [{"name": name} for name in result], 200 except (CouchbaseException, Exception) as e: - return f"Unexpected error: {e}", 500 + hotel_ns.abort(500, f"Unexpected error: {e}") @hotel_ns.route("/filter") @@ -80,4 +80,4 @@ def post(self): hotels = couchbase_db.filter(data, limit=limit, offset=offset) return hotels, 200 except (CouchbaseException, Exception) as e: - return f"Unexpected error: {e}", 500 + hotel_ns.abort(500, f"Unexpected error: {e}") diff --git a/src/db.py b/src/db.py index b869512..1758818 100644 --- a/src/db.py +++ b/src/db.py @@ -143,54 +143,43 @@ 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 propagate to the caller (the API layer maps them to a + 500 response) instead of being swallowed here. + """ + 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"]) + ) + return [row.fields.get("name", "") for row in search_result.rows()] def filter(self, filter, 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. + + Search errors propagate to the caller (the API layer maps them to a + 500 response) instead of being swallowed here. + """ + 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 + ) + return [row.fields for row in result.rows()] diff --git a/src/tests/test_db_search_errors.py b/src/tests/test_db_search_errors.py new file mode 100644 index 0000000..3559066 --- /dev/null +++ b/src/tests/test_db_search_errors.py @@ -0,0 +1,58 @@ +"""Unit tests for CouchbaseClient search error propagation. + +These tests need no running cluster: they replace the scope with a stub +whose ``search`` raises, and check that the route layer (which maps +exceptions to HTTP 500) receives the original Couchbase error. +""" + +import pytest +from couchbase.exceptions import CouchbaseException + +from src.db import CouchbaseClient + + +def _raise(): + raise CouchbaseException(message="search index unavailable") + + +class _FailingScope: + """Fails when the search request is issued.""" + + def search(self, *args, **kwargs): + _raise() + + +class _LazyFailingResult: + def rows(self): + _raise() + yield # pragma: no cover - makes this a generator like the SDK's + + +class _LazyFailingScope: + """Fails while streaming rows, as the SDK does for a missing index.""" + + def search(self, *args, **kwargs): + return _LazyFailingResult() + + +@pytest.fixture(params=[_FailingScope, _LazyFailingScope]) +def client_with_failing_search(request): + client = CouchbaseClient() + client.scope = request.param() + client.index_name = "hotel_search" + return client + + +def test_search_by_name_propagates_couchbase_error(client_with_failing_search): + with pytest.raises(CouchbaseException, match="search index unavailable"): + client_with_failing_search.search_by_name("KCL") + + +def test_filter_propagates_couchbase_error(client_with_failing_search): + with pytest.raises(CouchbaseException, match="search index unavailable"): + client_with_failing_search.filter({"city": "Santa Margarita"}, 10, 0) + + +def test_filter_without_search_fields_returns_empty_list(): + client = CouchbaseClient() + assert client.filter({}, 10, 0) == []