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.

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