Skip to content

Commit

Permalink
tests: add tests for _get_image_from_url
Browse files Browse the repository at this point in the history
  • Loading branch information
raphael0202 committed Oct 27, 2023
1 parent 0330216 commit a141d5a
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
2 changes: 1 addition & 1 deletion robotoff/utils/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
44 changes: 44 additions & 0 deletions tests/unit/utils/test_image.py
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit a141d5a

Please sign in to comment.