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.

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