barunsaha commited on
Commit
27e940d
·
1 Parent(s): 6371053

Skip image search when Pexels API key is not set; add new test cases

Browse files
src/slidedeckai/helpers/image_search.py CHANGED
@@ -4,6 +4,7 @@ Search photos using Pexels API.
4
  import logging
5
  import os
6
  import random
 
7
  from io import BytesIO
8
  from typing import Union, Literal
9
  from urllib.parse import urlparse, parse_qs
@@ -15,6 +16,18 @@ from dotenv import load_dotenv
15
  load_dotenv()
16
 
17
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  REQUEST_TIMEOUT = 12
19
  MAX_PHOTOS = 3
20
 
@@ -50,23 +63,27 @@ def search_pexels(
50
  per_page: No. of results to be displayed per page.
51
 
52
  Returns:
53
- The JSON response from the Pexels API containing search results.
 
54
 
55
  Raises:
56
  requests.exceptions.RequestException: If the request to the Pexels API fails.
57
  """
58
- url = 'https://api.pexels.com/v1/search'
59
- headers = {
60
- 'Authorization': os.getenv('PEXEL_API_KEY'),
61
- 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0',
62
- }
63
  params = {
64
  'query': query,
65
  'size': size,
66
  'page': 1,
67
  'per_page': per_page
68
  }
69
- response = requests.get(url, headers=headers, params=params, timeout=REQUEST_TIMEOUT)
 
 
 
 
 
70
  response.raise_for_status() # Ensure the request was successful
71
 
72
  return response.json()
@@ -83,8 +100,12 @@ def get_photo_url_from_api_response(
83
  json_response: The JSON response.
84
 
85
  Returns:
86
- The selected photo URL and page URL or `None`.
 
87
  """
 
 
 
88
  page_url = None
89
  photo_url = None
90
 
@@ -123,11 +144,7 @@ def get_image_from_url(url: str) -> BytesIO:
123
  Raises:
124
  requests.exceptions.RequestException: If the request to the URL fails.
125
  """
126
- headers = {
127
- 'Authorization': os.getenv('PEXEL_API_KEY'),
128
- 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0',
129
- }
130
- response = requests.get(url, headers=headers, stream=True, timeout=REQUEST_TIMEOUT)
131
  response.raise_for_status()
132
  image_data = BytesIO(response.content)
133
 
 
4
  import logging
5
  import os
6
  import random
7
+ import warnings
8
  from io import BytesIO
9
  from typing import Union, Literal
10
  from urllib.parse import urlparse, parse_qs
 
16
  load_dotenv()
17
 
18
 
19
+ # If PEXEL_API_KEY env var is unavailable, issue a one-time warning
20
+ if not os.getenv('PEXEL_API_KEY'):
21
+ warnings.warn(
22
+ 'PEXEL_API_KEY environment variable is not set. '
23
+ 'Image search functionality will not work without it.'
24
+ )
25
+
26
+ PEXELS_URL = 'https://api.pexels.com/v1/search'
27
+ REQUEST_HEADER = {
28
+ 'Authorization': os.getenv('PEXEL_API_KEY'),
29
+ 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0',
30
+ }
31
  REQUEST_TIMEOUT = 12
32
  MAX_PHOTOS = 3
33
 
 
63
  per_page: No. of results to be displayed per page.
64
 
65
  Returns:
66
+ The JSON response from the Pexels API containing search results. Empty dict if API key
67
+ is not set.
68
 
69
  Raises:
70
  requests.exceptions.RequestException: If the request to the Pexels API fails.
71
  """
72
+ if not os.getenv('PEXEL_API_KEY'):
73
+ return {}
74
+
 
 
75
  params = {
76
  'query': query,
77
  'size': size,
78
  'page': 1,
79
  'per_page': per_page
80
  }
81
+ response = requests.get(
82
+ PEXELS_URL,
83
+ headers=REQUEST_HEADER,
84
+ params=params,
85
+ timeout=REQUEST_TIMEOUT
86
+ )
87
  response.raise_for_status() # Ensure the request was successful
88
 
89
  return response.json()
 
100
  json_response: The JSON response.
101
 
102
  Returns:
103
+ The selected photo URL and page URL or `None`. Empty tuple if no photos found or API key
104
+ is not set.
105
  """
106
+ if not os.getenv('PEXEL_API_KEY'):
107
+ return None, None
108
+
109
  page_url = None
110
  photo_url = None
111
 
 
144
  Raises:
145
  requests.exceptions.RequestException: If the request to the URL fails.
146
  """
147
+ response = requests.get(url, headers=REQUEST_HEADER, stream=True, timeout=REQUEST_TIMEOUT)
 
 
 
 
148
  response.raise_for_status()
149
  image_data = BytesIO(response.content)
150
 
tests/unit/test_image_search.py CHANGED
@@ -42,7 +42,6 @@ def _dummy_requests_get_success_search(
42
  timeout: int
43
  ):
44
  """Return a successful mock response for search_pexels."""
45
-
46
  # Validate that the function under test passes expected args
47
  assert 'Authorization' in headers
48
  assert 'User-Agent' in headers
@@ -72,7 +71,6 @@ def _dummy_requests_get_image(
72
  stream: bool, timeout: int
73
  ):
74
  """Return a mock image response for get_image_from_url."""
75
-
76
  assert stream is True
77
  assert 'Authorization' in headers
78
  data = b'\x89PNG\r\n\x1a\n...'
@@ -169,3 +167,22 @@ def test_search_pexels_raises_on_request_error(monkeypatch) -> None:
169
 
170
  with pytest.raises(RuntimeError):
171
  image_search.search_pexels(query='x')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  timeout: int
43
  ):
44
  """Return a successful mock response for search_pexels."""
 
45
  # Validate that the function under test passes expected args
46
  assert 'Authorization' in headers
47
  assert 'User-Agent' in headers
 
71
  stream: bool, timeout: int
72
  ):
73
  """Return a mock image response for get_image_from_url."""
 
74
  assert stream is True
75
  assert 'Authorization' in headers
76
  data = b'\x89PNG\r\n\x1a\n...'
 
167
 
168
  with pytest.raises(RuntimeError):
169
  image_search.search_pexels(query='x')
170
+
171
+
172
+ def test_search_pexels_returns_empty_when_no_api_key(monkeypatch) -> None:
173
+ """When PEXEL_API_KEY is not set, search_pexels should return an empty dict."""
174
+ monkeypatch.delenv('PEXEL_API_KEY', raising=False)
175
+ result = image_search.search_pexels(query='people')
176
+
177
+ assert result == {}
178
+
179
+
180
+ def test_get_photo_url_from_api_response_returns_none_when_no_api_key(monkeypatch) -> None:
181
+ """When PEXEL_API_KEY is not set, get_photo_url_from_api_response should return (None, None)."""
182
+ photos = [
183
+ {'url': 'https://pexels.com/photo/1', 'src': {'large': 'https://images/1_large.jpg'}}
184
+ ]
185
+ monkeypatch.delenv('PEXEL_API_KEY', raising=False)
186
+ result = image_search.get_photo_url_from_api_response({'photos': photos})
187
+
188
+ assert result == (None, None)