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.

77 lines
2.7 KiB

  1. # coding: utf-8
  2. import json
  3. from datetime import timedelta as td
  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. from django.test.utils import override_settings
  9. class NotifyTestCase(BaseTestCase):
  10. def _setup_data(self, value, status="down", email_verified=True):
  11. self.check = Check(project=self.project)
  12. self.check.status = status
  13. self.check.last_ping = now() - td(minutes=61)
  14. self.check.save()
  15. self.channel = Channel(project=self.project)
  16. self.channel.kind = "msteams"
  17. self.channel.value = value
  18. self.channel.email_verified = email_verified
  19. self.channel.save()
  20. self.channel.checks.add(self.check)
  21. @patch("hc.api.transports.requests.request")
  22. def test_msteams(self, mock_post):
  23. self._setup_data("http://example.com/webhook")
  24. mock_post.return_value.status_code = 200
  25. self.check.name = "_underscores_ & more"
  26. self.channel.notify(self.check)
  27. assert Notification.objects.count() == 1
  28. args, kwargs = mock_post.call_args
  29. payload = kwargs["json"]
  30. self.assertEqual(payload["@type"], "MessageCard")
  31. # summary and title should be the same, except
  32. # title should have any special HTML characters escaped
  33. self.assertEqual(payload["summary"], "“_underscores_ & more” is DOWN.")
  34. self.assertEqual(payload["title"], "“_underscores_ & more” is DOWN.")
  35. # The payload should not contain check's code
  36. serialized = json.dumps(payload)
  37. self.assertNotIn(str(self.check.code), serialized)
  38. @patch("hc.api.transports.requests.request")
  39. def test_msteams_escapes_html_and_markdown_in_desc(self, mock_post):
  40. self._setup_data("http://example.com/webhook")
  41. mock_post.return_value.status_code = 200
  42. self.check.desc = """
  43. TEST _underscore_ `backticks` <u>underline</u> \\backslash\\ "quoted"
  44. """
  45. self.channel.notify(self.check)
  46. args, kwargs = mock_post.call_args
  47. text = kwargs["json"]["sections"][0]["text"]
  48. self.assertIn(r"\_underscore\_", text)
  49. self.assertIn(r"\`backticks\`", text)
  50. self.assertIn("&lt;u&gt;underline&lt;/u&gt;", text)
  51. self.assertIn(r"\\backslash\\ ", text)
  52. self.assertIn("&quot;quoted&quot;", text)
  53. @override_settings(MSTEAMS_ENABLED=False)
  54. def test_it_requires_msteams_enabled(self):
  55. self._setup_data("http://example.com/webhook")
  56. self.channel.notify(self.check)
  57. n = Notification.objects.get()
  58. self.assertEqual(n.error, "MS Teams notifications are not enabled.")