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.

65 lines
2.2 KiB

  1. # coding: utf-8
  2. from datetime import timedelta as td
  3. from unittest.mock import patch
  4. from django.test.utils import override_settings
  5. from django.utils.timezone import now
  6. from hc.api.models import Channel, Check, Notification, TokenBucket
  7. from hc.test import BaseTestCase
  8. class NotifyTestCase(BaseTestCase):
  9. def _setup_data(self, 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 = "po"
  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_pushover(self, mock_post):
  22. self._setup_data("123|0")
  23. mock_post.return_value.status_code = 200
  24. self.channel.notify(self.check)
  25. assert Notification.objects.count() == 1
  26. args, kwargs = mock_post.call_args
  27. payload = kwargs["data"]
  28. self.assertIn("DOWN", payload["title"])
  29. @patch("hc.api.transports.requests.request")
  30. def test_pushover_up_priority(self, mock_post):
  31. self._setup_data("123|0|2", status="up")
  32. mock_post.return_value.status_code = 200
  33. self.channel.notify(self.check)
  34. assert Notification.objects.count() == 1
  35. args, kwargs = mock_post.call_args
  36. payload = kwargs["data"]
  37. self.assertIn("UP", payload["title"])
  38. self.assertEqual(payload["priority"], 2)
  39. self.assertIn("retry", payload)
  40. self.assertIn("expire", payload)
  41. @override_settings(SECRET_KEY="test-secret")
  42. @patch("hc.api.transports.requests.request")
  43. def test_it_obeys_rate_limit(self, mock_post):
  44. self._setup_data("123|0")
  45. # "c0ca..." is sha1("123test-secret")
  46. obj = TokenBucket(value="po-c0ca2a9774952af32cabf86453f69e442c4ed0eb")
  47. obj.tokens = 0
  48. obj.save()
  49. self.channel.notify(self.check)
  50. n = Notification.objects.first()
  51. self.assertEqual(n.error, "Rate limit exceeded")