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.

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