Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a warning when source query parameter contains invalid values #3949

Merged
merged 2 commits into from
Apr 2, 2024
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
12 changes: 11 additions & 1 deletion api/api/serializers/media_serializers.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
from collections import namedtuple

from django.conf import settings
Expand Down Expand Up @@ -29,6 +30,8 @@
from api.utils.url import add_protocol


logger = logging.getLogger(__name__)

#######################
# Request serializers #
#######################
Expand Down Expand Up @@ -396,7 +399,14 @@ def validate_source(self, value):
return value
else:
sources = value.lower().split(",")
valid_sources = [source for source in sources if source in allowed_sources]
valid_sources = set(
[source for source in sources if source in allowed_sources]
)
if len(sources) > len(valid_sources):
invalid_sources = set(sources).difference(valid_sources)
logger.warning(
f"Invalid sources in search query: {invalid_sources}; sources query: '{value}'"
)
return ",".join(valid_sources)

def validate_excluded_source(self, input_sources):
Expand Down
21 changes: 21 additions & 0 deletions api/test/unit/serializers/test_media_serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,27 @@ def test_media_serializer_adds_license_url_if_missing(
assert repr["license_url"] == "https://creativecommons.org/publicdomain/zero/1.0/"


def test_media_serializer_logs_when_invalid_or_duplicate_source(media_type_config):
sources = {
"image": ("flickr,flickr,invalid", "flickr"),
"audio": ("freesound,freesound,invalid", "freesound"),
}
with patch("api.serializers.media_serializers.logger.warning") as mock_logger:
serializer_class = media_type_config.search_request_serializer(
context={"media_type": media_type_config.media_type},
data={"source": sources[media_type_config.media_type][0]},
)
assert serializer_class.is_valid()
assert (
serializer_class.validated_data["source"]
== sources[media_type_config.media_type][1]
)
mock_logger.assert_called_with(
f"Invalid sources in search query: {{'invalid'}}; "
f"sources query: '{sources[media_type_config.media_type][0]}'"
)


@pytest.mark.parametrize(
"has_sensitive_text",
(True, False),
Expand Down