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
11 changes: 10 additions & 1 deletion src/routers/search_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,14 @@ def search( # noqa: C901
bool,
Query(
description="If true, the results are sorted by id."
"By default they are sorted by best score.",
" By default they are sorted by best score.",
),
] = False,
sort_by_date_modified: Annotated[
bool,
Query(
description="If true, the results are sorted by date_modified (newest first)."
" By default they are sorted by best score.",
),
] = False,
limit: Annotated[int, Query(ge=1, le=LIMIT_MAX)] = 10,
Expand Down Expand Up @@ -196,6 +203,8 @@ def search( # noqa: C901
sort: dict[str, str | dict[str, str]] = {}
if sort_by_id:
sort = {"identifier": "asc"}
elif sort_by_date_modified:
sort = {"date_modified": "desc"}
else:
sort = {"_score": {"order": "desc"}}

Expand Down
16 changes: 14 additions & 2 deletions src/tests/routers/search_routers/test_search_routers.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import json
from http import HTTPStatus
from typing import Sequence
from unittest.mock import Mock

import pytest
Expand Down Expand Up @@ -44,7 +43,7 @@ def test_search_happy_path_get_all(client: TestClient, mocked_privileged_token:

response = client.post("/events", json=body, headers={"Authorization": "Fake token"})
response.raise_for_status()
identifier = response.json()['identifier']
identifier = response.json()["identifier"]
mock_elasticsearch(filename_mock="event_search.json", identifier=identifier)

search_service = "/search/events"
Expand Down Expand Up @@ -145,6 +144,19 @@ def test_search_bad_offset(client: TestClient, search_router):
]


@pytest.mark.parametrize("search_router", sr.router_list)
def test_search_sort_by_date_modified(client: TestClient, search_router):
mock_elasticsearch(filename_mock=f"{search_router.es_index}_search.json")

search_service = f"/search/{search_router.resource_name_plural}"
params = {"search_query": "description", "sort_by_date_modified": True}
response = client.get(search_service, params=params)

assert response.status_code == 200, response.json()
_, kwargs = ElasticsearchSingleton().client.search.call_args
assert kwargs["sort"] == {"date_modified": "desc"}


def mock_elasticsearch(filename_mock: str, identifier: str = ""):
with open(path_test_resources() / "elasticsearch" / filename_mock, "r") as f:
mocked_results = json.load(f)
Expand Down