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.

231 lines
8.2 KiB

6 years ago
9 years ago
9 years ago
6 years ago
6 years ago
6 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
  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 django.test.utils import override_settings
  10. class NotifyTestCase(BaseTestCase):
  11. def _setup_data(self, kind, value, status="down", email_verified=True):
  12. self.check = Check(project=self.project)
  13. self.check.status = status
  14. self.check.last_ping = now() - td(minutes=61)
  15. self.check.save()
  16. self.channel = Channel(project=self.project)
  17. self.channel.kind = kind
  18. self.channel.value = value
  19. self.channel.email_verified = email_verified
  20. self.channel.save()
  21. self.channel.checks.add(self.check)
  22. @patch("hc.api.transports.requests.request")
  23. def test_pagerteam(self, mock_post):
  24. self._setup_data("pagerteam", "123")
  25. self.channel.notify(self.check)
  26. self.assertFalse(mock_post.called)
  27. self.assertEqual(Notification.objects.count(), 0)
  28. @patch("hc.api.transports.requests.request")
  29. def test_hipchat(self, mock_post):
  30. self._setup_data("hipchat", "123")
  31. self.channel.notify(self.check)
  32. self.assertFalse(mock_post.called)
  33. self.assertEqual(Notification.objects.count(), 0)
  34. @patch("hc.api.transports.requests.request")
  35. def test_discord(self, mock_post):
  36. v = json.dumps({"webhook": {"url": "123"}})
  37. self._setup_data("discord", v)
  38. mock_post.return_value.status_code = 200
  39. self.channel.notify(self.check)
  40. assert Notification.objects.count() == 1
  41. args, kwargs = mock_post.call_args
  42. payload = kwargs["json"]
  43. attachment = payload["attachments"][0]
  44. fields = {f["title"]: f["value"] for f in attachment["fields"]}
  45. self.assertEqual(fields["Last Ping"], "an hour ago")
  46. @patch("hc.api.transports.requests.request")
  47. def test_discord_rewrites_discordapp_com(self, mock_post):
  48. v = json.dumps({"webhook": {"url": "https://discordapp.com/foo"}})
  49. self._setup_data("discord", v)
  50. mock_post.return_value.status_code = 200
  51. self.channel.notify(self.check)
  52. assert Notification.objects.count() == 1
  53. args, kwargs = mock_post.call_args
  54. url = args[1]
  55. # discordapp.com is deprecated. For existing webhook URLs, wwe should
  56. # rewrite discordapp.com to discord.com:
  57. self.assertEqual(url, "https://discord.com/foo/slack")
  58. @patch("hc.api.transports.requests.request")
  59. def test_pushbullet(self, mock_post):
  60. self._setup_data("pushbullet", "fake-token")
  61. mock_post.return_value.status_code = 200
  62. self.channel.notify(self.check)
  63. assert Notification.objects.count() == 1
  64. _, kwargs = mock_post.call_args
  65. self.assertEqual(kwargs["json"]["type"], "note")
  66. self.assertEqual(kwargs["headers"]["Access-Token"], "fake-token")
  67. @patch("hc.api.transports.requests.request")
  68. def test_telegram(self, mock_post):
  69. v = json.dumps({"id": 123})
  70. self._setup_data("telegram", v)
  71. mock_post.return_value.status_code = 200
  72. self.channel.notify(self.check)
  73. assert Notification.objects.count() == 1
  74. args, kwargs = mock_post.call_args
  75. payload = kwargs["json"]
  76. self.assertEqual(payload["chat_id"], 123)
  77. self.assertTrue("The check" in payload["text"])
  78. @patch("hc.api.transports.requests.request")
  79. def test_telegram_returns_error(self, mock_post):
  80. self._setup_data("telegram", json.dumps({"id": 123}))
  81. mock_post.return_value.status_code = 400
  82. mock_post.return_value.json.return_value = {"description": "Hi"}
  83. self.channel.notify(self.check)
  84. n = Notification.objects.first()
  85. self.assertEqual(n.error, 'Received status code 400 with a message: "Hi"')
  86. def test_telegram_obeys_rate_limit(self):
  87. self._setup_data("telegram", json.dumps({"id": 123}))
  88. TokenBucket.objects.create(value="tg-123", tokens=0)
  89. self.channel.notify(self.check)
  90. n = Notification.objects.first()
  91. self.assertEqual(n.error, "Rate limit exceeded")
  92. @patch("hc.api.transports.requests.request")
  93. def test_call(self, mock_post):
  94. self.profile.call_limit = 1
  95. self.profile.save()
  96. value = {"label": "foo", "value": "+1234567890"}
  97. self._setup_data("call", json.dumps(value))
  98. self.check.last_ping = now() - td(hours=2)
  99. mock_post.return_value.status_code = 200
  100. self.channel.notify(self.check)
  101. args, kwargs = mock_post.call_args
  102. payload = kwargs["data"]
  103. self.assertEqual(payload["To"], "+1234567890")
  104. n = Notification.objects.get()
  105. callback_path = f"/api/v1/notifications/{n.code}/status"
  106. self.assertTrue(payload["StatusCallback"].endswith(callback_path))
  107. @patch("hc.api.transports.requests.request")
  108. def test_call_limit(self, mock_post):
  109. # At limit already:
  110. self.profile.call_limit = 50
  111. self.profile.last_call_date = now()
  112. self.profile.calls_sent = 50
  113. self.profile.save()
  114. definition = {"value": "+1234567890"}
  115. self._setup_data("call", json.dumps(definition))
  116. self.channel.notify(self.check)
  117. self.assertFalse(mock_post.called)
  118. n = Notification.objects.get()
  119. self.assertTrue("Monthly phone call limit exceeded" in n.error)
  120. # And email should have been sent
  121. self.assertEqual(len(mail.outbox), 1)
  122. email = mail.outbox[0]
  123. self.assertEqual(email.to[0], "[email protected]")
  124. self.assertEqual(email.subject, "Monthly Phone Call Limit Reached")
  125. @patch("hc.api.transports.requests.request")
  126. def test_call_limit_reset(self, mock_post):
  127. # At limit, but also into a new month
  128. self.profile.call_limit = 50
  129. self.profile.calls_sent = 50
  130. self.profile.last_call_date = now() - td(days=100)
  131. self.profile.save()
  132. self._setup_data("call", "+1234567890")
  133. mock_post.return_value.status_code = 200
  134. self.channel.notify(self.check)
  135. self.assertTrue(mock_post.called)
  136. def test_not_implimented(self):
  137. self._setup_data("webhook", "http://example")
  138. self.channel.kind = "invalid"
  139. with self.assertRaises(NotImplementedError):
  140. self.channel.notify(self.check)
  141. @patch("hc.api.transports.os.system")
  142. @override_settings(SHELL_ENABLED=True)
  143. def test_shell(self, mock_system):
  144. definition = {"cmd_down": "logger hello", "cmd_up": ""}
  145. self._setup_data("shell", json.dumps(definition))
  146. mock_system.return_value = 0
  147. self.channel.notify(self.check)
  148. mock_system.assert_called_with("logger hello")
  149. @patch("hc.api.transports.os.system")
  150. @override_settings(SHELL_ENABLED=True)
  151. def test_shell_handles_nonzero_exit_code(self, mock_system):
  152. definition = {"cmd_down": "logger hello", "cmd_up": ""}
  153. self._setup_data("shell", json.dumps(definition))
  154. mock_system.return_value = 123
  155. self.channel.notify(self.check)
  156. n = Notification.objects.get()
  157. self.assertEqual(n.error, "Command returned exit code 123")
  158. @patch("hc.api.transports.os.system")
  159. @override_settings(SHELL_ENABLED=True)
  160. def test_shell_supports_variables(self, mock_system):
  161. definition = {"cmd_down": "logger $NAME is $STATUS ($TAG1)", "cmd_up": ""}
  162. self._setup_data("shell", json.dumps(definition))
  163. mock_system.return_value = 0
  164. self.check.name = "Database"
  165. self.check.tags = "foo bar"
  166. self.check.save()
  167. self.channel.notify(self.check)
  168. mock_system.assert_called_with("logger Database is down (foo)")
  169. @patch("hc.api.transports.os.system")
  170. @override_settings(SHELL_ENABLED=False)
  171. def test_shell_disabled(self, mock_system):
  172. definition = {"cmd_down": "logger hello", "cmd_up": ""}
  173. self._setup_data("shell", json.dumps(definition))
  174. self.channel.notify(self.check)
  175. self.assertFalse(mock_system.called)
  176. n = Notification.objects.get()
  177. self.assertEqual(n.error, "Shell commands are not enabled")