Skip to content

Commit

Permalink
Fix #70 -- Mute HTTP status code errors (#71)
Browse files Browse the repository at this point in the history
  • Loading branch information
codingjoe authored Apr 22, 2024
1 parent aa0eddb commit c82278d
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
10 changes: 9 additions & 1 deletion sam/contrib/brave/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,16 @@ def search(query: str, _context=None) -> str:
try:
results = api.search(query)["web"]
except brave.BraveSearchAPIError:
logger.exception("Failed to search the web for query: %s", query)
logger.warning(
"Failed to search the web for query: %s", query, exc_info=True
)
return "search failed"
except KeyError:
logger.exception(
"The response from the web search API is missing the expected key %r",
"web",
)
return "search failed, do not retry"
else:
if not results["results"]:
logger.warning("No results found for query: %s", query)
Expand Down
28 changes: 27 additions & 1 deletion tests/test_tools.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
import json
import logging
import smtplib
from unittest import mock

import pytest
import requests
from bs4 import ParserRejectedMarkup
from slack_sdk.errors import SlackClientError

import sam.contrib.algolia.tools
import sam.contrib.brave.tools
import sam.slack
from sam import tools
from sam.contrib import algolia
from sam.contrib.brave import BraveSearchAPIError
from sam.contrib.github.tools import create_github_issue


Expand Down Expand Up @@ -57,6 +58,31 @@ def test_web_search__with_coordinates():
)


def test_web_search__brave_error(monkeypatch, caplog):
client = mock.MagicMock()
client.__enter__().search = mock.Mock(side_effect=BraveSearchAPIError())
monkeypatch.setattr("sam.contrib.brave.tools.brave.get_client", lambda: client)
with caplog.at_level(logging.WARN):
output = sam.contrib.brave.tools.search("ferien")
assert client.__enter__().search.called
assert "Failed to search the web for query: ferien" in caplog.text
assert output == "search failed"


def test_web_search__key_error(monkeypatch, caplog):
client = mock.MagicMock()
client.__enter__().search = mock.Mock(return_value={})
monkeypatch.setattr("sam.contrib.brave.tools.brave.get_client", lambda: client)
with caplog.at_level(logging.ERROR):
output = sam.contrib.brave.tools.search("ferien")
assert client.__enter__().search.called
assert (
"The response from the web search API is missing the expected key"
in caplog.text
)
assert output == "search failed, do not retry"


def test_fetch_website():
assert "GitHub, Inc" in tools.fetch_website("https://github.com/")

Expand Down

0 comments on commit c82278d

Please sign in to comment.