test_api.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. from unittest import mock
  2. from django.urls import reverse
  3. from django.utils import timezone
  4. from django.utils.dateparse import parse_datetime
  5. from freezegun import freeze_time
  6. from model_bakery import baker
  7. from apps.uptime.models import Monitor
  8. from glitchtip.test_utils.test_case import GlitchTestCase
  9. class UptimeAPITestCase(GlitchTestCase):
  10. @classmethod
  11. def setUpTestData(cls):
  12. cls.create_user()
  13. cls.list_url = reverse(
  14. "api:list_monitors",
  15. args=[cls.organization.slug],
  16. )
  17. def setUp(self):
  18. self.client.force_login(self.user)
  19. @mock.patch("apps.uptime.tasks.perform_checks.run")
  20. def test_list(self, mocked):
  21. monitor = baker.make(
  22. "uptime.Monitor", organization=self.organization, url="http://example.com"
  23. )
  24. baker.make(
  25. "uptime.MonitorCheck",
  26. monitor=monitor,
  27. is_up=False,
  28. start_check="2021-09-19T15:39:31Z",
  29. )
  30. baker.make(
  31. "uptime.MonitorCheck",
  32. monitor=monitor,
  33. is_up=True,
  34. is_change=True,
  35. start_check="2021-09-19T15:40:31Z",
  36. )
  37. res = self.client.get(self.list_url)
  38. self.assertContains(res, monitor.name)
  39. data = res.json()
  40. self.assertEqual(data[0]["isUp"], True)
  41. self.assertEqual(data[0]["lastChange"], "2021-09-19T15:40:31Z")
  42. @mock.patch("apps.uptime.tasks.perform_checks.run")
  43. def test_list_aggregation(self, _):
  44. """Test up and down event aggregations"""
  45. monitor = baker.make(
  46. "uptime.Monitor", organization=self.organization, url="http://example.com"
  47. )
  48. start_time = timezone.now()
  49. # Make 100 events, 50 up and then 50 up and down every minute
  50. for i in range(99):
  51. is_up = i % 2
  52. if i < 50:
  53. is_up = True
  54. current_time = start_time + timezone.timedelta(minutes=i)
  55. with freeze_time(current_time):
  56. baker.make(
  57. "uptime.MonitorCheck",
  58. monitor=monitor,
  59. is_up=is_up,
  60. start_check=current_time,
  61. )
  62. with freeze_time(current_time):
  63. res = self.client.get(self.list_url)
  64. self.assertEqual(len(res.json()[0]["checks"]), 60)
  65. @mock.patch("apps.uptime.tasks.perform_checks.run")
  66. def test_create_http_monitor(self, mocked):
  67. data = {
  68. "monitorType": "Ping",
  69. "name": "Test",
  70. "url": "https://www.google.com",
  71. "expectedStatus": 200,
  72. "interval": 60,
  73. "project": self.project.pk,
  74. "timeout": 25,
  75. }
  76. res = self.client.post(self.list_url, data, content_type="application/json")
  77. self.assertEqual(res.status_code, 201)
  78. monitor = Monitor.objects.all().first()
  79. self.assertEqual(monitor.name, data["name"])
  80. self.assertEqual(monitor.timeout, data["timeout"])
  81. self.assertEqual(monitor.organization, self.organization)
  82. self.assertEqual(monitor.project, self.project)
  83. mocked.assert_called_once()
  84. @mock.patch("apps.uptime.tasks.perform_checks.run")
  85. def test_create_port_monitor(self, mocked):
  86. """Port monitor URLs should be converted to domain:port format, with protocol removed"""
  87. data = {
  88. "monitorType": "TCP Port",
  89. "name": "Test",
  90. "url": "http://example.com:80",
  91. "expectedStatus": None,
  92. "interval": 60,
  93. }
  94. res = self.client.post(self.list_url, data, content_type="application/json")
  95. self.assertEqual(res.status_code, 201)
  96. monitor = Monitor.objects.all().first()
  97. self.assertEqual(monitor.url, "example.com:80")
  98. mocked.assert_called_once()
  99. def test_create_port_monitor_validation(self):
  100. """Port monitor URLs should be converted to domain:port format, with protocol removed"""
  101. data = {
  102. "monitorType": "TCP Port",
  103. "name": "Test",
  104. "url": "example:80:",
  105. "expectedStatus": "",
  106. "interval": 60,
  107. }
  108. res = self.client.post(self.list_url, data)
  109. self.assertEqual(res.status_code, 400)
  110. def test_create_invalid(self):
  111. data = {
  112. "monitorType": "Ping",
  113. "name": "Test",
  114. "url": "foo:80:",
  115. "expectedStatus": 200,
  116. "interval": 60,
  117. "project": self.project.pk,
  118. }
  119. res = self.client.post(self.list_url, data)
  120. self.assertEqual(res.status_code, 400)
  121. data = {
  122. "monitorType": "Ping",
  123. "name": "Test",
  124. "url": "https://www.google.com",
  125. "expectedStatus": 200,
  126. "interval": 60,
  127. "project": self.project.pk,
  128. "timeout": 999,
  129. }
  130. res = self.client.post(self.list_url, data)
  131. self.assertEqual(res.status_code, 400)
  132. @mock.patch("apps.uptime.tasks.perform_checks.run")
  133. def test_create_expected_status(self, mocked):
  134. data = {
  135. "monitorType": "Ping",
  136. "name": "Test",
  137. "url": "http://example.com",
  138. "expectedStatus": None,
  139. "interval": 60,
  140. "project": self.project.pk,
  141. }
  142. res = self.client.post(self.list_url, data, content_type="application/json")
  143. mocked.assert_called_once()
  144. self.assertEqual(res.status_code, 201)
  145. self.assertTrue(Monitor.objects.filter(expected_status=None).exists())
  146. @mock.patch("apps.uptime.tasks.perform_checks.run")
  147. def test_monitor_retrieve(self, _):
  148. """Test monitor details endpoint. Unlike the list view,
  149. checks here should include response time for the frontend graph"""
  150. environment = baker.make(
  151. "environments.Environment", organization=self.organization
  152. )
  153. monitor = baker.make(
  154. "uptime.Monitor",
  155. organization=self.organization,
  156. url="http://example.com",
  157. monitor_type="Heartbeat",
  158. environment=environment,
  159. )
  160. now = timezone.now()
  161. baker.make(
  162. "uptime.MonitorCheck",
  163. monitor=monitor,
  164. is_up=False,
  165. is_change=True,
  166. start_check="2021-09-19T15:39:31Z",
  167. )
  168. baker.make(
  169. "uptime.MonitorCheck",
  170. monitor=monitor,
  171. is_up=True,
  172. is_change=True,
  173. start_check=now,
  174. )
  175. url = reverse("api:get_monitor", args=[self.organization.slug, monitor.pk])
  176. res = self.client.get(url)
  177. data = res.json()
  178. self.assertEqual(data["isUp"], True)
  179. self.assertEqual(parse_datetime(data["lastChange"]), now)
  180. self.assertEqual(data["environment"], environment.pk)
  181. self.assertIn("responseTime", data["checks"][0])
  182. @mock.patch("apps.uptime.tasks.perform_checks.run")
  183. def test_monitor_checks_list(self, _):
  184. monitor = baker.make(
  185. "uptime.Monitor",
  186. organization=self.organization,
  187. url="http://example.com",
  188. )
  189. baker.make(
  190. "uptime.MonitorCheck",
  191. monitor=monitor,
  192. is_up=False,
  193. start_check="2021-09-19T15:39:31Z",
  194. )
  195. url = reverse(
  196. "api:list_monitor_checks", args=[self.organization.slug, monitor.pk]
  197. )
  198. res = self.client.get(url)
  199. self.assertContains(res, "2021-09-19T15:39:31Z")
  200. @mock.patch("apps.uptime.tasks.perform_checks.run")
  201. def test_monitor_update(self, _):
  202. monitor = baker.make(
  203. "uptime.Monitor",
  204. organization=self.organization,
  205. url="http://example.com",
  206. interval="60",
  207. monitor_type="Ping",
  208. expected_status="200",
  209. )
  210. url = reverse("api:update_monitor", args=[self.organization.slug, monitor.pk])
  211. data = {
  212. "name": "New name",
  213. "url": "https://differentexample.com",
  214. "monitorType": "GET",
  215. "expectedStatus": "200",
  216. "interval": 60,
  217. "project": self.project.id,
  218. }
  219. res = self.client.put(url, data, content_type="application/json")
  220. self.assertEqual(res.json()["monitorType"], "GET")
  221. self.assertEqual(res.json()["project"], self.project.id)
  222. self.assertEqual(res.json()["url"], "https://differentexample.com")
  223. @mock.patch("apps.uptime.tasks.perform_checks.run")
  224. def test_list_isolation(self, _):
  225. """Users should only access monitors in their organization"""
  226. user2 = baker.make("users.user")
  227. org2 = baker.make("organizations_ext.Organization")
  228. org2.add_user(user2)
  229. monitor1 = baker.make(
  230. "uptime.Monitor", url="http://example.com", organization=self.organization
  231. )
  232. monitor2 = baker.make(
  233. "uptime.Monitor", url="http://example.com", organization=org2
  234. )
  235. res = self.client.get(self.list_url)
  236. self.assertContains(res, monitor1.name)
  237. self.assertNotContains(res, monitor2.name)
  238. def test_create_isolation(self):
  239. """Users should only make monitors in their organization"""
  240. org2 = baker.make("organizations_ext.Organization")
  241. url = reverse("api:list_monitors", args=[org2.slug])
  242. data = {
  243. "monitorType": "Ping",
  244. "name": "Test",
  245. "url": "https://www.google.com",
  246. "expectedStatus": 200,
  247. "interval": 60,
  248. "project": self.project.pk,
  249. }
  250. res = self.client.post(url, data)
  251. self.assertEqual(res.status_code, 400)