Skip to content

Commit

Permalink
Add unit test for Discord webhook
Browse files Browse the repository at this point in the history
  • Loading branch information
VitalyVakhteev authored and justinclift committed Jul 10, 2023
1 parent a98542f commit c3598ac
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 12 deletions.
21 changes: 11 additions & 10 deletions redash/destinations/discord.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@ def configuration_schema(cls):
return {
"type": "object",
"properties": {
"url": {"type": "string", "title": "Discord Webhook URL"},
"name": {"type": "string", "title": "Discord Bot Name"}
"url": {"type": "string", "title": "Discord Webhook URL"}
},
"secret": ["url"],
}
Expand All @@ -40,19 +39,19 @@ def notify(self, alert, query, user, new_state, app, host, options):
"inline": True,
},
]
if alert.custom_body:
fields.append({"name": "Description", "value": alert.custom_body})
if alert.options.get("custom_body"):
fields.append({"name": "Description", "value": alert.options["custom_body"]})
if new_state == "triggered":
if alert.custom_subject:
text = alert.custom_subject
if alert.options.get("custom_subject"):
text = alert.options["custom_subject"]
else:
text = alert.name + " just triggered"
color = "12597547"
else:
text = alert.name + " went back to normal"
color = "2600544"

payload = {"name": options.get("name"), "content": text, "embeds": [{"color": color, "fields": fields}]}
payload = {"content": text, "embeds": [{"color": color, "fields": fields}]}
headers = {"Content-Type": "application/json"}
try:
resp = requests.post(
Expand All @@ -61,14 +60,16 @@ def notify(self, alert, query, user, new_state, app, host, options):
headers=headers,
timeout=5.0,
)
if resp.status_code != 200:
if resp.status_code != 200 and resp.status_code != 204:
logging.error(
"webhook send ERROR. status_code => {status}".format(
status=resp.status_code
)
)
except Exception:
logging.exception("webhook send ERROR.")
else:
logging.info(msg=f"webhook send SUCCESS")
except Exception as e:
logging.exception("webhook send ERROR: %s", e)


register(Discord)
70 changes: 68 additions & 2 deletions tests/handlers/test_destinations.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from tests import BaseTestCase
from mock import patch
import json
from unittest import mock

from redash.destinations.discord import Discord
from redash.models import NotificationDestination
from tests import BaseTestCase
from redash.destinations.slack import Slack


Expand Down Expand Up @@ -97,3 +99,67 @@ def test_post(self):
d = NotificationDestination.query.get(d.id)
self.assertEqual(d.name, data["name"])
self.assertEqual(d.options["url"], data["options"]["url"])


def test_discord_notify_calls_requests_post():
alert = mock.Mock(spec_set=["id", "name", "options", "render_template"])
alert.id = 1
alert.name = "Test Alert"
alert.options = {
"custom_subject": "Test custom subject",
"custom_body": "Test custom body",
}
alert.render_template = mock.Mock(return_value={"Rendered": "template"})
query = mock.Mock()
query.id = 1

user = mock.Mock()
app = mock.Mock()
host = "https://localhost:5000"
options = {
"url": "https://discordapp.com/api/webhooks/test"
}

new_state = "triggered"
destination = Discord(options)

with mock.patch('redash.destinations.discord.requests.post') as mock_post:
mock_response = mock.Mock()
mock_response.status_code = 204
mock_post.return_value = mock_response

destination.notify(alert, query, user, new_state, app, host, options)

expected_payload = {
"content": "Test custom subject",
"embeds": [
{
"color": "12597547",
"fields": [
{
"name": "Query",
"value": f"{host}/queries/{query.id}",
"inline": True
},
{
"name": "Alert",
"value": f"{host}/alerts/{alert.id}",
"inline": True
},
{
"name": "Description",
"value": "Test custom body"
}
]
}
]
}

mock_post.assert_called_once_with(
"https://discordapp.com/api/webhooks/test",
data=json.dumps(expected_payload),
headers={"Content-Type": "application/json"},
timeout=5.0
)

assert mock_response.status_code == 204

0 comments on commit c3598ac

Please sign in to comment.