Skip to content
Open
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
90 changes: 41 additions & 49 deletions app/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 2 additions & 3 deletions app/routers/hotel.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
98 changes: 98 additions & 0 deletions app/tests/test_hotel_search_errors.py
Original file line number Diff line number Diff line change
@@ -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() == []
Loading