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. 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_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)