Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
5 changes: 4 additions & 1 deletion serpapi/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ class SearchIDNotProvided(ValueError, SerpApiError):
class HTTPError(requests.exceptions.HTTPError, SerpApiError):
"""HTTP Error."""

pass
def __init__(self, http_error_exception: requests.exceptions.HTTPError):
self.status_code = http_error_exception.response.status_code
self.error = http_error_exception.response.json().get("error", None)
super().__init__(*http_error_exception.args, response=http_error_exception.response, request=http_error_exception.request)


class HTTPConnectionError(HTTPError, requests.exceptions.ConnectionError, SerpApiError):
Expand Down
18 changes: 18 additions & 0 deletions tests/test_exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import pytest
from unittest.mock import Mock, patch
import requests
import serpapi


def test_http_error():
"""Ensure that an HTTPError has the correct status code and error."""
mock_response = Mock()
mock_response.status_code = 401
mock_response.json.return_value = { "error": "Invalid API key" }

requests_error = requests.exceptions.HTTPError(response=mock_response, request=Mock())
http_error = serpapi.HTTPError(requests_error)

assert http_error.status_code == 401
assert http_error.error == "Invalid API key"
assert http_error.response == mock_response
12 changes: 11 additions & 1 deletion tests/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,10 @@ def test_account_without_credentials():

def test_account_with_bad_credentials(invalid_key_client):
"""Ensure that an HTTPError is raised when account is accessed with invalid API Credentials."""
with pytest.raises(serpapi.HTTPError):
with pytest.raises(serpapi.HTTPError) as exc_info:
invalid_key_client.account()

assert exc_info.value.response.status_code == 401


def test_account_with_credentials(client):
Expand All @@ -38,6 +40,14 @@ def test_account_with_credentials(client):
assert isinstance(account, dict)


def test_search_with_missing_params(client):
with pytest.raises(serpapi.HTTPError) as exc_info:
client.search({ "q": "" })

assert exc_info.value.status_code == 400
assert "Missing query `q` parameter" in exc_info.value.error


def test_coffee_search(coffee_search):
assert isinstance(coffee_search, serpapi.SerpResults)
assert hasattr(coffee_search, "__getitem__")
Expand Down
Loading