Encode webhook POST body as utf-8. Fixes #130

This commit is contained in:
Pēteris Caune 2017-08-14 22:20:57 +03:00
parent 56dfeb7996
commit 8d58a3a361
2 changed files with 18 additions and 2 deletions

View File

@ -1,3 +1,5 @@
# coding: utf-8
from datetime import timedelta as td from datetime import timedelta as td
import json import json
@ -7,6 +9,7 @@ from hc.api.models import Channel, Check, Notification
from hc.test import BaseTestCase from hc.test import BaseTestCase
from mock import patch from mock import patch
from requests.exceptions import ConnectionError, Timeout from requests.exceptions import ConnectionError, Timeout
from six import binary_type
class NotifyTestCase(BaseTestCase): class NotifyTestCase(BaseTestCase):
@ -100,7 +103,8 @@ class NotifyTestCase(BaseTestCase):
self.assertEqual(args[1], "http://example.com") self.assertEqual(args[1], "http://example.com")
# spaces should not have been urlencoded: # spaces should not have been urlencoded:
self.assertTrue(kwargs["data"].startswith("The Time Is 2")) payload = kwargs["data"].decode("utf-8")
self.assertTrue(payload.startswith("The Time Is 2"))
@patch("hc.api.transports.requests.request") @patch("hc.api.transports.requests.request")
def test_webhooks_dollarsign_escaping(self, mock_get): def test_webhooks_dollarsign_escaping(self, mock_get):
@ -129,6 +133,18 @@ class NotifyTestCase(BaseTestCase):
"get", "http://bar", headers={"User-Agent": "healthchecks.io"}, "get", "http://bar", headers={"User-Agent": "healthchecks.io"},
timeout=5) timeout=5)
@patch("hc.api.transports.requests.request")
def test_webhooks_handle_unicode_post_body(self, mock_request):
template = u"http://example.com\n\n(╯°□°)╯︵ ┻━┻"
self._setup_data("webhook", template)
self.check.save()
self.channel.notify(self.check)
args, kwargs = mock_request.call_args
# unicode should be encoded into utf-8
self.assertTrue(isinstance(kwargs["data"], binary_type))
def test_email(self): def test_email(self):
self._setup_data("email", "alice@example.org") self._setup_data("email", "alice@example.org")
self.channel.notify(self.check) self.channel.notify(self.check)

View File

@ -156,7 +156,7 @@ class Webhook(HttpTransport):
url = self.prepare(url, check, urlencode=True) url = self.prepare(url, check, urlencode=True)
if self.channel.post_data: if self.channel.post_data:
payload = self.prepare(self.channel.post_data, check) payload = self.prepare(self.channel.post_data, check)
return self.post(url, data=payload) return self.post(url, data=payload.encode("utf-8"))
else: else:
return self.get(url) return self.get(url)