From 236aa072701a94b19cf004b9cf46d86efad56bc4 Mon Sep 17 00:00:00 2001 From: Lorenzo Vagliano Date: Tue, 8 Oct 2024 16:21:30 +0200 Subject: [PATCH] Added DefaultOrderingFilterBackend to the ArticleDocumentView in order to sort search output in descending order by default. --- scoap3/articles/api/views.py | 2 ++ scoap3/articles/tests/test_search.py | 40 ++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/scoap3/articles/api/views.py b/scoap3/articles/api/views.py index 96f324e3a..65695b7e2 100644 --- a/scoap3/articles/api/views.py +++ b/scoap3/articles/api/views.py @@ -1,5 +1,6 @@ from django_elasticsearch_dsl_drf.constants import LOOKUP_FILTER_RANGE, LOOKUP_QUERY_IN from django_elasticsearch_dsl_drf.filter_backends import ( + DefaultOrderingFilterBackend, FacetedSearchFilterBackend, FilteringFilterBackend, OrderingFilterBackend, @@ -104,6 +105,7 @@ def __init__(self, *args, **kwargs): FacetedSearchFilterBackend, FilteringFilterBackend, OrderingFilterBackend, + DefaultOrderingFilterBackend, ] renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES + [ArticleCSVRenderer] diff --git a/scoap3/articles/tests/test_search.py b/scoap3/articles/tests/test_search.py index 7274f02da..a60c7d891 100644 --- a/scoap3/articles/tests/test_search.py +++ b/scoap3/articles/tests/test_search.py @@ -9,3 +9,43 @@ def test_article_search(user, client): client.force_login(user) response = client.get(reverse("search:article-list")) assert response.status_code == status.HTTP_200_OK + + +def test_article_search_ordering_default(user, client, license): + client.force_login(user) + + articles = [ + { + "title": "Article 1", + "related_licenses": [license.id], + "publication_date": "2014-01-01", + }, + { + "title": "Article 2", + "related_licenses": [license.id], + "publication_date": "2014-01-02", + }, + { + "title": "Article 3", + "related_licenses": [license.id], + "publication_date": "2014-01-03", + }, + ] + + for article in articles: + response = client.post( + reverse("api:article-list"), + data=article, + ) + assert response.status_code == 201 + + response = client.get(reverse("search:article-list")) + data = response.json() + + publication_dates = [] + for result in data["results"]: + publication_dates.append(result["publication_date"]) + + assert publication_dates == sorted( + publication_dates, reverse=True + ), "Articles are not ordered by publication date in descending order"