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.

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