Skip to content

Commit

Permalink
Add a warning when source query parameter contains invalid values (#3949
Browse files Browse the repository at this point in the history
)

* Add logging when source has invalid value

Signed-off-by: Olga Bulat <[email protected]>

* Add a test

Signed-off-by: Olga Bulat <[email protected]>

---------

Signed-off-by: Olga Bulat <[email protected]>
Co-authored-by: Olga Bulat <[email protected]>
  • Loading branch information
manojks1999 and obulat authored Apr 2, 2024
1 parent a51ac8d commit 12d7162
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
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

0 comments on commit 12d7162

Please sign in to comment.