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.

86 lines
2.7 KiB

  1. # coding: utf-8
  2. from datetime import timedelta as td
  3. import json
  4. from unittest.mock import patch
  5. from django.utils.timezone import now
  6. from hc.api.models import Channel, Check, Notification
  7. from hc.test import BaseTestCase
  8. class NotifyTestCase(BaseTestCase):
  9. def _setup_data(self, kind, value, status="down", email_verified=True):
  10. self.check = Check(project=self.project)
  11. self.check.status = status
  12. self.check.last_ping = now() - td(minutes=61)
  13. self.check.save()
  14. self.channel = Channel(project=self.project)
  15. self.channel.kind = kind
  16. self.channel.value = value
  17. self.channel.email_verified = email_verified
  18. self.channel.save()
  19. self.channel.checks.add(self.check)
  20. @patch("hc.api.transports.requests.request")
  21. def test_zulip(self, mock_post):
  22. definition = {
  23. "bot_email": "[email protected]",
  24. "api_key": "fake-key",
  25. "mtype": "stream",
  26. "to": "general",
  27. }
  28. self._setup_data("zulip", json.dumps(definition))
  29. mock_post.return_value.status_code = 200
  30. self.channel.notify(self.check)
  31. assert Notification.objects.count() == 1
  32. args, kwargs = mock_post.call_args
  33. method, url = args
  34. self.assertEqual(url, "https://example.org/api/v1/messages")
  35. payload = kwargs["data"]
  36. self.assertIn("DOWN", payload["topic"])
  37. @patch("hc.api.transports.requests.request")
  38. def test_zulip_returns_error(self, mock_post):
  39. definition = {
  40. "bot_email": "[email protected]",
  41. "api_key": "fake-key",
  42. "mtype": "stream",
  43. "to": "general",
  44. }
  45. self._setup_data("zulip", json.dumps(definition))
  46. mock_post.return_value.status_code = 403
  47. mock_post.return_value.json.return_value = {"msg": "Nice try"}
  48. self.channel.notify(self.check)
  49. n = Notification.objects.first()
  50. self.assertEqual(n.error, 'Received status code 403 with a message: "Nice try"')
  51. @patch("hc.api.transports.requests.request")
  52. def test_zulip_uses_site_parameter(self, mock_post):
  53. definition = {
  54. "bot_email": "[email protected]",
  55. "site": "https://custom.example.org",
  56. "api_key": "fake-key",
  57. "mtype": "stream",
  58. "to": "general",
  59. }
  60. self._setup_data("zulip", json.dumps(definition))
  61. mock_post.return_value.status_code = 200
  62. self.channel.notify(self.check)
  63. assert Notification.objects.count() == 1
  64. args, kwargs = mock_post.call_args
  65. method, url = args
  66. self.assertEqual(url, "https://custom.example.org/api/v1/messages")
  67. payload = kwargs["data"]
  68. self.assertIn("DOWN", payload["topic"])