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.

585 lines
20 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. class NotifyTestCase(BaseTestCase):
  11. def _setup_data(self, kind, value, status="down", email_verified=True):
  12. self.check = Check()
  13. self.check.status = status
  14. self.check.user = self.alice
  15. self.check.last_ping = now() - td(minutes=61)
  16. self.check.save()
  17. self.channel = Channel(user=self.alice)
  18. self.channel.kind = kind
  19. self.channel.value = value
  20. self.channel.email_verified = email_verified
  21. self.channel.save()
  22. self.channel.checks.add(self.check)
  23. @patch("hc.api.transports.requests.request")
  24. def test_webhook(self, mock_get):
  25. self._setup_data("webhook", "http://example")
  26. mock_get.return_value.status_code = 200
  27. self.channel.notify(self.check)
  28. mock_get.assert_called_with(
  29. "get", u"http://example",
  30. headers={"User-Agent": "healthchecks.io"}, timeout=5)
  31. @patch("hc.api.transports.requests.request", side_effect=Timeout)
  32. def test_webhooks_handle_timeouts(self, mock_get):
  33. self._setup_data("webhook", "http://example")
  34. self.channel.notify(self.check)
  35. n = Notification.objects.get()
  36. self.assertEqual(n.error, "Connection timed out")
  37. @patch("hc.api.transports.requests.request", side_effect=ConnectionError)
  38. def test_webhooks_handle_connection_errors(self, mock_get):
  39. self._setup_data("webhook", "http://example")
  40. self.channel.notify(self.check)
  41. n = Notification.objects.get()
  42. self.assertEqual(n.error, "Connection failed")
  43. @patch("hc.api.transports.requests.request")
  44. def test_webhooks_ignore_up_events(self, mock_get):
  45. self._setup_data("webhook", "http://example", status="up")
  46. self.channel.notify(self.check)
  47. self.assertFalse(mock_get.called)
  48. self.assertEqual(Notification.objects.count(), 0)
  49. @patch("hc.api.transports.requests.request")
  50. def test_webhooks_handle_500(self, mock_get):
  51. self._setup_data("webhook", "http://example")
  52. mock_get.return_value.status_code = 500
  53. self.channel.notify(self.check)
  54. n = Notification.objects.get()
  55. self.assertEqual(n.error, "Received status code 500")
  56. @patch("hc.api.transports.requests.request")
  57. def test_webhooks_support_variables(self, mock_get):
  58. template = "http://host/$CODE/$STATUS/$TAG1/$TAG2/?name=$NAME"
  59. self._setup_data("webhook", template)
  60. self.check.name = "Hello World"
  61. self.check.tags = "foo bar"
  62. self.check.save()
  63. self.channel.notify(self.check)
  64. url = u"http://host/%s/down/foo/bar/?name=Hello%%20World" \
  65. % self.check.code
  66. args, kwargs = mock_get.call_args
  67. self.assertEqual(args[0], "get")
  68. self.assertEqual(args[1], url)
  69. self.assertEqual(kwargs["headers"], {"User-Agent": "healthchecks.io"})
  70. self.assertEqual(kwargs["timeout"], 5)
  71. @patch("hc.api.transports.requests.request")
  72. def test_webhooks_support_post(self, mock_request):
  73. template = "http://example.com\n\nThe Time Is $NOW"
  74. self._setup_data("webhook", template)
  75. self.check.save()
  76. self.channel.notify(self.check)
  77. args, kwargs = mock_request.call_args
  78. self.assertEqual(args[0], "post")
  79. self.assertEqual(args[1], "http://example.com")
  80. # spaces should not have been urlencoded:
  81. payload = kwargs["data"].decode()
  82. self.assertTrue(payload.startswith("The Time Is 2"))
  83. @patch("hc.api.transports.requests.request")
  84. def test_webhooks_dollarsign_escaping(self, mock_get):
  85. # If name or tag contains what looks like a variable reference,
  86. # that should be left alone:
  87. template = "http://host/$NAME"
  88. self._setup_data("webhook", template)
  89. self.check.name = "$TAG1"
  90. self.check.tags = "foo"
  91. self.check.save()
  92. self.channel.notify(self.check)
  93. url = u"http://host/%24TAG1"
  94. mock_get.assert_called_with(
  95. "get", url, headers={"User-Agent": "healthchecks.io"}, timeout=5)
  96. @patch("hc.api.transports.requests.request")
  97. def test_webhook_fires_on_up_event(self, mock_get):
  98. self._setup_data("webhook", "http://foo\nhttp://bar", status="up")
  99. self.channel.notify(self.check)
  100. mock_get.assert_called_with(
  101. "get", "http://bar", headers={"User-Agent": "healthchecks.io"},
  102. timeout=5)
  103. @patch("hc.api.transports.requests.request")
  104. def test_webhooks_handle_unicode_post_body(self, mock_request):
  105. template = u"http://example.com\n\n(╯°□°)╯︵ ┻━┻"
  106. self._setup_data("webhook", template)
  107. self.check.save()
  108. self.channel.notify(self.check)
  109. args, kwargs = mock_request.call_args
  110. # unicode should be encoded into utf-8
  111. self.assertIsInstance(kwargs["data"], bytes)
  112. @patch("hc.api.transports.requests.request")
  113. def test_webhooks_handle_json_value(self, mock_request):
  114. definition = {"url_down": "http://foo.com"}
  115. self._setup_data("webhook", json.dumps(definition))
  116. self.channel.notify(self.check)
  117. headers = {"User-Agent": "healthchecks.io"}
  118. mock_request.assert_called_with(
  119. "get", "http://foo.com", headers=headers, timeout=5)
  120. @patch("hc.api.transports.requests.request")
  121. def test_webhooks_handle_json_up_event(self, mock_request):
  122. definition = {"url_up": "http://bar"}
  123. self._setup_data("webhook", json.dumps(definition), status="up")
  124. self.channel.notify(self.check)
  125. headers = {"User-Agent": "healthchecks.io"}
  126. mock_request.assert_called_with(
  127. "get", "http://bar", headers=headers, timeout=5)
  128. @patch("hc.api.transports.requests.request")
  129. def test_webhooks_handle_post_headers(self, mock_request):
  130. definition = {
  131. "url_down": "http://foo.com",
  132. "post_data": "data",
  133. "headers": {"Content-Type": "application/json"}
  134. }
  135. self._setup_data("webhook", json.dumps(definition))
  136. self.channel.notify(self.check)
  137. headers = {
  138. "User-Agent": "healthchecks.io",
  139. "Content-Type": "application/json"
  140. }
  141. mock_request.assert_called_with(
  142. "post", "http://foo.com", data=b"data", headers=headers, timeout=5)
  143. @patch("hc.api.transports.requests.request")
  144. def test_webhooks_handle_get_headers(self, mock_request):
  145. definition = {
  146. "url_down": "http://foo.com",
  147. "headers": {"Content-Type": "application/json"}
  148. }
  149. self._setup_data("webhook", json.dumps(definition))
  150. self.channel.notify(self.check)
  151. headers = {
  152. "User-Agent": "healthchecks.io",
  153. "Content-Type": "application/json"
  154. }
  155. mock_request.assert_called_with(
  156. "get", "http://foo.com", headers=headers, timeout=5)
  157. @patch("hc.api.transports.requests.request")
  158. def test_webhooks_allow_user_agent_override(self, mock_request):
  159. definition = {
  160. "url_down": "http://foo.com",
  161. "headers": {"User-Agent": "My-Agent"}
  162. }
  163. self._setup_data("webhook", json.dumps(definition))
  164. self.channel.notify(self.check)
  165. headers = {"User-Agent": "My-Agent"}
  166. mock_request.assert_called_with(
  167. "get", "http://foo.com", headers=headers, timeout=5)
  168. @patch("hc.api.transports.requests.request")
  169. def test_webhooks_support_variables_in_headers(self, mock_request):
  170. definition = {
  171. "url_down": "http://foo.com",
  172. "headers": {"X-Message": "$NAME is DOWN"}
  173. }
  174. self._setup_data("webhook", json.dumps(definition))
  175. self.check.name = "Foo"
  176. self.check.save()
  177. self.channel.notify(self.check)
  178. headers = {
  179. "User-Agent": "healthchecks.io",
  180. "X-Message": "Foo is DOWN"
  181. }
  182. mock_request.assert_called_with(
  183. "get", "http://foo.com", headers=headers, timeout=5)
  184. def test_email(self):
  185. self._setup_data("email", "[email protected]")
  186. self.channel.notify(self.check)
  187. n = Notification.objects.get()
  188. self.assertEqual(n.error, "")
  189. # And email should have been sent
  190. self.assertEqual(len(mail.outbox), 1)
  191. email = mail.outbox[0]
  192. self.assertTrue("X-Bounce-Url" in email.extra_headers)
  193. self.assertTrue("List-Unsubscribe" 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_pagertree(self, mock_post):
  223. self._setup_data("pagertree", "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. self.assertEqual(payload["event_type"], "trigger")
  230. @patch("hc.api.transports.requests.request")
  231. def test_slack(self, mock_post):
  232. self._setup_data("slack", "123")
  233. mock_post.return_value.status_code = 200
  234. self.channel.notify(self.check)
  235. assert Notification.objects.count() == 1
  236. args, kwargs = mock_post.call_args
  237. payload = kwargs["json"]
  238. attachment = payload["attachments"][0]
  239. fields = {f["title"]: f["value"] for f in attachment["fields"]}
  240. self.assertEqual(fields["Last Ping"], "an hour ago")
  241. @patch("hc.api.transports.requests.request")
  242. def test_slack_with_complex_value(self, mock_post):
  243. v = json.dumps({"incoming_webhook": {"url": "123"}})
  244. self._setup_data("slack", v)
  245. mock_post.return_value.status_code = 200
  246. self.channel.notify(self.check)
  247. assert Notification.objects.count() == 1
  248. args, kwargs = mock_post.call_args
  249. self.assertEqual(args[1], "123")
  250. @patch("hc.api.transports.requests.request")
  251. def test_slack_handles_500(self, mock_post):
  252. self._setup_data("slack", "123")
  253. mock_post.return_value.status_code = 500
  254. self.channel.notify(self.check)
  255. n = Notification.objects.get()
  256. self.assertEqual(n.error, "Received status code 500")
  257. @patch("hc.api.transports.requests.request", side_effect=Timeout)
  258. def test_slack_handles_timeout(self, mock_post):
  259. self._setup_data("slack", "123")
  260. self.channel.notify(self.check)
  261. n = Notification.objects.get()
  262. self.assertEqual(n.error, "Connection timed out")
  263. @patch("hc.api.transports.requests.request")
  264. def test_slack_with_tabs_in_schedule(self, mock_post):
  265. self._setup_data("slack", "123")
  266. self.check.kind = "cron"
  267. self.check.schedule = "*\t* * * *"
  268. self.check.save()
  269. mock_post.return_value.status_code = 200
  270. self.channel.notify(self.check)
  271. self.assertEqual(Notification.objects.count(), 1)
  272. self.assertTrue(mock_post.called)
  273. @patch("hc.api.transports.requests.request")
  274. def test_hipchat(self, mock_post):
  275. self._setup_data("hipchat", "123")
  276. mock_post.return_value.status_code = 204
  277. self.channel.notify(self.check)
  278. n = Notification.objects.first()
  279. self.assertEqual(n.error, "")
  280. args, kwargs = mock_post.call_args
  281. payload = kwargs["json"]
  282. self.assertIn("DOWN", payload["message"])
  283. @patch("hc.api.transports.requests.request")
  284. def test_opsgenie(self, mock_post):
  285. self._setup_data("opsgenie", "123")
  286. mock_post.return_value.status_code = 202
  287. self.channel.notify(self.check)
  288. n = Notification.objects.first()
  289. self.assertEqual(n.error, "")
  290. self.assertEqual(mock_post.call_count, 1)
  291. args, kwargs = mock_post.call_args
  292. payload = kwargs["json"]
  293. self.assertIn("DOWN", payload["message"])
  294. @patch("hc.api.transports.requests.request")
  295. def test_opsgenie_up(self, mock_post):
  296. self._setup_data("opsgenie", "123", status="up")
  297. mock_post.return_value.status_code = 202
  298. self.channel.notify(self.check)
  299. n = Notification.objects.first()
  300. self.assertEqual(n.error, "")
  301. self.assertEqual(mock_post.call_count, 1)
  302. args, kwargs = mock_post.call_args
  303. method, url = args
  304. self.assertTrue(str(self.check.code) in url)
  305. @patch("hc.api.transports.requests.request")
  306. def test_pushover(self, mock_post):
  307. self._setup_data("po", "123|0")
  308. mock_post.return_value.status_code = 200
  309. self.channel.notify(self.check)
  310. assert Notification.objects.count() == 1
  311. args, kwargs = mock_post.call_args
  312. payload = kwargs["data"]
  313. self.assertIn("DOWN", payload["title"])
  314. @patch("hc.api.transports.requests.request")
  315. def test_victorops(self, mock_post):
  316. self._setup_data("victorops", "123")
  317. mock_post.return_value.status_code = 200
  318. self.channel.notify(self.check)
  319. assert Notification.objects.count() == 1
  320. args, kwargs = mock_post.call_args
  321. payload = kwargs["json"]
  322. self.assertEqual(payload["message_type"], "CRITICAL")
  323. @patch("hc.api.transports.requests.request")
  324. def test_discord(self, mock_post):
  325. v = json.dumps({"webhook": {"url": "123"}})
  326. self._setup_data("discord", 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. attachment = payload["attachments"][0]
  333. fields = {f["title"]: f["value"] for f in attachment["fields"]}
  334. self.assertEqual(fields["Last Ping"], "an hour ago")
  335. @patch("hc.api.transports.requests.request")
  336. def test_pushbullet(self, mock_post):
  337. self._setup_data("pushbullet", "fake-token")
  338. mock_post.return_value.status_code = 200
  339. self.channel.notify(self.check)
  340. assert Notification.objects.count() == 1
  341. _, kwargs = mock_post.call_args
  342. self.assertEqual(kwargs["json"]["type"], "note")
  343. self.assertEqual(kwargs["headers"]["Access-Token"], "fake-token")
  344. @patch("hc.api.transports.requests.request")
  345. def test_telegram(self, mock_post):
  346. v = json.dumps({"id": 123})
  347. self._setup_data("telegram", v)
  348. mock_post.return_value.status_code = 200
  349. self.channel.notify(self.check)
  350. assert Notification.objects.count() == 1
  351. args, kwargs = mock_post.call_args
  352. payload = kwargs["json"]
  353. self.assertEqual(payload["chat_id"], 123)
  354. self.assertTrue("The check" in payload["text"])
  355. @patch("hc.api.transports.requests.request")
  356. def test_sms(self, mock_post):
  357. self._setup_data("sms", "+1234567890")
  358. self.check.last_ping = now() - td(hours=2)
  359. mock_post.return_value.status_code = 200
  360. self.channel.notify(self.check)
  361. assert Notification.objects.count() == 1
  362. args, kwargs = mock_post.call_args
  363. payload = kwargs["data"]
  364. self.assertEqual(payload["To"], "+1234567890")
  365. self.assertFalse(u"\xa0" in payload["Body"])
  366. # sent SMS counter should go up
  367. self.profile.refresh_from_db()
  368. self.assertEqual(self.profile.sms_sent, 1)
  369. @patch("hc.api.transports.requests.request")
  370. def test_sms_handles_json_value(self, mock_post):
  371. value = {"label": "foo", "value": "+1234567890"}
  372. self._setup_data("sms", json.dumps(value))
  373. self.check.last_ping = now() - td(hours=2)
  374. mock_post.return_value.status_code = 200
  375. self.channel.notify(self.check)
  376. assert Notification.objects.count() == 1
  377. args, kwargs = mock_post.call_args
  378. payload = kwargs["data"]
  379. self.assertEqual(payload["To"], "+1234567890")
  380. @patch("hc.api.transports.requests.request")
  381. def test_sms_limit(self, mock_post):
  382. # At limit already:
  383. self.profile.last_sms_date = now()
  384. self.profile.sms_sent = 50
  385. self.profile.save()
  386. self._setup_data("sms", "+1234567890")
  387. self.channel.notify(self.check)
  388. self.assertFalse(mock_post.called)
  389. n = Notification.objects.get()
  390. self.assertTrue("Monthly SMS limit exceeded" in n.error)
  391. @patch("hc.api.transports.requests.request")
  392. def test_sms_limit_reset(self, mock_post):
  393. # At limit, but also into a new month
  394. self.profile.sms_sent = 50
  395. self.profile.last_sms_date = now() - td(days=100)
  396. self.profile.save()
  397. self._setup_data("sms", "+1234567890")
  398. mock_post.return_value.status_code = 200
  399. self.channel.notify(self.check)
  400. self.assertTrue(mock_post.called)
  401. @patch("hc.api.transports.requests.request")
  402. def test_zendesk_down(self, mock_post):
  403. v = json.dumps({"access_token": "fake-token", "subdomain": "foo"})
  404. self._setup_data("zendesk", v)
  405. mock_post.return_value.status_code = 200
  406. self.channel.notify(self.check)
  407. assert Notification.objects.count() == 1
  408. args, kwargs = mock_post.call_args
  409. method, url = args
  410. self.assertEqual(method, "post")
  411. self.assertTrue("foo.zendesk.com" in url)
  412. payload = kwargs["json"]
  413. self.assertEqual(payload["request"]["type"], "incident")
  414. self.assertTrue("down" in payload["request"]["subject"])
  415. headers = kwargs["headers"]
  416. self.assertEqual(headers["Authorization"], "Bearer fake-token")
  417. @patch("hc.api.transports.requests.request")
  418. @patch("hc.api.transports.requests.get")
  419. def test_zendesk_up(self, mock_get, mock_post):
  420. v = json.dumps({"access_token": "fake-token", "subdomain": "foo"})
  421. self._setup_data("zendesk", v, status="up")
  422. mock_post.return_value.status_code = 200
  423. mock_get.return_value.status_code = 200
  424. mock_get.return_value.json.return_value = {
  425. "requests": [{
  426. "url": "https://foo.example.org/comment",
  427. "description": "code is %s" % self.check.code
  428. }]
  429. }
  430. self.channel.notify(self.check)
  431. assert Notification.objects.count() == 1
  432. args, kwargs = mock_post.call_args
  433. self.assertTrue("foo.example.org" in args[1])
  434. payload = kwargs["json"]
  435. self.assertEqual(payload["request"]["type"], "incident")
  436. self.assertTrue("UP" in payload["request"]["subject"])
  437. headers = kwargs["headers"]
  438. self.assertEqual(headers["Authorization"], "Bearer fake-token")
  439. @patch("hc.api.transports.requests.request")
  440. @patch("hc.api.transports.requests.get")
  441. def test_zendesk_up_with_no_existing_ticket(self, mock_get, mock_post):
  442. v = json.dumps({"access_token": "fake-token", "subdomain": "foo"})
  443. self._setup_data("zendesk", v, status="up")
  444. mock_get.return_value.status_code = 200
  445. mock_get.return_value.json.return_value = {"requests": []}
  446. self.channel.notify(self.check)
  447. n = Notification.objects.get()
  448. self.assertEqual(n.error, "Could not find a ticket to update")
  449. self.assertFalse(mock_post.called)