From cacba71caa74887c903f7bf02665cda9313349f0 Mon Sep 17 00:00:00 2001 From: Daniel Bauer Date: Thu, 15 Aug 2024 21:58:42 +0200 Subject: [PATCH] add utility method to add signposts from view --- django_signposting/utils.py | 23 ++++++++++++++++ tests/test_utils.py | 54 +++++++++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 django_signposting/utils.py create mode 100644 tests/test_utils.py diff --git a/django_signposting/utils.py b/django_signposting/utils.py new file mode 100644 index 0000000..31b2110 --- /dev/null +++ b/django_signposting/utils.py @@ -0,0 +1,23 @@ +from django.http import HttpResponse + + +def add_signposts(response: HttpResponse, **kwargs): + """ Adds signposting headers to the responses. + params: + response - the response object + kwargs - a map of relation types to a list of corresponding links. Each link can be a link or a tuple of link and media type. + """ + + if not hasattr(response, '_signposts'): + response._signposts = {} + + for key in kwargs.keys(): + + values = kwargs[key] + if isinstance(values, str) or isinstance(values, tuple): + values = [values] + + if key not in response._signposts: + response._signposts[key] = values + else: + response._signposts[key] += values \ No newline at end of file diff --git a/tests/test_utils.py b/tests/test_utils.py new file mode 100644 index 0000000..3933411 --- /dev/null +++ b/tests/test_utils.py @@ -0,0 +1,54 @@ +from django.http import HttpResponse +from django.conf import settings +from django_signposting.utils import add_signposts +import pytest + + +@pytest.fixture(scope="module", autouse=True) +def configure_django_settings(): + settings.configure() + + +def test_add_signpost(): + response = HttpResponse() + add_signposts(response, item="http://example.com") + + assert response._signposts["item"] == ["http://example.com"] + + +def test_add_multiple_signposts(): + response = HttpResponse() + add_signposts(response, + item="http://example.com", + author=["https://example2.com", "https://example3.com"] + ) + + assert response._signposts == { + "item": ["http://example.com"], + "author": [ + "https://example2.com", + "https://example3.com", + ] + } + + +def test_add_signposts_with_content_type(): + response = HttpResponse() + add_signposts(response, + item=("http://example.com", "text/json"), + author=["https://example2.com", "https://example3.com"] + ) + + assert response._signposts == { + "item": [("http://example.com", "text/json")], + "author": [ + "https://example2.com", + "https://example3.com", + ] + } + + +def test_add_signposts_from_dict(): + response = HttpResponse() + add_signposts(response, **{"cite-as": ["https://example.com"]}) + assert response._signposts["cite-as"] == ["https://example.com"]