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.

536 lines
19 KiB

6 years ago
9 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
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.user = self.alice
  15. self.check.last_ping = now() - td(minutes=61)
  16. self.check.save()
  17. self.channel = Channel(user=self.alice, project=self.project)
  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_pushover_up_priority(self, mock_post):
  316. self._setup_data("po", "123|0|2", status="up")
  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["data"]
  322. self.assertIn("UP", payload["title"])
  323. self.assertEqual(payload["priority"], 2)
  324. self.assertIn("retry", payload)
  325. self.assertIn("expire", payload)
  326. @patch("hc.api.transports.requests.request")
  327. def test_victorops(self, mock_post):
  328. self._setup_data("victorops", "123")
  329. mock_post.return_value.status_code = 200
  330. self.channel.notify(self.check)
  331. assert Notification.objects.count() == 1
  332. args, kwargs = mock_post.call_args
  333. payload = kwargs["json"]
  334. self.assertEqual(payload["message_type"], "CRITICAL")
  335. @patch("hc.api.transports.requests.request")
  336. def test_discord(self, mock_post):
  337. v = json.dumps({"webhook": {"url": "123"}})
  338. self._setup_data("discord", v)
  339. mock_post.return_value.status_code = 200
  340. self.channel.notify(self.check)
  341. assert Notification.objects.count() == 1
  342. args, kwargs = mock_post.call_args
  343. payload = kwargs["json"]
  344. attachment = payload["attachments"][0]
  345. fields = {f["title"]: f["value"] for f in attachment["fields"]}
  346. self.assertEqual(fields["Last Ping"], "an hour ago")
  347. @patch("hc.api.transports.requests.request")
  348. def test_pushbullet(self, mock_post):
  349. self._setup_data("pushbullet", "fake-token")
  350. mock_post.return_value.status_code = 200
  351. self.channel.notify(self.check)
  352. assert Notification.objects.count() == 1
  353. _, kwargs = mock_post.call_args
  354. self.assertEqual(kwargs["json"]["type"], "note")
  355. self.assertEqual(kwargs["headers"]["Access-Token"], "fake-token")
  356. @patch("hc.api.transports.requests.request")
  357. def test_telegram(self, mock_post):
  358. v = json.dumps({"id": 123})
  359. self._setup_data("telegram", v)
  360. mock_post.return_value.status_code = 200
  361. self.channel.notify(self.check)
  362. assert Notification.objects.count() == 1
  363. args, kwargs = mock_post.call_args
  364. payload = kwargs["json"]
  365. self.assertEqual(payload["chat_id"], 123)
  366. self.assertTrue("The check" in payload["text"])
  367. @patch("hc.api.transports.requests.request")
  368. def test_sms(self, mock_post):
  369. self._setup_data("sms", "+1234567890")
  370. self.check.last_ping = now() - td(hours=2)
  371. mock_post.return_value.status_code = 200
  372. self.channel.notify(self.check)
  373. assert Notification.objects.count() == 1
  374. args, kwargs = mock_post.call_args
  375. payload = kwargs["data"]
  376. self.assertEqual(payload["To"], "+1234567890")
  377. self.assertFalse(u"\xa0" in payload["Body"])
  378. # sent SMS counter should go up
  379. self.profile.refresh_from_db()
  380. self.assertEqual(self.profile.sms_sent, 1)
  381. @patch("hc.api.transports.requests.request")
  382. def test_sms_handles_json_value(self, mock_post):
  383. value = {"label": "foo", "value": "+1234567890"}
  384. self._setup_data("sms", json.dumps(value))
  385. self.check.last_ping = now() - td(hours=2)
  386. mock_post.return_value.status_code = 200
  387. self.channel.notify(self.check)
  388. assert Notification.objects.count() == 1
  389. args, kwargs = mock_post.call_args
  390. payload = kwargs["data"]
  391. self.assertEqual(payload["To"], "+1234567890")
  392. @patch("hc.api.transports.requests.request")
  393. def test_sms_limit(self, mock_post):
  394. # At limit already:
  395. self.profile.last_sms_date = now()
  396. self.profile.sms_sent = 50
  397. self.profile.save()
  398. self._setup_data("sms", "+1234567890")
  399. self.channel.notify(self.check)
  400. self.assertFalse(mock_post.called)
  401. n = Notification.objects.get()
  402. self.assertTrue("Monthly SMS limit exceeded" in n.error)
  403. @patch("hc.api.transports.requests.request")
  404. def test_sms_limit_reset(self, mock_post):
  405. # At limit, but also into a new month
  406. self.profile.sms_sent = 50
  407. self.profile.last_sms_date = now() - td(days=100)
  408. self.profile.save()
  409. self._setup_data("sms", "+1234567890")
  410. mock_post.return_value.status_code = 200
  411. self.channel.notify(self.check)
  412. self.assertTrue(mock_post.called)