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.

800 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. 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. @patch("hc.api.transports.requests.request")
  280. def test_pd(self, mock_post):
  281. self._setup_data("pd", "123")
  282. mock_post.return_value.status_code = 200
  283. self.channel.notify(self.check)
  284. assert Notification.objects.count() == 1
  285. args, kwargs = mock_post.call_args
  286. payload = kwargs["json"]
  287. self.assertEqual(payload["event_type"], "trigger")
  288. self.assertEqual(payload["service_key"], "123")
  289. @patch("hc.api.transports.requests.request")
  290. def test_pd_complex(self, mock_post):
  291. self._setup_data("pd", json.dumps({"service_key": "456"}))
  292. mock_post.return_value.status_code = 200
  293. self.channel.notify(self.check)
  294. assert Notification.objects.count() == 1
  295. args, kwargs = mock_post.call_args
  296. payload = kwargs["json"]
  297. self.assertEqual(payload["event_type"], "trigger")
  298. self.assertEqual(payload["service_key"], "456")
  299. @patch("hc.api.transports.requests.request")
  300. def test_pagertree(self, mock_post):
  301. self._setup_data("pagertree", "123")
  302. mock_post.return_value.status_code = 200
  303. self.channel.notify(self.check)
  304. assert Notification.objects.count() == 1
  305. args, kwargs = mock_post.call_args
  306. payload = kwargs["json"]
  307. self.assertEqual(payload["event_type"], "trigger")
  308. @patch("hc.api.transports.requests.request")
  309. def test_pagerteam(self, mock_post):
  310. self._setup_data("pagerteam", "123")
  311. mock_post.return_value.status_code = 200
  312. self.channel.notify(self.check)
  313. assert Notification.objects.count() == 1
  314. args, kwargs = mock_post.call_args
  315. payload = kwargs["json"]
  316. self.assertEqual(payload["event_type"], "trigger")
  317. @patch("hc.api.transports.requests.request")
  318. def test_slack(self, mock_post):
  319. self._setup_data("slack", "123")
  320. mock_post.return_value.status_code = 200
  321. self.channel.notify(self.check)
  322. assert Notification.objects.count() == 1
  323. args, kwargs = mock_post.call_args
  324. payload = kwargs["json"]
  325. attachment = payload["attachments"][0]
  326. fields = {f["title"]: f["value"] for f in attachment["fields"]}
  327. self.assertEqual(fields["Last Ping"], "an hour ago")
  328. @patch("hc.api.transports.requests.request")
  329. def test_slack_with_complex_value(self, mock_post):
  330. v = json.dumps({"incoming_webhook": {"url": "123"}})
  331. self._setup_data("slack", v)
  332. mock_post.return_value.status_code = 200
  333. self.channel.notify(self.check)
  334. assert Notification.objects.count() == 1
  335. args, kwargs = mock_post.call_args
  336. self.assertEqual(args[1], "123")
  337. @patch("hc.api.transports.requests.request")
  338. def test_slack_handles_500(self, mock_post):
  339. self._setup_data("slack", "123")
  340. mock_post.return_value.status_code = 500
  341. self.channel.notify(self.check)
  342. n = Notification.objects.get()
  343. self.assertEqual(n.error, "Received status code 500")
  344. @patch("hc.api.transports.requests.request", side_effect=Timeout)
  345. def test_slack_handles_timeout(self, mock_post):
  346. self._setup_data("slack", "123")
  347. self.channel.notify(self.check)
  348. n = Notification.objects.get()
  349. self.assertEqual(n.error, "Connection timed out")
  350. @patch("hc.api.transports.requests.request")
  351. def test_slack_with_tabs_in_schedule(self, mock_post):
  352. self._setup_data("slack", "123")
  353. self.check.kind = "cron"
  354. self.check.schedule = "*\t* * * *"
  355. self.check.save()
  356. mock_post.return_value.status_code = 200
  357. self.channel.notify(self.check)
  358. self.assertEqual(Notification.objects.count(), 1)
  359. self.assertTrue(mock_post.called)
  360. @patch("hc.api.transports.requests.request")
  361. def test_hipchat(self, mock_post):
  362. self._setup_data("hipchat", "123")
  363. self.channel.notify(self.check)
  364. self.assertFalse(mock_post.called)
  365. self.assertEqual(Notification.objects.count(), 0)
  366. @patch("hc.api.transports.requests.request")
  367. def test_opsgenie_with_legacy_value(self, mock_post):
  368. self._setup_data("opsgenie", "123")
  369. mock_post.return_value.status_code = 202
  370. self.channel.notify(self.check)
  371. n = Notification.objects.first()
  372. self.assertEqual(n.error, "")
  373. self.assertEqual(mock_post.call_count, 1)
  374. args, kwargs = mock_post.call_args
  375. self.assertIn("api.opsgenie.com", args[1])
  376. payload = kwargs["json"]
  377. self.assertIn("DOWN", payload["message"])
  378. @patch("hc.api.transports.requests.request")
  379. def test_opsgenie_up(self, mock_post):
  380. self._setup_data("opsgenie", "123", status="up")
  381. mock_post.return_value.status_code = 202
  382. self.channel.notify(self.check)
  383. n = Notification.objects.first()
  384. self.assertEqual(n.error, "")
  385. self.assertEqual(mock_post.call_count, 1)
  386. args, kwargs = mock_post.call_args
  387. method, url = args
  388. self.assertTrue(str(self.check.code) in url)
  389. @patch("hc.api.transports.requests.request")
  390. def test_opsgenie_with_json_value(self, mock_post):
  391. self._setup_data("opsgenie", json.dumps({"key": "456", "region": "eu"}))
  392. mock_post.return_value.status_code = 202
  393. self.channel.notify(self.check)
  394. n = Notification.objects.first()
  395. self.assertEqual(n.error, "")
  396. self.assertEqual(mock_post.call_count, 1)
  397. args, kwargs = mock_post.call_args
  398. self.assertIn("api.eu.opsgenie.com", args[1])
  399. @patch("hc.api.transports.requests.request")
  400. def test_pushover(self, mock_post):
  401. self._setup_data("po", "123|0")
  402. mock_post.return_value.status_code = 200
  403. self.channel.notify(self.check)
  404. assert Notification.objects.count() == 1
  405. args, kwargs = mock_post.call_args
  406. payload = kwargs["data"]
  407. self.assertIn("DOWN", payload["title"])
  408. @patch("hc.api.transports.requests.request")
  409. def test_pushover_up_priority(self, mock_post):
  410. self._setup_data("po", "123|0|2", status="up")
  411. mock_post.return_value.status_code = 200
  412. self.channel.notify(self.check)
  413. assert Notification.objects.count() == 1
  414. args, kwargs = mock_post.call_args
  415. payload = kwargs["data"]
  416. self.assertIn("UP", payload["title"])
  417. self.assertEqual(payload["priority"], 2)
  418. self.assertIn("retry", payload)
  419. self.assertIn("expire", payload)
  420. @patch("hc.api.transports.requests.request")
  421. def test_victorops(self, mock_post):
  422. self._setup_data("victorops", "123")
  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["json"]
  428. self.assertEqual(payload["message_type"], "CRITICAL")
  429. @patch("hc.api.transports.requests.request")
  430. def test_discord(self, mock_post):
  431. v = json.dumps({"webhook": {"url": "123"}})
  432. self._setup_data("discord", v)
  433. mock_post.return_value.status_code = 200
  434. self.channel.notify(self.check)
  435. assert Notification.objects.count() == 1
  436. args, kwargs = mock_post.call_args
  437. payload = kwargs["json"]
  438. attachment = payload["attachments"][0]
  439. fields = {f["title"]: f["value"] for f in attachment["fields"]}
  440. self.assertEqual(fields["Last Ping"], "an hour ago")
  441. @patch("hc.api.transports.requests.request")
  442. def test_pushbullet(self, mock_post):
  443. self._setup_data("pushbullet", "fake-token")
  444. mock_post.return_value.status_code = 200
  445. self.channel.notify(self.check)
  446. assert Notification.objects.count() == 1
  447. _, kwargs = mock_post.call_args
  448. self.assertEqual(kwargs["json"]["type"], "note")
  449. self.assertEqual(kwargs["headers"]["Access-Token"], "fake-token")
  450. @patch("hc.api.transports.requests.request")
  451. def test_telegram(self, mock_post):
  452. v = json.dumps({"id": 123})
  453. self._setup_data("telegram", v)
  454. mock_post.return_value.status_code = 200
  455. self.channel.notify(self.check)
  456. assert Notification.objects.count() == 1
  457. args, kwargs = mock_post.call_args
  458. payload = kwargs["json"]
  459. self.assertEqual(payload["chat_id"], 123)
  460. self.assertTrue("The check" in payload["text"])
  461. @patch("hc.api.transports.requests.request")
  462. def test_sms(self, mock_post):
  463. self._setup_data("sms", "+1234567890")
  464. self.check.last_ping = now() - td(hours=2)
  465. mock_post.return_value.status_code = 200
  466. self.channel.notify(self.check)
  467. self.assertEqual(Notification.objects.count(), 1)
  468. args, kwargs = mock_post.call_args
  469. payload = kwargs["data"]
  470. self.assertEqual(payload["To"], "+1234567890")
  471. self.assertFalse("\xa0" in payload["Body"])
  472. # sent SMS counter should go up
  473. self.profile.refresh_from_db()
  474. self.assertEqual(self.profile.sms_sent, 1)
  475. @patch("hc.api.transports.requests.request")
  476. def test_sms_handles_json_value(self, mock_post):
  477. value = {"label": "foo", "value": "+1234567890"}
  478. self._setup_data("sms", json.dumps(value))
  479. self.check.last_ping = now() - td(hours=2)
  480. mock_post.return_value.status_code = 200
  481. self.channel.notify(self.check)
  482. assert Notification.objects.count() == 1
  483. args, kwargs = mock_post.call_args
  484. payload = kwargs["data"]
  485. self.assertEqual(payload["To"], "+1234567890")
  486. @patch("hc.api.transports.requests.request")
  487. def test_sms_limit(self, mock_post):
  488. # At limit already:
  489. self.profile.last_sms_date = now()
  490. self.profile.sms_sent = 50
  491. self.profile.save()
  492. self._setup_data("sms", "+1234567890")
  493. self.channel.notify(self.check)
  494. self.assertFalse(mock_post.called)
  495. n = Notification.objects.get()
  496. self.assertTrue("Monthly SMS limit exceeded" in n.error)
  497. # And email should have been sent
  498. self.assertEqual(len(mail.outbox), 1)
  499. email = mail.outbox[0]
  500. self.assertEqual(email.to[0], "[email protected]")
  501. self.assertEqual(email.subject, "Monthly SMS Limit Reached")
  502. @patch("hc.api.transports.requests.request")
  503. def test_sms_limit_reset(self, mock_post):
  504. # At limit, but also into a new month
  505. self.profile.sms_sent = 50
  506. self.profile.last_sms_date = now() - td(days=100)
  507. self.profile.save()
  508. self._setup_data("sms", "+1234567890")
  509. mock_post.return_value.status_code = 200
  510. self.channel.notify(self.check)
  511. self.assertTrue(mock_post.called)
  512. @patch("hc.api.transports.requests.request")
  513. def test_whatsapp(self, mock_post):
  514. definition = {"value": "+1234567890", "up": True, "down": True}
  515. self._setup_data("whatsapp", json.dumps(definition))
  516. self.check.last_ping = now() - td(hours=2)
  517. mock_post.return_value.status_code = 200
  518. self.channel.notify(self.check)
  519. self.assertEqual(Notification.objects.count(), 1)
  520. args, kwargs = mock_post.call_args
  521. payload = kwargs["data"]
  522. self.assertEqual(payload["To"], "whatsapp:+1234567890")
  523. # sent SMS counter should go up
  524. self.profile.refresh_from_db()
  525. self.assertEqual(self.profile.sms_sent, 1)
  526. @patch("hc.api.transports.requests.request")
  527. def test_whatsapp_obeys_up_down_flags(self, mock_post):
  528. definition = {"value": "+1234567890", "up": True, "down": False}
  529. self._setup_data("whatsapp", json.dumps(definition))
  530. self.check.last_ping = now() - td(hours=2)
  531. self.channel.notify(self.check)
  532. self.assertEqual(Notification.objects.count(), 0)
  533. self.assertFalse(mock_post.called)
  534. @patch("hc.api.transports.requests.request")
  535. def test_whatsapp_limit(self, mock_post):
  536. # At limit already:
  537. self.profile.last_sms_date = now()
  538. self.profile.sms_sent = 50
  539. self.profile.save()
  540. definition = {"value": "+1234567890", "up": True, "down": True}
  541. self._setup_data("whatsapp", json.dumps(definition))
  542. self.channel.notify(self.check)
  543. self.assertFalse(mock_post.called)
  544. n = Notification.objects.get()
  545. self.assertTrue("Monthly message limit exceeded" in n.error)
  546. # And email should have been sent
  547. self.assertEqual(len(mail.outbox), 1)
  548. email = mail.outbox[0]
  549. self.assertEqual(email.to[0], "[email protected]")
  550. self.assertEqual(email.subject, "Monthly WhatsApp Limit Reached")
  551. @patch("apprise.Apprise")
  552. @override_settings(APPRISE_ENABLED=True)
  553. def test_apprise_enabled(self, mock_apprise):
  554. self._setup_data("apprise", "123")
  555. mock_aobj = Mock()
  556. mock_aobj.add.return_value = True
  557. mock_aobj.notify.return_value = True
  558. mock_apprise.return_value = mock_aobj
  559. self.channel.notify(self.check)
  560. self.assertEqual(Notification.objects.count(), 1)
  561. self.check.status = "up"
  562. self.assertEqual(Notification.objects.count(), 1)
  563. @patch("apprise.Apprise")
  564. @override_settings(APPRISE_ENABLED=False)
  565. def test_apprise_disabled(self, mock_apprise):
  566. self._setup_data("apprise", "123")
  567. mock_aobj = Mock()
  568. mock_aobj.add.return_value = True
  569. mock_aobj.notify.return_value = True
  570. mock_apprise.return_value = mock_aobj
  571. self.channel.notify(self.check)
  572. self.assertEqual(Notification.objects.count(), 1)
  573. def test_not_implimented(self):
  574. self._setup_data("webhook", "http://example")
  575. self.channel.kind = "invalid"
  576. with self.assertRaises(NotImplementedError):
  577. self.channel.notify(self.check)
  578. @patch("hc.api.transports.requests.request")
  579. def test_msteams(self, mock_post):
  580. self._setup_data("msteams", "http://example.com/webhook")
  581. mock_post.return_value.status_code = 200
  582. self.channel.notify(self.check)
  583. assert Notification.objects.count() == 1
  584. args, kwargs = mock_post.call_args
  585. payload = kwargs["json"]
  586. self.assertEqual(payload["@type"], "MessageCard")
  587. @patch("hc.api.transports.os.system")
  588. @override_settings(SHELL_ENABLED=True)
  589. def test_shell(self, mock_system):
  590. definition = {"cmd_down": "logger hello", "cmd_up": ""}
  591. self._setup_data("shell", json.dumps(definition))
  592. mock_system.return_value = 0
  593. self.channel.notify(self.check)
  594. mock_system.assert_called_with("logger hello")
  595. @patch("hc.api.transports.os.system")
  596. @override_settings(SHELL_ENABLED=True)
  597. def test_shell_handles_nonzero_exit_code(self, mock_system):
  598. definition = {"cmd_down": "logger hello", "cmd_up": ""}
  599. self._setup_data("shell", json.dumps(definition))
  600. mock_system.return_value = 123
  601. self.channel.notify(self.check)
  602. n = Notification.objects.get()
  603. self.assertEqual(n.error, "Command returned exit code 123")
  604. @patch("hc.api.transports.os.system")
  605. @override_settings(SHELL_ENABLED=True)
  606. def test_shell_supports_variables(self, mock_system):
  607. definition = {"cmd_down": "logger $NAME is $STATUS ($TAG1)", "cmd_up": ""}
  608. self._setup_data("shell", json.dumps(definition))
  609. mock_system.return_value = 0
  610. self.check.name = "Database"
  611. self.check.tags = "foo bar"
  612. self.check.save()
  613. self.channel.notify(self.check)
  614. mock_system.assert_called_with("logger Database is down (foo)")
  615. @patch("hc.api.transports.os.system")
  616. @override_settings(SHELL_ENABLED=False)
  617. def test_shell_disabled(self, mock_system):
  618. definition = {"cmd_down": "logger hello", "cmd_up": ""}
  619. self._setup_data("shell", json.dumps(definition))
  620. self.channel.notify(self.check)
  621. self.assertFalse(mock_system.called)
  622. n = Notification.objects.get()
  623. self.assertEqual(n.error, "Shell commands are not enabled")