You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

479 lines
16 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. # coding: utf-8
  2. from datetime import timedelta as td
  3. import json
  4. from django.core import mail
  5. from django.utils.timezone import now
  6. from hc.api.models import Channel, Check, Notification
  7. from hc.test import BaseTestCase
  8. from mock import patch
  9. from requests.exceptions import ConnectionError, Timeout
  10. from six import binary_type
  11. class NotifyTestCase(BaseTestCase):
  12. def _setup_data(self, kind, value, status="down", email_verified=True):
  13. self.check = Check()
  14. self.check.status = status
  15. self.check.user = self.alice
  16. self.check.last_ping = now() - td(minutes=61)
  17. self.check.save()
  18. self.channel = Channel(user=self.alice)
  19. self.channel.kind = kind
  20. self.channel.value = value
  21. self.channel.email_verified = email_verified
  22. self.channel.save()
  23. self.channel.checks.add(self.check)
  24. @patch("hc.api.transports.requests.request")
  25. def test_webhook(self, mock_get):
  26. self._setup_data("webhook", "http://example")
  27. mock_get.return_value.status_code = 200
  28. self.channel.notify(self.check)
  29. mock_get.assert_called_with(
  30. "get", u"http://example",
  31. headers={"User-Agent": "healthchecks.io"}, timeout=5)
  32. @patch("hc.api.transports.requests.request", side_effect=Timeout)
  33. def test_webhooks_handle_timeouts(self, mock_get):
  34. self._setup_data("webhook", "http://example")
  35. self.channel.notify(self.check)
  36. n = Notification.objects.get()
  37. self.assertEqual(n.error, "Connection timed out")
  38. @patch("hc.api.transports.requests.request", side_effect=ConnectionError)
  39. def test_webhooks_handle_connection_errors(self, mock_get):
  40. self._setup_data("webhook", "http://example")
  41. self.channel.notify(self.check)
  42. n = Notification.objects.get()
  43. self.assertEqual(n.error, "Connection failed")
  44. @patch("hc.api.transports.requests.request")
  45. def test_webhooks_ignore_up_events(self, mock_get):
  46. self._setup_data("webhook", "http://example", status="up")
  47. self.channel.notify(self.check)
  48. self.assertFalse(mock_get.called)
  49. self.assertEqual(Notification.objects.count(), 0)
  50. @patch("hc.api.transports.requests.request")
  51. def test_webhooks_handle_500(self, mock_get):
  52. self._setup_data("webhook", "http://example")
  53. mock_get.return_value.status_code = 500
  54. self.channel.notify(self.check)
  55. n = Notification.objects.get()
  56. self.assertEqual(n.error, "Received status code 500")
  57. @patch("hc.api.transports.requests.request")
  58. def test_webhooks_support_variables(self, mock_get):
  59. template = "http://host/$CODE/$STATUS/$TAG1/$TAG2/?name=$NAME"
  60. self._setup_data("webhook", template)
  61. self.check.name = "Hello World"
  62. self.check.tags = "foo bar"
  63. self.check.save()
  64. self.channel.notify(self.check)
  65. url = u"http://host/%s/down/foo/bar/?name=Hello%%20World" \
  66. % self.check.code
  67. args, kwargs = mock_get.call_args
  68. self.assertEqual(args[0], "get")
  69. self.assertEqual(args[1], url)
  70. self.assertEqual(kwargs["headers"], {"User-Agent": "healthchecks.io"})
  71. self.assertEqual(kwargs["timeout"], 5)
  72. @patch("hc.api.transports.requests.request")
  73. def test_webhooks_support_post(self, mock_request):
  74. template = "http://example.com\n\nThe Time Is $NOW"
  75. self._setup_data("webhook", template)
  76. self.check.save()
  77. self.channel.notify(self.check)
  78. args, kwargs = mock_request.call_args
  79. self.assertEqual(args[0], "post")
  80. self.assertEqual(args[1], "http://example.com")
  81. # spaces should not have been urlencoded:
  82. payload = kwargs["data"].decode("utf-8")
  83. self.assertTrue(payload.startswith("The Time Is 2"))
  84. @patch("hc.api.transports.requests.request")
  85. def test_webhooks_dollarsign_escaping(self, mock_get):
  86. # If name or tag contains what looks like a variable reference,
  87. # that should be left alone:
  88. template = "http://host/$NAME"
  89. self._setup_data("webhook", template)
  90. self.check.name = "$TAG1"
  91. self.check.tags = "foo"
  92. self.check.save()
  93. self.channel.notify(self.check)
  94. url = u"http://host/%24TAG1"
  95. mock_get.assert_called_with(
  96. "get", url, headers={"User-Agent": "healthchecks.io"}, timeout=5)
  97. @patch("hc.api.transports.requests.request")
  98. def test_webhook_fires_on_up_event(self, mock_get):
  99. self._setup_data("webhook", "http://foo\nhttp://bar", status="up")
  100. self.channel.notify(self.check)
  101. mock_get.assert_called_with(
  102. "get", "http://bar", headers={"User-Agent": "healthchecks.io"},
  103. timeout=5)
  104. @patch("hc.api.transports.requests.request")
  105. def test_webhooks_handle_unicode_post_body(self, mock_request):
  106. template = u"http://example.com\n\n(╯°□°)╯︵ ┻━┻"
  107. self._setup_data("webhook", template)
  108. self.check.save()
  109. self.channel.notify(self.check)
  110. args, kwargs = mock_request.call_args
  111. # unicode should be encoded into utf-8
  112. self.assertTrue(isinstance(kwargs["data"], binary_type))
  113. @patch("hc.api.transports.requests.request")
  114. def test_webhooks_handle_json_value(self, mock_request):
  115. definition = {"url_down": "http://foo.com"}
  116. self._setup_data("webhook", json.dumps(definition))
  117. self.channel.notify(self.check)
  118. headers = {"User-Agent": "healthchecks.io"}
  119. mock_request.assert_called_with(
  120. "get", "http://foo.com", headers=headers, timeout=5)
  121. @patch("hc.api.transports.requests.request")
  122. def test_webhooks_handle_json_up_event(self, mock_request):
  123. definition = {"url_up": "http://bar"}
  124. self._setup_data("webhook", json.dumps(definition), status="up")
  125. self.channel.notify(self.check)
  126. headers = {"User-Agent": "healthchecks.io"}
  127. mock_request.assert_called_with(
  128. "get", "http://bar", headers=headers, timeout=5)
  129. @patch("hc.api.transports.requests.request")
  130. def test_webhooks_handle_post_headers(self, mock_request):
  131. definition = {
  132. "url_down": "http://foo.com",
  133. "post_data": "data",
  134. "headers": {"Content-Type": "application/json"}
  135. }
  136. self._setup_data("webhook", json.dumps(definition))
  137. self.channel.notify(self.check)
  138. headers = {
  139. "User-Agent": "healthchecks.io",
  140. "Content-Type": "application/json"
  141. }
  142. mock_request.assert_called_with(
  143. "post", "http://foo.com", data=b"data", headers=headers, timeout=5)
  144. @patch("hc.api.transports.requests.request")
  145. def test_webhooks_handle_get_headers(self, mock_request):
  146. definition = {
  147. "url_down": "http://foo.com",
  148. "headers": {"Content-Type": "application/json"}
  149. }
  150. self._setup_data("webhook", json.dumps(definition))
  151. self.channel.notify(self.check)
  152. headers = {
  153. "User-Agent": "healthchecks.io",
  154. "Content-Type": "application/json"
  155. }
  156. mock_request.assert_called_with(
  157. "get", "http://foo.com", headers=headers, timeout=5)
  158. @patch("hc.api.transports.requests.request")
  159. def test_webhooks_allow_user_agent_override(self, mock_request):
  160. definition = {
  161. "url_down": "http://foo.com",
  162. "headers": {"User-Agent": "My-Agent"}
  163. }
  164. self._setup_data("webhook", json.dumps(definition))
  165. self.channel.notify(self.check)
  166. headers = {"User-Agent": "My-Agent"}
  167. mock_request.assert_called_with(
  168. "get", "http://foo.com", headers=headers, timeout=5)
  169. @patch("hc.api.transports.requests.request")
  170. def test_webhooks_support_variables_in_headers(self, mock_request):
  171. definition = {
  172. "url_down": "http://foo.com",
  173. "headers": {"X-Message": "$NAME is DOWN"}
  174. }
  175. self._setup_data("webhook", json.dumps(definition))
  176. self.check.name = "Foo"
  177. self.check.save()
  178. self.channel.notify(self.check)
  179. headers = {
  180. "User-Agent": "healthchecks.io",
  181. "X-Message": "Foo is DOWN"
  182. }
  183. mock_request.assert_called_with(
  184. "get", "http://foo.com", headers=headers, timeout=5)
  185. def test_email(self):
  186. self._setup_data("email", "[email protected]")
  187. self.channel.notify(self.check)
  188. n = Notification.objects.get()
  189. self.assertEqual(n.error, "")
  190. # And email should have been sent
  191. self.assertEqual(len(mail.outbox), 1)
  192. email = mail.outbox[0]
  193. self.assertTrue("X-Bounce-Url" in email.extra_headers)
  194. def test_it_skips_unverified_email(self):
  195. self._setup_data("email", "[email protected]", email_verified=False)
  196. self.channel.notify(self.check)
  197. # If an email is not verified, it should be skipped over
  198. # without logging a notification:
  199. self.assertEqual(Notification.objects.count(), 0)
  200. self.assertEqual(len(mail.outbox), 0)
  201. @patch("hc.api.transports.requests.request")
  202. def test_pd(self, mock_post):
  203. self._setup_data("pd", "123")
  204. mock_post.return_value.status_code = 200
  205. self.channel.notify(self.check)
  206. assert Notification.objects.count() == 1
  207. args, kwargs = mock_post.call_args
  208. payload = kwargs["json"]
  209. self.assertEqual(payload["event_type"], "trigger")
  210. self.assertEqual(payload["service_key"], "123")
  211. @patch("hc.api.transports.requests.request")
  212. def test_pd_complex(self, mock_post):
  213. self._setup_data("pd", json.dumps({"service_key": "456"}))
  214. mock_post.return_value.status_code = 200
  215. self.channel.notify(self.check)
  216. assert Notification.objects.count() == 1
  217. args, kwargs = mock_post.call_args
  218. payload = kwargs["json"]
  219. self.assertEqual(payload["event_type"], "trigger")
  220. self.assertEqual(payload["service_key"], "456")
  221. @patch("hc.api.transports.requests.request")
  222. def test_slack(self, mock_post):
  223. self._setup_data("slack", "123")
  224. mock_post.return_value.status_code = 200
  225. self.channel.notify(self.check)
  226. assert Notification.objects.count() == 1
  227. args, kwargs = mock_post.call_args
  228. payload = kwargs["json"]
  229. attachment = payload["attachments"][0]
  230. fields = {f["title"]: f["value"] for f in attachment["fields"]}
  231. self.assertEqual(fields["Last Ping"], "an hour ago")
  232. @patch("hc.api.transports.requests.request")
  233. def test_slack_with_complex_value(self, mock_post):
  234. v = json.dumps({"incoming_webhook": {"url": "123"}})
  235. self._setup_data("slack", v)
  236. mock_post.return_value.status_code = 200
  237. self.channel.notify(self.check)
  238. assert Notification.objects.count() == 1
  239. args, kwargs = mock_post.call_args
  240. self.assertEqual(args[1], "123")
  241. @patch("hc.api.transports.requests.request")
  242. def test_slack_handles_500(self, mock_post):
  243. self._setup_data("slack", "123")
  244. mock_post.return_value.status_code = 500
  245. self.channel.notify(self.check)
  246. n = Notification.objects.get()
  247. self.assertEqual(n.error, "Received status code 500")
  248. @patch("hc.api.transports.requests.request", side_effect=Timeout)
  249. def test_slack_handles_timeout(self, mock_post):
  250. self._setup_data("slack", "123")
  251. self.channel.notify(self.check)
  252. n = Notification.objects.get()
  253. self.assertEqual(n.error, "Connection timed out")
  254. @patch("hc.api.transports.requests.request")
  255. def test_slack_with_tabs_in_schedule(self, mock_post):
  256. self._setup_data("slack", "123")
  257. self.check.kind = "cron"
  258. self.check.schedule = "*\t* * * *"
  259. self.check.save()
  260. mock_post.return_value.status_code = 200
  261. self.channel.notify(self.check)
  262. self.assertEqual(Notification.objects.count(), 1)
  263. self.assertTrue(mock_post.called)
  264. @patch("hc.api.transports.requests.request")
  265. def test_hipchat(self, mock_post):
  266. self._setup_data("hipchat", "123")
  267. mock_post.return_value.status_code = 204
  268. self.channel.notify(self.check)
  269. n = Notification.objects.first()
  270. self.assertEqual(n.error, "")
  271. args, kwargs = mock_post.call_args
  272. payload = kwargs["json"]
  273. self.assertIn("DOWN", payload["message"])
  274. @patch("hc.api.transports.requests.request")
  275. def test_opsgenie(self, mock_post):
  276. self._setup_data("opsgenie", "123")
  277. mock_post.return_value.status_code = 200
  278. self.channel.notify(self.check)
  279. n = Notification.objects.first()
  280. self.assertEqual(n.error, "")
  281. args, kwargs = mock_post.call_args
  282. payload = kwargs["json"]
  283. self.assertIn("DOWN", payload["message"])
  284. @patch("hc.api.transports.requests.request")
  285. def test_pushover(self, mock_post):
  286. self._setup_data("po", "123|0")
  287. mock_post.return_value.status_code = 200
  288. self.channel.notify(self.check)
  289. assert Notification.objects.count() == 1
  290. args, kwargs = mock_post.call_args
  291. payload = kwargs["data"]
  292. self.assertIn("DOWN", payload["title"])
  293. @patch("hc.api.transports.requests.request")
  294. def test_victorops(self, mock_post):
  295. self._setup_data("victorops", "123")
  296. mock_post.return_value.status_code = 200
  297. self.channel.notify(self.check)
  298. assert Notification.objects.count() == 1
  299. args, kwargs = mock_post.call_args
  300. payload = kwargs["json"]
  301. self.assertEqual(payload["message_type"], "CRITICAL")
  302. @patch("hc.api.transports.requests.request")
  303. def test_discord(self, mock_post):
  304. v = json.dumps({"webhook": {"url": "123"}})
  305. self._setup_data("discord", v)
  306. mock_post.return_value.status_code = 200
  307. self.channel.notify(self.check)
  308. assert Notification.objects.count() == 1
  309. args, kwargs = mock_post.call_args
  310. payload = kwargs["json"]
  311. attachment = payload["attachments"][0]
  312. fields = {f["title"]: f["value"] for f in attachment["fields"]}
  313. self.assertEqual(fields["Last Ping"], "an hour ago")
  314. @patch("hc.api.transports.requests.request")
  315. def test_pushbullet(self, mock_post):
  316. self._setup_data("pushbullet", "fake-token")
  317. mock_post.return_value.status_code = 200
  318. self.channel.notify(self.check)
  319. assert Notification.objects.count() == 1
  320. _, kwargs = mock_post.call_args
  321. self.assertEqual(kwargs["json"]["type"], "note")
  322. self.assertEqual(kwargs["headers"]["Access-Token"], "fake-token")
  323. @patch("hc.api.transports.requests.request")
  324. def test_telegram(self, mock_post):
  325. v = json.dumps({"id": 123})
  326. self._setup_data("telegram", v)
  327. mock_post.return_value.status_code = 200
  328. self.channel.notify(self.check)
  329. assert Notification.objects.count() == 1
  330. args, kwargs = mock_post.call_args
  331. payload = kwargs["json"]
  332. self.assertEqual(payload["chat_id"], 123)
  333. self.assertTrue("The check" in payload["text"])
  334. @patch("hc.api.transports.requests.request")
  335. def test_sms(self, mock_post):
  336. self._setup_data("sms", "+1234567890")
  337. self.check.last_ping = now() - td(hours=2)
  338. mock_post.return_value.status_code = 200
  339. self.channel.notify(self.check)
  340. assert Notification.objects.count() == 1
  341. args, kwargs = mock_post.call_args
  342. payload = kwargs["data"]
  343. self.assertEqual(payload["To"], "+1234567890")
  344. self.assertFalse(u"\xa0" in payload["Body"])
  345. # sent SMS counter should go up
  346. self.profile.refresh_from_db()
  347. self.assertEqual(self.profile.sms_sent, 1)
  348. @patch("hc.api.transports.requests.request")
  349. def test_sms_limit(self, mock_post):
  350. # At limit already:
  351. self.profile.last_sms_date = now()
  352. self.profile.sms_sent = 50
  353. self.profile.save()
  354. self._setup_data("sms", "+1234567890")
  355. self.channel.notify(self.check)
  356. self.assertFalse(mock_post.called)
  357. n = Notification.objects.get()
  358. self.assertTrue("Monthly SMS limit exceeded" in n.error)
  359. @patch("hc.api.transports.requests.request")
  360. def test_sms_limit_reset(self, mock_post):
  361. # At limit, but also into a new month
  362. self.profile.sms_sent = 50
  363. self.profile.last_sms_date = now() - td(days=100)
  364. self.profile.save()
  365. self._setup_data("sms", "+1234567890")
  366. mock_post.return_value.status_code = 200
  367. self.channel.notify(self.check)
  368. self.assertTrue(mock_post.called)