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.

577 lines
20 KiB

6 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
6 years ago
6 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
6 years ago
6 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(project=self.project)
  13. self.check.status = status
  14. self.check.last_ping = now() - td(minutes=61)
  15. self.check.save()
  16. self.channel = Channel(project=self.project)
  17. self.channel.kind = kind
  18. self.channel.value = value
  19. self.channel.email_verified = email_verified
  20. self.channel.save()
  21. self.channel.checks.add(self.check)
  22. @patch("hc.api.transports.requests.request")
  23. def test_webhook(self, mock_get):
  24. self._setup_data("webhook", "http://example")
  25. mock_get.return_value.status_code = 200
  26. self.channel.notify(self.check)
  27. mock_get.assert_called_with(
  28. "get",
  29. u"http://example",
  30. headers={"User-Agent": "healthchecks.io"},
  31. timeout=5,
  32. )
  33. @patch("hc.api.transports.requests.request", side_effect=Timeout)
  34. def test_webhooks_handle_timeouts(self, mock_get):
  35. self._setup_data("webhook", "http://example")
  36. self.channel.notify(self.check)
  37. n = Notification.objects.get()
  38. self.assertEqual(n.error, "Connection timed out")
  39. @patch("hc.api.transports.requests.request", side_effect=ConnectionError)
  40. def test_webhooks_handle_connection_errors(self, mock_get):
  41. self._setup_data("webhook", "http://example")
  42. self.channel.notify(self.check)
  43. n = Notification.objects.get()
  44. self.assertEqual(n.error, "Connection failed")
  45. @patch("hc.api.transports.requests.request")
  46. def test_webhooks_ignore_up_events(self, mock_get):
  47. self._setup_data("webhook", "http://example", status="up")
  48. self.channel.notify(self.check)
  49. self.assertFalse(mock_get.called)
  50. self.assertEqual(Notification.objects.count(), 0)
  51. @patch("hc.api.transports.requests.request")
  52. def test_webhooks_handle_500(self, mock_get):
  53. self._setup_data("webhook", "http://example")
  54. mock_get.return_value.status_code = 500
  55. self.channel.notify(self.check)
  56. n = Notification.objects.get()
  57. self.assertEqual(n.error, "Received status code 500")
  58. @patch("hc.api.transports.requests.request")
  59. def test_webhooks_support_variables(self, mock_get):
  60. template = "http://host/$CODE/$STATUS/$TAG1/$TAG2/?name=$NAME"
  61. self._setup_data("webhook", template)
  62. self.check.name = "Hello World"
  63. self.check.tags = "foo bar"
  64. self.check.save()
  65. self.channel.notify(self.check)
  66. url = u"http://host/%s/down/foo/bar/?name=Hello%%20World" % 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()
  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. )
  98. @patch("hc.api.transports.requests.request")
  99. def test_webhook_fires_on_up_event(self, mock_get):
  100. self._setup_data("webhook", "http://foo\nhttp://bar", status="up")
  101. self.channel.notify(self.check)
  102. mock_get.assert_called_with(
  103. "get", "http://bar", headers={"User-Agent": "healthchecks.io"}, timeout=5
  104. )
  105. @patch("hc.api.transports.requests.request")
  106. def test_webhooks_handle_unicode_post_body(self, mock_request):
  107. template = u"http://example.com\n\n(╯°□°)╯︵ ┻━┻"
  108. self._setup_data("webhook", template)
  109. self.check.save()
  110. self.channel.notify(self.check)
  111. args, kwargs = mock_request.call_args
  112. # unicode should be encoded into utf-8
  113. self.assertIsInstance(kwargs["data"], bytes)
  114. @patch("hc.api.transports.requests.request")
  115. def test_webhooks_handle_json_value(self, mock_request):
  116. definition = {
  117. "method_down": "GET",
  118. "url_down": "http://foo.com",
  119. "body_down": "",
  120. "headers_down": {},
  121. }
  122. self._setup_data("webhook", json.dumps(definition))
  123. self.channel.notify(self.check)
  124. headers = {"User-Agent": "healthchecks.io"}
  125. mock_request.assert_called_with(
  126. "get", "http://foo.com", headers=headers, timeout=5
  127. )
  128. @patch("hc.api.transports.requests.request")
  129. def test_webhooks_handle_json_up_event(self, mock_request):
  130. definition = {
  131. "method_up": "GET",
  132. "url_up": "http://bar",
  133. "body_up": "",
  134. "headers_up": {},
  135. }
  136. self._setup_data("webhook", json.dumps(definition), status="up")
  137. self.channel.notify(self.check)
  138. headers = {"User-Agent": "healthchecks.io"}
  139. mock_request.assert_called_with("get", "http://bar", headers=headers, timeout=5)
  140. @patch("hc.api.transports.requests.request")
  141. def test_webhooks_handle_post_headers(self, mock_request):
  142. definition = {
  143. "method_down": "POST",
  144. "url_down": "http://foo.com",
  145. "body_down": "data",
  146. "headers_down": {"Content-Type": "application/json"},
  147. }
  148. self._setup_data("webhook", json.dumps(definition))
  149. self.channel.notify(self.check)
  150. headers = {"User-Agent": "healthchecks.io", "Content-Type": "application/json"}
  151. mock_request.assert_called_with(
  152. "post", "http://foo.com", data=b"data", headers=headers, timeout=5
  153. )
  154. @patch("hc.api.transports.requests.request")
  155. def test_webhooks_handle_get_headers(self, mock_request):
  156. definition = {
  157. "method_down": "GET",
  158. "url_down": "http://foo.com",
  159. "body_down": "",
  160. "headers_down": {"Content-Type": "application/json"},
  161. }
  162. self._setup_data("webhook", json.dumps(definition))
  163. self.channel.notify(self.check)
  164. headers = {"User-Agent": "healthchecks.io", "Content-Type": "application/json"}
  165. mock_request.assert_called_with(
  166. "get", "http://foo.com", headers=headers, timeout=5
  167. )
  168. @patch("hc.api.transports.requests.request")
  169. def test_webhooks_allow_user_agent_override(self, mock_request):
  170. definition = {
  171. "method_down": "GET",
  172. "url_down": "http://foo.com",
  173. "body_down": "",
  174. "headers_down": {"User-Agent": "My-Agent"},
  175. }
  176. self._setup_data("webhook", json.dumps(definition))
  177. self.channel.notify(self.check)
  178. headers = {"User-Agent": "My-Agent"}
  179. mock_request.assert_called_with(
  180. "get", "http://foo.com", headers=headers, timeout=5
  181. )
  182. @patch("hc.api.transports.requests.request")
  183. def test_webhooks_support_variables_in_headers(self, mock_request):
  184. definition = {
  185. "method_down": "GET",
  186. "url_down": "http://foo.com",
  187. "body_down": "",
  188. "headers_down": {"X-Message": "$NAME is DOWN"},
  189. }
  190. self._setup_data("webhook", json.dumps(definition))
  191. self.check.name = "Foo"
  192. self.check.save()
  193. self.channel.notify(self.check)
  194. headers = {"User-Agent": "healthchecks.io", "X-Message": "Foo is DOWN"}
  195. mock_request.assert_called_with(
  196. "get", "http://foo.com", headers=headers, timeout=5
  197. )
  198. def test_email(self):
  199. self._setup_data("email", "[email protected]")
  200. self.channel.notify(self.check)
  201. n = Notification.objects.get()
  202. self.assertEqual(n.error, "")
  203. # And email should have been sent
  204. self.assertEqual(len(mail.outbox), 1)
  205. email = mail.outbox[0]
  206. self.assertEqual(email.to[0], "[email protected]")
  207. self.assertTrue("X-Bounce-Url" in email.extra_headers)
  208. self.assertTrue("List-Unsubscribe" in email.extra_headers)
  209. def test_email_transport_handles_json_value(self):
  210. payload = {"value": "[email protected]", "up": True, "down": True}
  211. self._setup_data("email", json.dumps(payload))
  212. self.channel.notify(self.check)
  213. # And email should have been sent
  214. self.assertEqual(len(mail.outbox), 1)
  215. email = mail.outbox[0]
  216. self.assertEqual(email.to[0], "[email protected]")
  217. def test_it_skips_unverified_email(self):
  218. self._setup_data("email", "[email protected]", email_verified=False)
  219. self.channel.notify(self.check)
  220. # If an email is not verified, it should be skipped over
  221. # without logging a notification:
  222. self.assertEqual(Notification.objects.count(), 0)
  223. self.assertEqual(len(mail.outbox), 0)
  224. def test_email_checks_up_down_flags(self):
  225. payload = {"value": "[email protected]", "up": True, "down": False}
  226. self._setup_data("email", json.dumps(payload))
  227. self.channel.notify(self.check)
  228. # This channel should not notify on "down" events:
  229. self.assertEqual(Notification.objects.count(), 0)
  230. self.assertEqual(len(mail.outbox), 0)
  231. @patch("hc.api.transports.requests.request")
  232. def test_pd(self, mock_post):
  233. self._setup_data("pd", "123")
  234. mock_post.return_value.status_code = 200
  235. self.channel.notify(self.check)
  236. assert Notification.objects.count() == 1
  237. args, kwargs = mock_post.call_args
  238. payload = kwargs["json"]
  239. self.assertEqual(payload["event_type"], "trigger")
  240. self.assertEqual(payload["service_key"], "123")
  241. @patch("hc.api.transports.requests.request")
  242. def test_pd_complex(self, mock_post):
  243. self._setup_data("pd", json.dumps({"service_key": "456"}))
  244. mock_post.return_value.status_code = 200
  245. self.channel.notify(self.check)
  246. assert Notification.objects.count() == 1
  247. args, kwargs = mock_post.call_args
  248. payload = kwargs["json"]
  249. self.assertEqual(payload["event_type"], "trigger")
  250. self.assertEqual(payload["service_key"], "456")
  251. @patch("hc.api.transports.requests.request")
  252. def test_pagertree(self, mock_post):
  253. self._setup_data("pagertree", "123")
  254. mock_post.return_value.status_code = 200
  255. self.channel.notify(self.check)
  256. assert Notification.objects.count() == 1
  257. args, kwargs = mock_post.call_args
  258. payload = kwargs["json"]
  259. self.assertEqual(payload["event_type"], "trigger")
  260. @patch("hc.api.transports.requests.request")
  261. def test_pagerteam(self, mock_post):
  262. self._setup_data("pagerteam", "123")
  263. mock_post.return_value.status_code = 200
  264. self.channel.notify(self.check)
  265. assert Notification.objects.count() == 1
  266. args, kwargs = mock_post.call_args
  267. payload = kwargs["json"]
  268. self.assertEqual(payload["event_type"], "trigger")
  269. @patch("hc.api.transports.requests.request")
  270. def test_slack(self, mock_post):
  271. self._setup_data("slack", "123")
  272. mock_post.return_value.status_code = 200
  273. self.channel.notify(self.check)
  274. assert Notification.objects.count() == 1
  275. args, kwargs = mock_post.call_args
  276. payload = kwargs["json"]
  277. attachment = payload["attachments"][0]
  278. fields = {f["title"]: f["value"] for f in attachment["fields"]}
  279. self.assertEqual(fields["Last Ping"], "an hour ago")
  280. @patch("hc.api.transports.requests.request")
  281. def test_slack_with_complex_value(self, mock_post):
  282. v = json.dumps({"incoming_webhook": {"url": "123"}})
  283. self._setup_data("slack", v)
  284. mock_post.return_value.status_code = 200
  285. self.channel.notify(self.check)
  286. assert Notification.objects.count() == 1
  287. args, kwargs = mock_post.call_args
  288. self.assertEqual(args[1], "123")
  289. @patch("hc.api.transports.requests.request")
  290. def test_slack_handles_500(self, mock_post):
  291. self._setup_data("slack", "123")
  292. mock_post.return_value.status_code = 500
  293. self.channel.notify(self.check)
  294. n = Notification.objects.get()
  295. self.assertEqual(n.error, "Received status code 500")
  296. @patch("hc.api.transports.requests.request", side_effect=Timeout)
  297. def test_slack_handles_timeout(self, mock_post):
  298. self._setup_data("slack", "123")
  299. self.channel.notify(self.check)
  300. n = Notification.objects.get()
  301. self.assertEqual(n.error, "Connection timed out")
  302. @patch("hc.api.transports.requests.request")
  303. def test_slack_with_tabs_in_schedule(self, mock_post):
  304. self._setup_data("slack", "123")
  305. self.check.kind = "cron"
  306. self.check.schedule = "*\t* * * *"
  307. self.check.save()
  308. mock_post.return_value.status_code = 200
  309. self.channel.notify(self.check)
  310. self.assertEqual(Notification.objects.count(), 1)
  311. self.assertTrue(mock_post.called)
  312. @patch("hc.api.transports.requests.request")
  313. def test_hipchat(self, mock_post):
  314. self._setup_data("hipchat", "123")
  315. self.channel.notify(self.check)
  316. self.assertFalse(mock_post.called)
  317. self.assertEqual(Notification.objects.count(), 0)
  318. @patch("hc.api.transports.requests.request")
  319. def test_opsgenie(self, mock_post):
  320. self._setup_data("opsgenie", "123")
  321. mock_post.return_value.status_code = 202
  322. self.channel.notify(self.check)
  323. n = Notification.objects.first()
  324. self.assertEqual(n.error, "")
  325. self.assertEqual(mock_post.call_count, 1)
  326. args, kwargs = mock_post.call_args
  327. payload = kwargs["json"]
  328. self.assertIn("DOWN", payload["message"])
  329. @patch("hc.api.transports.requests.request")
  330. def test_opsgenie_up(self, mock_post):
  331. self._setup_data("opsgenie", "123", status="up")
  332. mock_post.return_value.status_code = 202
  333. self.channel.notify(self.check)
  334. n = Notification.objects.first()
  335. self.assertEqual(n.error, "")
  336. self.assertEqual(mock_post.call_count, 1)
  337. args, kwargs = mock_post.call_args
  338. method, url = args
  339. self.assertTrue(str(self.check.code) in url)
  340. @patch("hc.api.transports.requests.request")
  341. def test_pushover(self, mock_post):
  342. self._setup_data("po", "123|0")
  343. mock_post.return_value.status_code = 200
  344. self.channel.notify(self.check)
  345. assert Notification.objects.count() == 1
  346. args, kwargs = mock_post.call_args
  347. payload = kwargs["data"]
  348. self.assertIn("DOWN", payload["title"])
  349. @patch("hc.api.transports.requests.request")
  350. def test_pushover_up_priority(self, mock_post):
  351. self._setup_data("po", "123|0|2", status="up")
  352. mock_post.return_value.status_code = 200
  353. self.channel.notify(self.check)
  354. assert Notification.objects.count() == 1
  355. args, kwargs = mock_post.call_args
  356. payload = kwargs["data"]
  357. self.assertIn("UP", payload["title"])
  358. self.assertEqual(payload["priority"], 2)
  359. self.assertIn("retry", payload)
  360. self.assertIn("expire", payload)
  361. @patch("hc.api.transports.requests.request")
  362. def test_victorops(self, mock_post):
  363. self._setup_data("victorops", "123")
  364. mock_post.return_value.status_code = 200
  365. self.channel.notify(self.check)
  366. assert Notification.objects.count() == 1
  367. args, kwargs = mock_post.call_args
  368. payload = kwargs["json"]
  369. self.assertEqual(payload["message_type"], "CRITICAL")
  370. @patch("hc.api.transports.requests.request")
  371. def test_discord(self, mock_post):
  372. v = json.dumps({"webhook": {"url": "123"}})
  373. self._setup_data("discord", v)
  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["json"]
  379. attachment = payload["attachments"][0]
  380. fields = {f["title"]: f["value"] for f in attachment["fields"]}
  381. self.assertEqual(fields["Last Ping"], "an hour ago")
  382. @patch("hc.api.transports.requests.request")
  383. def test_pushbullet(self, mock_post):
  384. self._setup_data("pushbullet", "fake-token")
  385. mock_post.return_value.status_code = 200
  386. self.channel.notify(self.check)
  387. assert Notification.objects.count() == 1
  388. _, kwargs = mock_post.call_args
  389. self.assertEqual(kwargs["json"]["type"], "note")
  390. self.assertEqual(kwargs["headers"]["Access-Token"], "fake-token")
  391. @patch("hc.api.transports.requests.request")
  392. def test_telegram(self, mock_post):
  393. v = json.dumps({"id": 123})
  394. self._setup_data("telegram", v)
  395. mock_post.return_value.status_code = 200
  396. self.channel.notify(self.check)
  397. assert Notification.objects.count() == 1
  398. args, kwargs = mock_post.call_args
  399. payload = kwargs["json"]
  400. self.assertEqual(payload["chat_id"], 123)
  401. self.assertTrue("The check" in payload["text"])
  402. @patch("hc.api.transports.requests.request")
  403. def test_sms(self, mock_post):
  404. self._setup_data("sms", "+1234567890")
  405. self.check.last_ping = now() - td(hours=2)
  406. mock_post.return_value.status_code = 200
  407. self.channel.notify(self.check)
  408. assert Notification.objects.count() == 1
  409. args, kwargs = mock_post.call_args
  410. payload = kwargs["data"]
  411. self.assertEqual(payload["To"], "+1234567890")
  412. self.assertFalse(u"\xa0" in payload["Body"])
  413. # sent SMS counter should go up
  414. self.profile.refresh_from_db()
  415. self.assertEqual(self.profile.sms_sent, 1)
  416. @patch("hc.api.transports.requests.request")
  417. def test_sms_handles_json_value(self, mock_post):
  418. value = {"label": "foo", "value": "+1234567890"}
  419. self._setup_data("sms", json.dumps(value))
  420. self.check.last_ping = now() - td(hours=2)
  421. mock_post.return_value.status_code = 200
  422. self.channel.notify(self.check)
  423. assert Notification.objects.count() == 1
  424. args, kwargs = mock_post.call_args
  425. payload = kwargs["data"]
  426. self.assertEqual(payload["To"], "+1234567890")
  427. @patch("hc.api.transports.requests.request")
  428. def test_sms_limit(self, mock_post):
  429. # At limit already:
  430. self.profile.last_sms_date = now()
  431. self.profile.sms_sent = 50
  432. self.profile.save()
  433. self._setup_data("sms", "+1234567890")
  434. self.channel.notify(self.check)
  435. self.assertFalse(mock_post.called)
  436. n = Notification.objects.get()
  437. self.assertTrue("Monthly SMS limit exceeded" in n.error)
  438. @patch("hc.api.transports.requests.request")
  439. def test_sms_limit_reset(self, mock_post):
  440. # At limit, but also into a new month
  441. self.profile.sms_sent = 50
  442. self.profile.last_sms_date = now() - td(days=100)
  443. self.profile.save()
  444. self._setup_data("sms", "+1234567890")
  445. mock_post.return_value.status_code = 200
  446. self.channel.notify(self.check)
  447. self.assertTrue(mock_post.called)