Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/api/hotel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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}")
87 changes: 38 additions & 49 deletions src/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()]
58 changes: 58 additions & 0 deletions src/tests/test_db_search_errors.py
Original file line number Diff line number Diff line change
@@ -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) == []
Loading