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.

950 lines
33 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
6 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
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
  1. # coding: utf-8
  2. from datetime import timedelta as td
  3. import json
  4. from unittest.mock import patch, Mock
  5. from django.core import mail
  6. from django.utils.timezone import now
  7. from hc.api.models import Channel, Check, Notification, TokenBucket
  8. from hc.test import BaseTestCase
  9. from requests.exceptions import ConnectionError, Timeout
  10. from django.test.utils import override_settings
  11. class NotifyTestCase(BaseTestCase):
  12. def _setup_data(self, kind, value, status="down", email_verified=True):
  13. self.check = Check(project=self.project)
  14. self.check.status = status
  15. self.check.last_ping = now() - td(minutes=61)
  16. self.check.save()
  17. self.channel = Channel(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. definition = {
  26. "method_down": "GET",
  27. "url_down": "http://example",
  28. "body_down": "",
  29. "headers_down": {},
  30. }
  31. self._setup_data("webhook", json.dumps(definition))
  32. mock_get.return_value.status_code = 200
  33. self.channel.notify(self.check)
  34. mock_get.assert_called_with(
  35. "get",
  36. "http://example",
  37. headers={"User-Agent": "healthchecks.io"},
  38. timeout=5,
  39. )
  40. @patch("hc.api.transports.requests.request", side_effect=Timeout)
  41. def test_webhooks_handle_timeouts(self, mock_get):
  42. definition = {
  43. "method_down": "GET",
  44. "url_down": "http://example",
  45. "body_down": "",
  46. "headers_down": {},
  47. }
  48. self._setup_data("webhook", json.dumps(definition))
  49. self.channel.notify(self.check)
  50. n = Notification.objects.get()
  51. self.assertEqual(n.error, "Connection timed out")
  52. self.channel.refresh_from_db()
  53. self.assertEqual(self.channel.last_error, "Connection timed out")
  54. @patch("hc.api.transports.requests.request", side_effect=ConnectionError)
  55. def test_webhooks_handle_connection_errors(self, mock_get):
  56. definition = {
  57. "method_down": "GET",
  58. "url_down": "http://example",
  59. "body_down": "",
  60. "headers_down": {},
  61. }
  62. self._setup_data("webhook", json.dumps(definition))
  63. self.channel.notify(self.check)
  64. n = Notification.objects.get()
  65. self.assertEqual(n.error, "Connection failed")
  66. @patch("hc.api.transports.requests.request")
  67. def test_webhooks_handle_500(self, mock_get):
  68. definition = {
  69. "method_down": "GET",
  70. "url_down": "http://example",
  71. "body_down": "",
  72. "headers_down": {},
  73. }
  74. self._setup_data("webhook", json.dumps(definition))
  75. mock_get.return_value.status_code = 500
  76. self.channel.notify(self.check)
  77. n = Notification.objects.get()
  78. self.assertEqual(n.error, "Received status code 500")
  79. @patch("hc.api.transports.requests.request")
  80. def test_webhooks_support_variables(self, mock_get):
  81. definition = {
  82. "method_down": "GET",
  83. "url_down": "http://host/$CODE/$STATUS/$TAG1/$TAG2/?name=$NAME",
  84. "body_down": "",
  85. "headers_down": {},
  86. }
  87. self._setup_data("webhook", json.dumps(definition))
  88. self.check.name = "Hello World"
  89. self.check.tags = "foo bar"
  90. self.check.save()
  91. self.channel.notify(self.check)
  92. url = "http://host/%s/down/foo/bar/?name=Hello%%20World" % self.check.code
  93. args, kwargs = mock_get.call_args
  94. self.assertEqual(args[0], "get")
  95. self.assertEqual(args[1], url)
  96. self.assertEqual(kwargs["headers"], {"User-Agent": "healthchecks.io"})
  97. self.assertEqual(kwargs["timeout"], 5)
  98. @patch("hc.api.transports.requests.request")
  99. def test_webhooks_handle_variable_variables(self, mock_get):
  100. definition = {
  101. "method_down": "GET",
  102. "url_down": "http://host/$$NAMETAG1",
  103. "body_down": "",
  104. "headers_down": {},
  105. }
  106. self._setup_data("webhook", json.dumps(definition))
  107. self.check.tags = "foo bar"
  108. self.check.save()
  109. self.channel.notify(self.check)
  110. # $$NAMETAG1 should *not* get transformed to "foo"
  111. args, kwargs = mock_get.call_args
  112. self.assertEqual(args[1], "http://host/$TAG1")
  113. @patch("hc.api.transports.requests.request")
  114. def test_webhooks_support_post(self, mock_request):
  115. definition = {
  116. "method_down": "POST",
  117. "url_down": "http://example.com",
  118. "body_down": "The Time Is $NOW",
  119. "headers_down": {},
  120. }
  121. self._setup_data("webhook", json.dumps(definition))
  122. self.check.save()
  123. self.channel.notify(self.check)
  124. args, kwargs = mock_request.call_args
  125. self.assertEqual(args[0], "post")
  126. self.assertEqual(args[1], "http://example.com")
  127. # spaces should not have been urlencoded:
  128. payload = kwargs["data"].decode()
  129. self.assertTrue(payload.startswith("The Time Is 2"))
  130. @patch("hc.api.transports.requests.request")
  131. def test_webhooks_dollarsign_escaping(self, mock_get):
  132. # If name or tag contains what looks like a variable reference,
  133. # that should be left alone:
  134. definition = {
  135. "method_down": "GET",
  136. "url_down": "http://host/$NAME",
  137. "body_down": "",
  138. "headers_down": {},
  139. }
  140. self._setup_data("webhook", json.dumps(definition))
  141. self.check.name = "$TAG1"
  142. self.check.tags = "foo"
  143. self.check.save()
  144. self.channel.notify(self.check)
  145. url = "http://host/%24TAG1"
  146. mock_get.assert_called_with(
  147. "get", url, headers={"User-Agent": "healthchecks.io"}, timeout=5
  148. )
  149. @patch("hc.api.transports.requests.request")
  150. def test_webhooks_handle_up_events(self, mock_get):
  151. definition = {
  152. "method_up": "GET",
  153. "url_up": "http://bar",
  154. "body_up": "",
  155. "headers_up": {},
  156. }
  157. self._setup_data("webhook", json.dumps(definition), status="up")
  158. self.channel.notify(self.check)
  159. mock_get.assert_called_with(
  160. "get", "http://bar", headers={"User-Agent": "healthchecks.io"}, timeout=5
  161. )
  162. @patch("hc.api.transports.requests.request")
  163. def test_webhooks_handle_noop_up_events(self, mock_get):
  164. definition = {
  165. "method_up": "GET",
  166. "url_up": "",
  167. "body_up": "",
  168. "headers_up": {},
  169. }
  170. self._setup_data("webhook", json.dumps(definition), status="up")
  171. self.channel.notify(self.check)
  172. self.assertFalse(mock_get.called)
  173. self.assertEqual(Notification.objects.count(), 0)
  174. @patch("hc.api.transports.requests.request")
  175. def test_webhooks_handle_unicode_post_body(self, mock_request):
  176. definition = {
  177. "method_down": "POST",
  178. "url_down": "http://foo.com",
  179. "body_down": "(╯°□°)╯︵ ┻━┻",
  180. "headers_down": {},
  181. }
  182. self._setup_data("webhook", json.dumps(definition))
  183. self.check.save()
  184. self.channel.notify(self.check)
  185. args, kwargs = mock_request.call_args
  186. # unicode should be encoded into utf-8
  187. self.assertIsInstance(kwargs["data"], bytes)
  188. @patch("hc.api.transports.requests.request")
  189. def test_webhooks_handle_post_headers(self, mock_request):
  190. definition = {
  191. "method_down": "POST",
  192. "url_down": "http://foo.com",
  193. "body_down": "data",
  194. "headers_down": {"Content-Type": "application/json"},
  195. }
  196. self._setup_data("webhook", json.dumps(definition))
  197. self.channel.notify(self.check)
  198. headers = {"User-Agent": "healthchecks.io", "Content-Type": "application/json"}
  199. mock_request.assert_called_with(
  200. "post", "http://foo.com", data=b"data", headers=headers, timeout=5
  201. )
  202. @patch("hc.api.transports.requests.request")
  203. def test_webhooks_handle_get_headers(self, mock_request):
  204. definition = {
  205. "method_down": "GET",
  206. "url_down": "http://foo.com",
  207. "body_down": "",
  208. "headers_down": {"Content-Type": "application/json"},
  209. }
  210. self._setup_data("webhook", json.dumps(definition))
  211. self.channel.notify(self.check)
  212. headers = {"User-Agent": "healthchecks.io", "Content-Type": "application/json"}
  213. mock_request.assert_called_with(
  214. "get", "http://foo.com", headers=headers, timeout=5
  215. )
  216. @patch("hc.api.transports.requests.request")
  217. def test_webhooks_allow_user_agent_override(self, mock_request):
  218. definition = {
  219. "method_down": "GET",
  220. "url_down": "http://foo.com",
  221. "body_down": "",
  222. "headers_down": {"User-Agent": "My-Agent"},
  223. }
  224. self._setup_data("webhook", json.dumps(definition))
  225. self.channel.notify(self.check)
  226. headers = {"User-Agent": "My-Agent"}
  227. mock_request.assert_called_with(
  228. "get", "http://foo.com", headers=headers, timeout=5
  229. )
  230. @patch("hc.api.transports.requests.request")
  231. def test_webhooks_support_variables_in_headers(self, mock_request):
  232. definition = {
  233. "method_down": "GET",
  234. "url_down": "http://foo.com",
  235. "body_down": "",
  236. "headers_down": {"X-Message": "$NAME is DOWN"},
  237. }
  238. self._setup_data("webhook", json.dumps(definition))
  239. self.check.name = "Foo"
  240. self.check.save()
  241. self.channel.notify(self.check)
  242. headers = {"User-Agent": "healthchecks.io", "X-Message": "Foo is DOWN"}
  243. mock_request.assert_called_with(
  244. "get", "http://foo.com", headers=headers, timeout=5
  245. )
  246. def test_email(self):
  247. self._setup_data("email", "[email protected]")
  248. self.channel.notify(self.check)
  249. n = Notification.objects.get()
  250. self.assertEqual(n.error, "")
  251. # And email should have been sent
  252. self.assertEqual(len(mail.outbox), 1)
  253. email = mail.outbox[0]
  254. self.assertEqual(email.to[0], "[email protected]")
  255. self.assertTrue("X-Bounce-Url" in email.extra_headers)
  256. self.assertTrue("X-Status-Url" in email.extra_headers)
  257. self.assertTrue("List-Unsubscribe" in email.extra_headers)
  258. self.assertTrue("List-Unsubscribe-Post" in email.extra_headers)
  259. def test_email_transport_handles_json_value(self):
  260. payload = {"value": "[email protected]", "up": True, "down": True}
  261. self._setup_data("email", json.dumps(payload))
  262. self.channel.notify(self.check)
  263. # And email should have been sent
  264. self.assertEqual(len(mail.outbox), 1)
  265. email = mail.outbox[0]
  266. self.assertEqual(email.to[0], "[email protected]")
  267. def test_it_reports_unverified_email(self):
  268. self._setup_data("email", "[email protected]", email_verified=False)
  269. self.channel.notify(self.check)
  270. # If an email is not verified, it should say so in the notification:
  271. n = Notification.objects.get()
  272. self.assertEqual(n.error, "Email not verified")
  273. def test_email_checks_up_down_flags(self):
  274. payload = {"value": "[email protected]", "up": True, "down": False}
  275. self._setup_data("email", json.dumps(payload))
  276. self.channel.notify(self.check)
  277. # This channel should not notify on "down" events:
  278. self.assertEqual(Notification.objects.count(), 0)
  279. self.assertEqual(len(mail.outbox), 0)
  280. def test_email_handles_amperstand(self):
  281. self._setup_data("email", "[email protected]")
  282. self.check.name = "Foo & Bar"
  283. self.channel.notify(self.check)
  284. email = mail.outbox[0]
  285. self.assertEqual(email.subject, "DOWN | Foo & Bar")
  286. @patch("hc.api.transports.requests.request")
  287. def test_pd(self, mock_post):
  288. self._setup_data("pd", "123")
  289. mock_post.return_value.status_code = 200
  290. self.channel.notify(self.check)
  291. assert Notification.objects.count() == 1
  292. args, kwargs = mock_post.call_args
  293. payload = kwargs["json"]
  294. self.assertEqual(payload["event_type"], "trigger")
  295. self.assertEqual(payload["service_key"], "123")
  296. @patch("hc.api.transports.requests.request")
  297. def test_pd_complex(self, mock_post):
  298. self._setup_data("pd", json.dumps({"service_key": "456"}))
  299. mock_post.return_value.status_code = 200
  300. self.channel.notify(self.check)
  301. assert Notification.objects.count() == 1
  302. args, kwargs = mock_post.call_args
  303. payload = kwargs["json"]
  304. self.assertEqual(payload["event_type"], "trigger")
  305. self.assertEqual(payload["service_key"], "456")
  306. @patch("hc.api.transports.requests.request")
  307. def test_pagertree(self, mock_post):
  308. self._setup_data("pagertree", "123")
  309. mock_post.return_value.status_code = 200
  310. self.channel.notify(self.check)
  311. assert Notification.objects.count() == 1
  312. args, kwargs = mock_post.call_args
  313. payload = kwargs["json"]
  314. self.assertEqual(payload["event_type"], "trigger")
  315. @patch("hc.api.transports.requests.request")
  316. def test_pagerteam(self, mock_post):
  317. self._setup_data("pagerteam", "123")
  318. self.channel.notify(self.check)
  319. self.assertFalse(mock_post.called)
  320. self.assertEqual(Notification.objects.count(), 0)
  321. @patch("hc.api.transports.requests.request")
  322. def test_slack(self, mock_post):
  323. self._setup_data("slack", "123")
  324. mock_post.return_value.status_code = 200
  325. self.channel.notify(self.check)
  326. assert Notification.objects.count() == 1
  327. args, kwargs = mock_post.call_args
  328. payload = kwargs["json"]
  329. attachment = payload["attachments"][0]
  330. fields = {f["title"]: f["value"] for f in attachment["fields"]}
  331. self.assertEqual(fields["Last Ping"], "an hour ago")
  332. @patch("hc.api.transports.requests.request")
  333. def test_slack_with_complex_value(self, mock_post):
  334. v = json.dumps({"incoming_webhook": {"url": "123"}})
  335. self._setup_data("slack", v)
  336. mock_post.return_value.status_code = 200
  337. self.channel.notify(self.check)
  338. assert Notification.objects.count() == 1
  339. args, kwargs = mock_post.call_args
  340. self.assertEqual(args[1], "123")
  341. @patch("hc.api.transports.requests.request")
  342. def test_slack_handles_500(self, mock_post):
  343. self._setup_data("slack", "123")
  344. mock_post.return_value.status_code = 500
  345. self.channel.notify(self.check)
  346. n = Notification.objects.get()
  347. self.assertEqual(n.error, "Received status code 500")
  348. @patch("hc.api.transports.requests.request", side_effect=Timeout)
  349. def test_slack_handles_timeout(self, mock_post):
  350. self._setup_data("slack", "123")
  351. self.channel.notify(self.check)
  352. n = Notification.objects.get()
  353. self.assertEqual(n.error, "Connection timed out")
  354. @patch("hc.api.transports.requests.request")
  355. def test_slack_with_tabs_in_schedule(self, mock_post):
  356. self._setup_data("slack", "123")
  357. self.check.kind = "cron"
  358. self.check.schedule = "*\t* * * *"
  359. self.check.save()
  360. mock_post.return_value.status_code = 200
  361. self.channel.notify(self.check)
  362. self.assertEqual(Notification.objects.count(), 1)
  363. self.assertTrue(mock_post.called)
  364. @patch("hc.api.transports.requests.request")
  365. def test_hipchat(self, mock_post):
  366. self._setup_data("hipchat", "123")
  367. self.channel.notify(self.check)
  368. self.assertFalse(mock_post.called)
  369. self.assertEqual(Notification.objects.count(), 0)
  370. @patch("hc.api.transports.requests.request")
  371. def test_opsgenie_with_legacy_value(self, mock_post):
  372. self._setup_data("opsgenie", "123")
  373. mock_post.return_value.status_code = 202
  374. self.channel.notify(self.check)
  375. n = Notification.objects.first()
  376. self.assertEqual(n.error, "")
  377. self.assertEqual(mock_post.call_count, 1)
  378. args, kwargs = mock_post.call_args
  379. self.assertIn("api.opsgenie.com", args[1])
  380. payload = kwargs["json"]
  381. self.assertIn("DOWN", payload["message"])
  382. @patch("hc.api.transports.requests.request")
  383. def test_opsgenie_up(self, mock_post):
  384. self._setup_data("opsgenie", "123", status="up")
  385. mock_post.return_value.status_code = 202
  386. self.channel.notify(self.check)
  387. n = Notification.objects.first()
  388. self.assertEqual(n.error, "")
  389. self.assertEqual(mock_post.call_count, 1)
  390. args, kwargs = mock_post.call_args
  391. method, url = args
  392. self.assertTrue(str(self.check.code) in url)
  393. @patch("hc.api.transports.requests.request")
  394. def test_opsgenie_with_json_value(self, mock_post):
  395. self._setup_data("opsgenie", json.dumps({"key": "456", "region": "eu"}))
  396. mock_post.return_value.status_code = 202
  397. self.channel.notify(self.check)
  398. n = Notification.objects.first()
  399. self.assertEqual(n.error, "")
  400. self.assertEqual(mock_post.call_count, 1)
  401. args, kwargs = mock_post.call_args
  402. self.assertIn("api.eu.opsgenie.com", args[1])
  403. @patch("hc.api.transports.requests.request")
  404. def test_opsgenie_returns_error(self, mock_post):
  405. self._setup_data("opsgenie", "123")
  406. mock_post.return_value.status_code = 403
  407. mock_post.return_value.json.return_value = {"message": "Nice try"}
  408. self.channel.notify(self.check)
  409. n = Notification.objects.first()
  410. self.assertEqual(n.error, 'Received status code 403 with a message: "Nice try"')
  411. @patch("hc.api.transports.requests.request")
  412. def test_pushover(self, mock_post):
  413. self._setup_data("po", "123|0")
  414. mock_post.return_value.status_code = 200
  415. self.channel.notify(self.check)
  416. assert Notification.objects.count() == 1
  417. args, kwargs = mock_post.call_args
  418. payload = kwargs["data"]
  419. self.assertIn("DOWN", payload["title"])
  420. @patch("hc.api.transports.requests.request")
  421. def test_pushover_up_priority(self, mock_post):
  422. self._setup_data("po", "123|0|2", status="up")
  423. mock_post.return_value.status_code = 200
  424. self.channel.notify(self.check)
  425. assert Notification.objects.count() == 1
  426. args, kwargs = mock_post.call_args
  427. payload = kwargs["data"]
  428. self.assertIn("UP", payload["title"])
  429. self.assertEqual(payload["priority"], 2)
  430. self.assertIn("retry", payload)
  431. self.assertIn("expire", payload)
  432. @patch("hc.api.transports.requests.request")
  433. def test_victorops(self, mock_post):
  434. self._setup_data("victorops", "123")
  435. mock_post.return_value.status_code = 200
  436. self.channel.notify(self.check)
  437. assert Notification.objects.count() == 1
  438. args, kwargs = mock_post.call_args
  439. payload = kwargs["json"]
  440. self.assertEqual(payload["message_type"], "CRITICAL")
  441. @patch("hc.api.transports.requests.request")
  442. def test_discord(self, mock_post):
  443. v = json.dumps({"webhook": {"url": "123"}})
  444. self._setup_data("discord", v)
  445. mock_post.return_value.status_code = 200
  446. self.channel.notify(self.check)
  447. assert Notification.objects.count() == 1
  448. args, kwargs = mock_post.call_args
  449. payload = kwargs["json"]
  450. attachment = payload["attachments"][0]
  451. fields = {f["title"]: f["value"] for f in attachment["fields"]}
  452. self.assertEqual(fields["Last Ping"], "an hour ago")
  453. @patch("hc.api.transports.requests.request")
  454. def test_discord_rewrites_discordapp_com(self, mock_post):
  455. v = json.dumps({"webhook": {"url": "https://discordapp.com/foo"}})
  456. self._setup_data("discord", v)
  457. mock_post.return_value.status_code = 200
  458. self.channel.notify(self.check)
  459. assert Notification.objects.count() == 1
  460. args, kwargs = mock_post.call_args
  461. url = args[1]
  462. # discordapp.com is deprecated. For existing webhook URLs, wwe should
  463. # rewrite discordapp.com to discord.com:
  464. self.assertEqual(url, "https://discord.com/foo/slack")
  465. @patch("hc.api.transports.requests.request")
  466. def test_pushbullet(self, mock_post):
  467. self._setup_data("pushbullet", "fake-token")
  468. mock_post.return_value.status_code = 200
  469. self.channel.notify(self.check)
  470. assert Notification.objects.count() == 1
  471. _, kwargs = mock_post.call_args
  472. self.assertEqual(kwargs["json"]["type"], "note")
  473. self.assertEqual(kwargs["headers"]["Access-Token"], "fake-token")
  474. @patch("hc.api.transports.requests.request")
  475. def test_telegram(self, mock_post):
  476. v = json.dumps({"id": 123})
  477. self._setup_data("telegram", v)
  478. mock_post.return_value.status_code = 200
  479. self.channel.notify(self.check)
  480. assert Notification.objects.count() == 1
  481. args, kwargs = mock_post.call_args
  482. payload = kwargs["json"]
  483. self.assertEqual(payload["chat_id"], 123)
  484. self.assertTrue("The check" in payload["text"])
  485. @patch("hc.api.transports.requests.request")
  486. def test_telegram_returns_error(self, mock_post):
  487. self._setup_data("telegram", json.dumps({"id": 123}))
  488. mock_post.return_value.status_code = 400
  489. mock_post.return_value.json.return_value = {"description": "Hi"}
  490. self.channel.notify(self.check)
  491. n = Notification.objects.first()
  492. self.assertEqual(n.error, 'Received status code 400 with a message: "Hi"')
  493. def test_telegram_obeys_rate_limit(self):
  494. self._setup_data("telegram", json.dumps({"id": 123}))
  495. TokenBucket.objects.create(value="tg-123", tokens=0)
  496. self.channel.notify(self.check)
  497. n = Notification.objects.first()
  498. self.assertEqual(n.error, "Rate limit exceeded")
  499. @patch("hc.api.transports.requests.request")
  500. def test_sms(self, mock_post):
  501. self._setup_data("sms", "+1234567890")
  502. self.check.last_ping = now() - td(hours=2)
  503. mock_post.return_value.status_code = 200
  504. self.channel.notify(self.check)
  505. n = Notification.objects.get()
  506. args, kwargs = mock_post.call_args
  507. payload = kwargs["data"]
  508. self.assertEqual(payload["To"], "+1234567890")
  509. self.assertFalse("\xa0" in payload["Body"])
  510. callback_path = f"/api/v1/notifications/{n.code}/status"
  511. self.assertTrue(payload["StatusCallback"].endswith(callback_path))
  512. # sent SMS counter should go up
  513. self.profile.refresh_from_db()
  514. self.assertEqual(self.profile.sms_sent, 1)
  515. @patch("hc.api.transports.requests.request")
  516. def test_sms_handles_json_value(self, mock_post):
  517. value = {"label": "foo", "value": "+1234567890"}
  518. self._setup_data("sms", json.dumps(value))
  519. self.check.last_ping = now() - td(hours=2)
  520. mock_post.return_value.status_code = 200
  521. self.channel.notify(self.check)
  522. assert Notification.objects.count() == 1
  523. args, kwargs = mock_post.call_args
  524. payload = kwargs["data"]
  525. self.assertEqual(payload["To"], "+1234567890")
  526. @patch("hc.api.transports.requests.request")
  527. def test_sms_limit(self, mock_post):
  528. # At limit already:
  529. self.profile.last_sms_date = now()
  530. self.profile.sms_sent = 50
  531. self.profile.save()
  532. self._setup_data("sms", "+1234567890")
  533. self.channel.notify(self.check)
  534. self.assertFalse(mock_post.called)
  535. n = Notification.objects.get()
  536. self.assertTrue("Monthly SMS limit exceeded" in n.error)
  537. # And email should have been sent
  538. self.assertEqual(len(mail.outbox), 1)
  539. email = mail.outbox[0]
  540. self.assertEqual(email.to[0], "[email protected]")
  541. self.assertEqual(email.subject, "Monthly SMS Limit Reached")
  542. @patch("hc.api.transports.requests.request")
  543. def test_sms_limit_reset(self, mock_post):
  544. # At limit, but also into a new month
  545. self.profile.sms_sent = 50
  546. self.profile.last_sms_date = now() - td(days=100)
  547. self.profile.save()
  548. self._setup_data("sms", "+1234567890")
  549. mock_post.return_value.status_code = 200
  550. self.channel.notify(self.check)
  551. self.assertTrue(mock_post.called)
  552. @patch("hc.api.transports.requests.request")
  553. def test_whatsapp(self, mock_post):
  554. definition = {"value": "+1234567890", "up": True, "down": True}
  555. self._setup_data("whatsapp", json.dumps(definition))
  556. self.check.last_ping = now() - td(hours=2)
  557. mock_post.return_value.status_code = 200
  558. self.channel.notify(self.check)
  559. args, kwargs = mock_post.call_args
  560. payload = kwargs["data"]
  561. self.assertEqual(payload["To"], "whatsapp:+1234567890")
  562. n = Notification.objects.get()
  563. callback_path = f"/api/v1/notifications/{n.code}/status"
  564. self.assertTrue(payload["StatusCallback"].endswith(callback_path))
  565. # sent SMS counter should go up
  566. self.profile.refresh_from_db()
  567. self.assertEqual(self.profile.sms_sent, 1)
  568. @patch("hc.api.transports.requests.request")
  569. def test_whatsapp_obeys_up_down_flags(self, mock_post):
  570. definition = {"value": "+1234567890", "up": True, "down": False}
  571. self._setup_data("whatsapp", json.dumps(definition))
  572. self.check.last_ping = now() - td(hours=2)
  573. self.channel.notify(self.check)
  574. self.assertEqual(Notification.objects.count(), 0)
  575. self.assertFalse(mock_post.called)
  576. @patch("hc.api.transports.requests.request")
  577. def test_whatsapp_limit(self, mock_post):
  578. # At limit already:
  579. self.profile.last_sms_date = now()
  580. self.profile.sms_sent = 50
  581. self.profile.save()
  582. definition = {"value": "+1234567890", "up": True, "down": True}
  583. self._setup_data("whatsapp", json.dumps(definition))
  584. self.channel.notify(self.check)
  585. self.assertFalse(mock_post.called)
  586. n = Notification.objects.get()
  587. self.assertTrue("Monthly message limit exceeded" in n.error)
  588. # And email should have been sent
  589. self.assertEqual(len(mail.outbox), 1)
  590. email = mail.outbox[0]
  591. self.assertEqual(email.to[0], "[email protected]")
  592. self.assertEqual(email.subject, "Monthly WhatsApp Limit Reached")
  593. @patch("hc.api.transports.requests.request")
  594. def test_call(self, mock_post):
  595. self.profile.call_limit = 1
  596. self.profile.save()
  597. value = {"label": "foo", "value": "+1234567890"}
  598. self._setup_data("call", json.dumps(value))
  599. self.check.last_ping = now() - td(hours=2)
  600. mock_post.return_value.status_code = 200
  601. self.channel.notify(self.check)
  602. args, kwargs = mock_post.call_args
  603. payload = kwargs["data"]
  604. self.assertEqual(payload["To"], "+1234567890")
  605. n = Notification.objects.get()
  606. callback_path = f"/api/v1/notifications/{n.code}/status"
  607. self.assertTrue(payload["StatusCallback"].endswith(callback_path))
  608. @patch("hc.api.transports.requests.request")
  609. def test_call_limit(self, mock_post):
  610. # At limit already:
  611. self.profile.last_call_date = now()
  612. self.profile.calls_sent = 50
  613. self.profile.save()
  614. definition = {"value": "+1234567890"}
  615. self._setup_data("call", json.dumps(definition))
  616. self.channel.notify(self.check)
  617. self.assertFalse(mock_post.called)
  618. n = Notification.objects.get()
  619. self.assertTrue("Monthly phone call limit exceeded" in n.error)
  620. # And email should have been sent
  621. self.assertEqual(len(mail.outbox), 1)
  622. email = mail.outbox[0]
  623. self.assertEqual(email.to[0], "[email protected]")
  624. self.assertEqual(email.subject, "Monthly Phone Call Limit Reached")
  625. @patch("hc.api.transports.requests.request")
  626. def test_call_limit_reset(self, mock_post):
  627. # At limit, but also into a new month
  628. self.profile.calls_sent = 50
  629. self.profile.last_call_date = now() - td(days=100)
  630. self.profile.save()
  631. self._setup_data("sms", "+1234567890")
  632. mock_post.return_value.status_code = 200
  633. self.channel.notify(self.check)
  634. self.assertTrue(mock_post.called)
  635. @patch("apprise.Apprise")
  636. @override_settings(APPRISE_ENABLED=True)
  637. def test_apprise_enabled(self, mock_apprise):
  638. self._setup_data("apprise", "123")
  639. mock_aobj = Mock()
  640. mock_aobj.add.return_value = True
  641. mock_aobj.notify.return_value = True
  642. mock_apprise.return_value = mock_aobj
  643. self.channel.notify(self.check)
  644. self.assertEqual(Notification.objects.count(), 1)
  645. self.check.status = "up"
  646. self.assertEqual(Notification.objects.count(), 1)
  647. @patch("apprise.Apprise")
  648. @override_settings(APPRISE_ENABLED=False)
  649. def test_apprise_disabled(self, mock_apprise):
  650. self._setup_data("apprise", "123")
  651. mock_aobj = Mock()
  652. mock_aobj.add.return_value = True
  653. mock_aobj.notify.return_value = True
  654. mock_apprise.return_value = mock_aobj
  655. self.channel.notify(self.check)
  656. self.assertEqual(Notification.objects.count(), 1)
  657. def test_not_implimented(self):
  658. self._setup_data("webhook", "http://example")
  659. self.channel.kind = "invalid"
  660. with self.assertRaises(NotImplementedError):
  661. self.channel.notify(self.check)
  662. @patch("hc.api.transports.requests.request")
  663. def test_msteams(self, mock_post):
  664. self._setup_data("msteams", "http://example.com/webhook")
  665. mock_post.return_value.status_code = 200
  666. self.channel.notify(self.check)
  667. assert Notification.objects.count() == 1
  668. args, kwargs = mock_post.call_args
  669. payload = kwargs["json"]
  670. self.assertEqual(payload["@type"], "MessageCard")
  671. @patch("hc.api.transports.os.system")
  672. @override_settings(SHELL_ENABLED=True)
  673. def test_shell(self, mock_system):
  674. definition = {"cmd_down": "logger hello", "cmd_up": ""}
  675. self._setup_data("shell", json.dumps(definition))
  676. mock_system.return_value = 0
  677. self.channel.notify(self.check)
  678. mock_system.assert_called_with("logger hello")
  679. @patch("hc.api.transports.os.system")
  680. @override_settings(SHELL_ENABLED=True)
  681. def test_shell_handles_nonzero_exit_code(self, mock_system):
  682. definition = {"cmd_down": "logger hello", "cmd_up": ""}
  683. self._setup_data("shell", json.dumps(definition))
  684. mock_system.return_value = 123
  685. self.channel.notify(self.check)
  686. n = Notification.objects.get()
  687. self.assertEqual(n.error, "Command returned exit code 123")
  688. @patch("hc.api.transports.os.system")
  689. @override_settings(SHELL_ENABLED=True)
  690. def test_shell_supports_variables(self, mock_system):
  691. definition = {"cmd_down": "logger $NAME is $STATUS ($TAG1)", "cmd_up": ""}
  692. self._setup_data("shell", json.dumps(definition))
  693. mock_system.return_value = 0
  694. self.check.name = "Database"
  695. self.check.tags = "foo bar"
  696. self.check.save()
  697. self.channel.notify(self.check)
  698. mock_system.assert_called_with("logger Database is down (foo)")
  699. @patch("hc.api.transports.os.system")
  700. @override_settings(SHELL_ENABLED=False)
  701. def test_shell_disabled(self, mock_system):
  702. definition = {"cmd_down": "logger hello", "cmd_up": ""}
  703. self._setup_data("shell", json.dumps(definition))
  704. self.channel.notify(self.check)
  705. self.assertFalse(mock_system.called)
  706. n = Notification.objects.get()
  707. self.assertEqual(n.error, "Shell commands are not enabled")
  708. @patch("hc.api.transports.requests.request")
  709. def test_zulip(self, mock_post):
  710. definition = {
  711. "bot_email": "[email protected]",
  712. "api_key": "fake-key",
  713. "mtype": "stream",
  714. "to": "general",
  715. }
  716. self._setup_data("zulip", json.dumps(definition))
  717. mock_post.return_value.status_code = 200
  718. self.channel.notify(self.check)
  719. assert Notification.objects.count() == 1
  720. args, kwargs = mock_post.call_args
  721. payload = kwargs["data"]
  722. self.assertIn("DOWN", payload["topic"])
  723. @patch("hc.api.transports.requests.request")
  724. def test_zulip_returns_error(self, mock_post):
  725. definition = {
  726. "bot_email": "[email protected]",
  727. "api_key": "fake-key",
  728. "mtype": "stream",
  729. "to": "general",
  730. }
  731. self._setup_data("zulip", json.dumps(definition))
  732. mock_post.return_value.status_code = 403
  733. mock_post.return_value.json.return_value = {"msg": "Nice try"}
  734. self.channel.notify(self.check)
  735. n = Notification.objects.first()
  736. self.assertEqual(n.error, 'Received status code 403 with a message: "Nice try"')