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.

82 lines
2.5 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 django.test.utils import override_settings
  7. from hc.api.models import Channel, Check, Notification
  8. from hc.test import BaseTestCase
  9. @override_settings(SIGNAL_CLI_USERNAME="+987654321")
  10. class NotifySignalTestCase(BaseTestCase):
  11. def setUp(self):
  12. super().setUp()
  13. self.check = Check(project=self.project)
  14. self.check.name = "Daily Backup"
  15. self.check.status = "down"
  16. self.check.last_ping = now() - td(minutes=61)
  17. self.check.save()
  18. payload = {"value": "+123456789", "up": True, "down": True}
  19. self.channel = Channel(project=self.project)
  20. self.channel.kind = "signal"
  21. self.channel.value = json.dumps(payload)
  22. self.channel.save()
  23. self.channel.checks.add(self.check)
  24. @patch("hc.api.transports.subprocess.run")
  25. def test_it_works(self, mock_run):
  26. mock_run.return_value.returncode = 0
  27. self.channel.notify(self.check)
  28. n = Notification.objects.get()
  29. self.assertEqual(n.error, "")
  30. self.assertTrue(mock_run.called)
  31. args, kwargs = mock_run.call_args
  32. cmd = " ".join(args[0])
  33. self.assertIn("-u +987654321", cmd)
  34. self.assertIn("send +123456789", cmd)
  35. @patch("hc.api.transports.subprocess.run")
  36. def test_it_obeys_down_flag(self, mock_run):
  37. payload = {"value": "+123456789", "up": True, "down": False}
  38. self.channel.value = json.dumps(payload)
  39. self.channel.save()
  40. self.channel.notify(self.check)
  41. # This channel should not notify on "down" events:
  42. self.assertEqual(Notification.objects.count(), 0)
  43. self.assertFalse(mock_run.called)
  44. @patch("hc.api.transports.subprocess.run")
  45. def test_it_requires_signal_cli_username(self, mock_run):
  46. with override_settings(SIGNAL_CLI_USERNAME=None):
  47. self.channel.notify(self.check)
  48. n = Notification.objects.get()
  49. self.assertEqual(n.error, "Signal notifications are not enabled")
  50. self.assertFalse(mock_run.called)
  51. @patch("hc.api.transports.subprocess.run")
  52. def test_it_does_not_escape_special_characters(self, mock_run):
  53. self.check.name = "Foo & Bar"
  54. self.check.save()
  55. mock_run.return_value.returncode = 0
  56. self.channel.notify(self.check)
  57. self.assertTrue(mock_run.called)
  58. args, kwargs = mock_run.call_args
  59. cmd = " ".join(args[0])
  60. self.assertIn("Foo & Bar", cmd)