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.

535 lines
18 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
  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.assertTrue("X-Bounce-Url" in email.extra_headers)
  192. self.assertTrue("List-Unsubscribe" in email.extra_headers)
  193. def test_it_skips_unverified_email(self):
  194. self._setup_data("email", "[email protected]", email_verified=False)
  195. self.channel.notify(self.check)
  196. # If an email is not verified, it should be skipped over
  197. # without logging a notification:
  198. self.assertEqual(Notification.objects.count(), 0)
  199. self.assertEqual(len(mail.outbox), 0)
  200. @patch("hc.api.transports.requests.request")
  201. def test_pd(self, mock_post):
  202. self._setup_data("pd", "123")
  203. mock_post.return_value.status_code = 200
  204. self.channel.notify(self.check)
  205. assert Notification.objects.count() == 1
  206. args, kwargs = mock_post.call_args
  207. payload = kwargs["json"]
  208. self.assertEqual(payload["event_type"], "trigger")
  209. self.assertEqual(payload["service_key"], "123")
  210. @patch("hc.api.transports.requests.request")
  211. def test_pd_complex(self, mock_post):
  212. self._setup_data("pd", json.dumps({"service_key": "456"}))
  213. mock_post.return_value.status_code = 200
  214. self.channel.notify(self.check)
  215. assert Notification.objects.count() == 1
  216. args, kwargs = mock_post.call_args
  217. payload = kwargs["json"]
  218. self.assertEqual(payload["event_type"], "trigger")
  219. self.assertEqual(payload["service_key"], "456")
  220. @patch("hc.api.transports.requests.request")
  221. def test_pagertree(self, mock_post):
  222. self._setup_data("pagertree", "123")
  223. mock_post.return_value.status_code = 200
  224. self.channel.notify(self.check)
  225. assert Notification.objects.count() == 1
  226. args, kwargs = mock_post.call_args
  227. payload = kwargs["json"]
  228. self.assertEqual(payload["event_type"], "trigger")
  229. @patch("hc.api.transports.requests.request")
  230. def test_slack(self, mock_post):
  231. self._setup_data("slack", "123")
  232. mock_post.return_value.status_code = 200
  233. self.channel.notify(self.check)
  234. assert Notification.objects.count() == 1
  235. args, kwargs = mock_post.call_args
  236. payload = kwargs["json"]
  237. attachment = payload["attachments"][0]
  238. fields = {f["title"]: f["value"] for f in attachment["fields"]}
  239. self.assertEqual(fields["Last Ping"], "an hour ago")
  240. @patch("hc.api.transports.requests.request")
  241. def test_slack_with_complex_value(self, mock_post):
  242. v = json.dumps({"incoming_webhook": {"url": "123"}})
  243. self._setup_data("slack", v)
  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. self.assertEqual(args[1], "123")
  249. @patch("hc.api.transports.requests.request")
  250. def test_slack_handles_500(self, mock_post):
  251. self._setup_data("slack", "123")
  252. mock_post.return_value.status_code = 500
  253. self.channel.notify(self.check)
  254. n = Notification.objects.get()
  255. self.assertEqual(n.error, "Received status code 500")
  256. @patch("hc.api.transports.requests.request", side_effect=Timeout)
  257. def test_slack_handles_timeout(self, mock_post):
  258. self._setup_data("slack", "123")
  259. self.channel.notify(self.check)
  260. n = Notification.objects.get()
  261. self.assertEqual(n.error, "Connection timed out")
  262. @patch("hc.api.transports.requests.request")
  263. def test_slack_with_tabs_in_schedule(self, mock_post):
  264. self._setup_data("slack", "123")
  265. self.check.kind = "cron"
  266. self.check.schedule = "*\t* * * *"
  267. self.check.save()
  268. mock_post.return_value.status_code = 200
  269. self.channel.notify(self.check)
  270. self.assertEqual(Notification.objects.count(), 1)
  271. self.assertTrue(mock_post.called)
  272. @patch("hc.api.transports.requests.request")
  273. def test_hipchat(self, mock_post):
  274. self._setup_data("hipchat", "123")
  275. mock_post.return_value.status_code = 204
  276. self.channel.notify(self.check)
  277. n = Notification.objects.first()
  278. self.assertEqual(n.error, "")
  279. args, kwargs = mock_post.call_args
  280. payload = kwargs["json"]
  281. self.assertIn("DOWN", payload["message"])
  282. @patch("hc.api.transports.requests.request")
  283. def test_opsgenie(self, mock_post):
  284. self._setup_data("opsgenie", "123")
  285. mock_post.return_value.status_code = 202
  286. self.channel.notify(self.check)
  287. n = Notification.objects.first()
  288. self.assertEqual(n.error, "")
  289. self.assertEqual(mock_post.call_count, 1)
  290. args, kwargs = mock_post.call_args
  291. payload = kwargs["json"]
  292. self.assertIn("DOWN", payload["message"])
  293. @patch("hc.api.transports.requests.request")
  294. def test_opsgenie_up(self, mock_post):
  295. self._setup_data("opsgenie", "123", status="up")
  296. mock_post.return_value.status_code = 202
  297. self.channel.notify(self.check)
  298. n = Notification.objects.first()
  299. self.assertEqual(n.error, "")
  300. self.assertEqual(mock_post.call_count, 1)
  301. args, kwargs = mock_post.call_args
  302. method, url = args
  303. self.assertTrue(str(self.check.code) in url)
  304. @patch("hc.api.transports.requests.request")
  305. def test_pushover(self, mock_post):
  306. self._setup_data("po", "123|0")
  307. mock_post.return_value.status_code = 200
  308. self.channel.notify(self.check)
  309. assert Notification.objects.count() == 1
  310. args, kwargs = mock_post.call_args
  311. payload = kwargs["data"]
  312. self.assertIn("DOWN", payload["title"])
  313. @patch("hc.api.transports.requests.request")
  314. def test_pushover_up_priority(self, mock_post):
  315. self._setup_data("po", "123|0|2", status="up")
  316. mock_post.return_value.status_code = 200
  317. self.channel.notify(self.check)
  318. assert Notification.objects.count() == 1
  319. args, kwargs = mock_post.call_args
  320. payload = kwargs["data"]
  321. self.assertIn("UP", payload["title"])
  322. self.assertEqual(payload["priority"], 2)
  323. self.assertIn("retry", payload)
  324. self.assertIn("expire", payload)
  325. @patch("hc.api.transports.requests.request")
  326. def test_victorops(self, mock_post):
  327. self._setup_data("victorops", "123")
  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["json"]
  333. self.assertEqual(payload["message_type"], "CRITICAL")
  334. @patch("hc.api.transports.requests.request")
  335. def test_discord(self, mock_post):
  336. v = json.dumps({"webhook": {"url": "123"}})
  337. self._setup_data("discord", v)
  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["json"]
  343. attachment = payload["attachments"][0]
  344. fields = {f["title"]: f["value"] for f in attachment["fields"]}
  345. self.assertEqual(fields["Last Ping"], "an hour ago")
  346. @patch("hc.api.transports.requests.request")
  347. def test_pushbullet(self, mock_post):
  348. self._setup_data("pushbullet", "fake-token")
  349. mock_post.return_value.status_code = 200
  350. self.channel.notify(self.check)
  351. assert Notification.objects.count() == 1
  352. _, kwargs = mock_post.call_args
  353. self.assertEqual(kwargs["json"]["type"], "note")
  354. self.assertEqual(kwargs["headers"]["Access-Token"], "fake-token")
  355. @patch("hc.api.transports.requests.request")
  356. def test_telegram(self, mock_post):
  357. v = json.dumps({"id": 123})
  358. self._setup_data("telegram", 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. self.assertEqual(payload["chat_id"], 123)
  365. self.assertTrue("The check" in payload["text"])
  366. @patch("hc.api.transports.requests.request")
  367. def test_sms(self, mock_post):
  368. self._setup_data("sms", "+1234567890")
  369. self.check.last_ping = now() - td(hours=2)
  370. mock_post.return_value.status_code = 200
  371. self.channel.notify(self.check)
  372. assert Notification.objects.count() == 1
  373. args, kwargs = mock_post.call_args
  374. payload = kwargs["data"]
  375. self.assertEqual(payload["To"], "+1234567890")
  376. self.assertFalse(u"\xa0" in payload["Body"])
  377. # sent SMS counter should go up
  378. self.profile.refresh_from_db()
  379. self.assertEqual(self.profile.sms_sent, 1)
  380. @patch("hc.api.transports.requests.request")
  381. def test_sms_handles_json_value(self, mock_post):
  382. value = {"label": "foo", "value": "+1234567890"}
  383. self._setup_data("sms", json.dumps(value))
  384. self.check.last_ping = now() - td(hours=2)
  385. mock_post.return_value.status_code = 200
  386. self.channel.notify(self.check)
  387. assert Notification.objects.count() == 1
  388. args, kwargs = mock_post.call_args
  389. payload = kwargs["data"]
  390. self.assertEqual(payload["To"], "+1234567890")
  391. @patch("hc.api.transports.requests.request")
  392. def test_sms_limit(self, mock_post):
  393. # At limit already:
  394. self.profile.last_sms_date = now()
  395. self.profile.sms_sent = 50
  396. self.profile.save()
  397. self._setup_data("sms", "+1234567890")
  398. self.channel.notify(self.check)
  399. self.assertFalse(mock_post.called)
  400. n = Notification.objects.get()
  401. self.assertTrue("Monthly SMS limit exceeded" in n.error)
  402. @patch("hc.api.transports.requests.request")
  403. def test_sms_limit_reset(self, mock_post):
  404. # At limit, but also into a new month
  405. self.profile.sms_sent = 50
  406. self.profile.last_sms_date = now() - td(days=100)
  407. self.profile.save()
  408. self._setup_data("sms", "+1234567890")
  409. mock_post.return_value.status_code = 200
  410. self.channel.notify(self.check)
  411. self.assertTrue(mock_post.called)