diff --git a/robotoff/utils/image.py b/robotoff/utils/image.py index e233499c5e..800485551b 100644 --- a/robotoff/utils/image.py +++ b/robotoff/utils/image.py @@ -98,7 +98,7 @@ def _get_image_from_url( image_url: str, error_raise: bool = True, session: Optional[requests.Session] = None, -) -> requests.Request | None: +) -> requests.Response | None: auth = ( settings._off_net_auth if urlparse(image_url).netloc.endswith("openfoodfacts.net") diff --git a/tests/unit/utils/test_image.py b/tests/unit/utils/test_image.py new file mode 100644 index 0000000000..b2edbea384 --- /dev/null +++ b/tests/unit/utils/test_image.py @@ -0,0 +1,44 @@ +from unittest.mock import patch + +import pytest +import requests + +from robotoff.utils.image import ImageLoadingException, _get_image_from_url + + +@patch("robotoff.utils.image.requests.get") +def test__get_image_from_url(mock_get): + # Mock the response from requests.get + mock_response = mock_get.return_value + mock_response.content = b"fake image content" + mock_response.status_code = 200 + + # Call the function with an image URL + url = "https://example.com/image.jpg" + result = _get_image_from_url(url) + + # Check that requests.get was called with the correct URL + mock_get.assert_called_once_with(url, auth=None) + + # Check that the content of the response is the same as the mock content + assert result.content == b"fake image content" + + # Check that the status code of the response is the same as the mock + # status code + assert result.status_code == 200 + + # Test when r.ok returns False + mock_response.status_code = 404 + mock_response.content = b"" + mock_response.ok = False + with pytest.raises(ImageLoadingException): + _get_image_from_url(url) + + # Test when there is an error during HTTP request + mock_get.side_effect = requests.exceptions.SSLError + with pytest.raises(ImageLoadingException): + _get_image_from_url(url) + + # Check that the function returns None when error_raise is False + image = _get_image_from_url(url, error_raise=False) + assert image is None