test_group.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. from datetime import timedelta
  2. from unittest import mock
  3. from django.utils import timezone
  4. from sentry.api.event_search import SearchFilter, SearchKey, SearchValue
  5. from sentry.api.serializers import serialize
  6. from sentry.api.serializers.models.group import GroupSerializerSnuba
  7. from sentry.issues.grouptype import PerformanceNPlusOneGroupType, ProfileFileIOGroupType
  8. from sentry.models.group import Group, GroupStatus
  9. from sentry.models.groupenvironment import GroupEnvironment
  10. from sentry.models.grouplink import GroupLink
  11. from sentry.models.groupresolution import GroupResolution
  12. from sentry.models.groupsnooze import GroupSnooze
  13. from sentry.models.groupsubscription import GroupSubscription
  14. from sentry.models.notificationsettingoption import NotificationSettingOption
  15. from sentry.notifications.types import NotificationSettingsOptionEnum
  16. from sentry.silo.base import SiloMode
  17. from sentry.testutils.cases import APITestCase, PerformanceIssueTestCase, SnubaTestCase
  18. from sentry.testutils.helpers.datetime import before_now, iso_format
  19. from sentry.testutils.silo import assume_test_silo_mode
  20. from sentry.types.group import PriorityLevel
  21. from sentry.users.models.user_option import UserOption
  22. from sentry.utils.samples import load_data
  23. from tests.sentry.issues.test_utils import SearchIssueTestMixin
  24. class GroupSerializerSnubaTest(APITestCase, SnubaTestCase):
  25. def setUp(self):
  26. super().setUp()
  27. self.min_ago = before_now(minutes=1)
  28. self.day_ago = before_now(days=1)
  29. self.week_ago = before_now(days=7)
  30. def test_permalink(self):
  31. group = self.create_group()
  32. result = serialize(group, self.user, serializer=GroupSerializerSnuba())
  33. assert "http://" in result["permalink"]
  34. assert f"{group.organization.slug}/issues/{group.id}" in result["permalink"]
  35. def test_permalink_outside_org(self):
  36. outside_user = self.create_user()
  37. group = self.create_group()
  38. result = serialize(group, outside_user, serializer=GroupSerializerSnuba())
  39. assert result["permalink"] is None
  40. def test_priority_high(self):
  41. outside_user = self.create_user()
  42. group = self.create_group(priority=PriorityLevel.HIGH)
  43. result = serialize(group, outside_user, serializer=GroupSerializerSnuba())
  44. assert result["priority"] == "high"
  45. def test_priority_medium(self):
  46. outside_user = self.create_user()
  47. group = self.create_group(priority=PriorityLevel.MEDIUM)
  48. result = serialize(group, outside_user, serializer=GroupSerializerSnuba())
  49. assert result["priority"] == "medium"
  50. def test_priority_none(self):
  51. outside_user = self.create_user()
  52. group = self.create_group()
  53. result = serialize(group, outside_user, serializer=GroupSerializerSnuba())
  54. assert result["priority"] is None
  55. assert result["priorityLockedAt"] is None
  56. def test_is_ignored_with_expired_snooze(self):
  57. now = timezone.now()
  58. user = self.create_user()
  59. group = self.create_group(status=GroupStatus.IGNORED)
  60. GroupSnooze.objects.create(group=group, until=now - timedelta(minutes=1))
  61. result = serialize(group, user, serializer=GroupSerializerSnuba())
  62. assert result["status"] == "unresolved"
  63. assert result["statusDetails"] == {}
  64. def test_is_ignored_with_valid_snooze(self):
  65. now = timezone.now()
  66. user = self.create_user()
  67. group = self.create_group(status=GroupStatus.IGNORED)
  68. snooze = GroupSnooze.objects.create(group=group, until=now + timedelta(minutes=1))
  69. result = serialize(group, user, serializer=GroupSerializerSnuba())
  70. assert result["status"] == "ignored"
  71. assert result["statusDetails"]["ignoreCount"] == snooze.count
  72. assert result["statusDetails"]["ignoreWindow"] == snooze.window
  73. assert result["statusDetails"]["ignoreUserCount"] == snooze.user_count
  74. assert result["statusDetails"]["ignoreUserWindow"] == snooze.user_window
  75. assert result["statusDetails"]["ignoreUntil"] == snooze.until
  76. assert result["statusDetails"]["actor"] is None
  77. def test_is_ignored_with_valid_snooze_and_actor(self):
  78. now = timezone.now()
  79. user = self.create_user()
  80. group = self.create_group(status=GroupStatus.IGNORED)
  81. GroupSnooze.objects.create(group=group, until=now + timedelta(minutes=1), actor_id=user.id)
  82. result = serialize(group, user, serializer=GroupSerializerSnuba())
  83. assert result["status"] == "ignored"
  84. assert result["statusDetails"]["actor"]["id"] == str(user.id)
  85. def test_resolved_in_next_release(self):
  86. release = self.create_release(project=self.project, version="a")
  87. user = self.create_user()
  88. group = self.create_group(status=GroupStatus.RESOLVED)
  89. GroupResolution.objects.create(
  90. group=group, release=release, type=GroupResolution.Type.in_next_release
  91. )
  92. result = serialize(group, user, serializer=GroupSerializerSnuba())
  93. assert result["status"] == "resolved"
  94. assert result["statusDetails"] == {"inNextRelease": True, "actor": None}
  95. def test_resolved_in_release(self):
  96. release = self.create_release(project=self.project, version="a")
  97. user = self.create_user()
  98. group = self.create_group(status=GroupStatus.RESOLVED)
  99. GroupResolution.objects.create(
  100. group=group, release=release, type=GroupResolution.Type.in_release
  101. )
  102. result = serialize(group, user, serializer=GroupSerializerSnuba())
  103. assert result["status"] == "resolved"
  104. assert result["statusDetails"] == {"inRelease": "a", "actor": None}
  105. def test_resolved_with_actor(self):
  106. release = self.create_release(project=self.project, version="a")
  107. user = self.create_user()
  108. group = self.create_group(status=GroupStatus.RESOLVED)
  109. GroupResolution.objects.create(
  110. group=group, release=release, type=GroupResolution.Type.in_release, actor_id=user.id
  111. )
  112. result = serialize(group, user, serializer=GroupSerializerSnuba())
  113. assert result["status"] == "resolved"
  114. assert result["statusDetails"]["actor"]["id"] == str(user.id)
  115. def test_resolved_in_commit(self):
  116. repo = self.create_repo(project=self.project)
  117. commit = self.create_commit(repo=repo)
  118. user = self.create_user()
  119. group = self.create_group(status=GroupStatus.RESOLVED)
  120. GroupLink.objects.create(
  121. group_id=group.id,
  122. project_id=group.project_id,
  123. linked_id=commit.id,
  124. linked_type=GroupLink.LinkedType.commit,
  125. relationship=GroupLink.Relationship.resolves,
  126. )
  127. result = serialize(group, user, serializer=GroupSerializerSnuba())
  128. assert result["status"] == "resolved"
  129. assert result["statusDetails"]["inCommit"]["id"] == commit.key
  130. @mock.patch("sentry.models.Group.is_over_resolve_age")
  131. def test_auto_resolved(self, mock_is_over_resolve_age):
  132. mock_is_over_resolve_age.return_value = True
  133. user = self.create_user()
  134. group = self.create_group(status=GroupStatus.UNRESOLVED)
  135. result = serialize(group, user, serializer=GroupSerializerSnuba())
  136. assert result["status"] == "resolved"
  137. assert result["statusDetails"] == {"autoResolved": True}
  138. def test_subscribed(self):
  139. user = self.create_user()
  140. group = self.create_group()
  141. GroupSubscription.objects.create(
  142. user_id=user.id, group=group, project=group.project, is_active=True
  143. )
  144. result = serialize(group, user, serializer=GroupSerializerSnuba())
  145. assert result["isSubscribed"]
  146. assert result["subscriptionDetails"] == {"reason": "unknown"}
  147. def test_explicit_unsubscribed(self):
  148. user = self.create_user()
  149. group = self.create_group()
  150. GroupSubscription.objects.create(
  151. user_id=user.id, group=group, project=group.project, is_active=False
  152. )
  153. result = serialize(group, user, serializer=GroupSerializerSnuba())
  154. assert not result["isSubscribed"]
  155. assert not result["subscriptionDetails"]
  156. def test_implicit_subscribed(self):
  157. user = self.create_user()
  158. group = self.create_group()
  159. combinations = (
  160. # (default, project, subscribed, has_details)
  161. (
  162. NotificationSettingsOptionEnum.ALWAYS,
  163. NotificationSettingsOptionEnum.DEFAULT,
  164. True,
  165. False,
  166. ),
  167. (
  168. NotificationSettingsOptionEnum.ALWAYS,
  169. NotificationSettingsOptionEnum.ALWAYS,
  170. True,
  171. False,
  172. ),
  173. (
  174. NotificationSettingsOptionEnum.ALWAYS,
  175. NotificationSettingsOptionEnum.SUBSCRIBE_ONLY,
  176. False,
  177. False,
  178. ),
  179. (
  180. NotificationSettingsOptionEnum.ALWAYS,
  181. NotificationSettingsOptionEnum.NEVER,
  182. False,
  183. True,
  184. ),
  185. (
  186. NotificationSettingsOptionEnum.DEFAULT,
  187. NotificationSettingsOptionEnum.DEFAULT,
  188. False,
  189. False,
  190. ),
  191. (
  192. NotificationSettingsOptionEnum.SUBSCRIBE_ONLY,
  193. NotificationSettingsOptionEnum.DEFAULT,
  194. False,
  195. False,
  196. ),
  197. (
  198. NotificationSettingsOptionEnum.SUBSCRIBE_ONLY,
  199. NotificationSettingsOptionEnum.ALWAYS,
  200. True,
  201. False,
  202. ),
  203. (
  204. NotificationSettingsOptionEnum.SUBSCRIBE_ONLY,
  205. NotificationSettingsOptionEnum.SUBSCRIBE_ONLY,
  206. False,
  207. False,
  208. ),
  209. (
  210. NotificationSettingsOptionEnum.SUBSCRIBE_ONLY,
  211. NotificationSettingsOptionEnum.NEVER,
  212. False,
  213. True,
  214. ),
  215. (
  216. NotificationSettingsOptionEnum.NEVER,
  217. NotificationSettingsOptionEnum.DEFAULT,
  218. False,
  219. True,
  220. ),
  221. (
  222. NotificationSettingsOptionEnum.NEVER,
  223. NotificationSettingsOptionEnum.ALWAYS,
  224. True,
  225. False,
  226. ),
  227. (
  228. NotificationSettingsOptionEnum.NEVER,
  229. NotificationSettingsOptionEnum.SUBSCRIBE_ONLY,
  230. False,
  231. False,
  232. ),
  233. (
  234. NotificationSettingsOptionEnum.NEVER,
  235. NotificationSettingsOptionEnum.NEVER,
  236. False,
  237. True,
  238. ),
  239. )
  240. for default_value, project_value, is_subscribed, has_details in combinations:
  241. with assume_test_silo_mode(SiloMode.CONTROL):
  242. UserOption.objects.clear_local_cache()
  243. NotificationSettingOption.objects.all().delete()
  244. if default_value != NotificationSettingsOptionEnum.DEFAULT:
  245. NotificationSettingOption.objects.create(
  246. user_id=user.id,
  247. scope_type="user",
  248. scope_identifier=user.id,
  249. value=default_value.value,
  250. type="workflow",
  251. )
  252. if project_value != NotificationSettingsOptionEnum.DEFAULT:
  253. NotificationSettingOption.objects.create(
  254. user_id=user.id,
  255. scope_type="project",
  256. scope_identifier=group.project.id,
  257. value=project_value.value,
  258. type="workflow",
  259. )
  260. result = serialize(group, user, serializer=GroupSerializerSnuba())
  261. subscription_details = result.get("subscriptionDetails")
  262. assert result["isSubscribed"] is is_subscribed
  263. assert (
  264. subscription_details == {"disabled": True}
  265. if has_details
  266. else subscription_details is None
  267. )
  268. def test_global_no_conversations_overrides_group_subscription(self):
  269. user = self.create_user()
  270. group = self.create_group()
  271. GroupSubscription.objects.create(
  272. user_id=user.id, group=group, project=group.project, is_active=True
  273. )
  274. with assume_test_silo_mode(SiloMode.CONTROL):
  275. NotificationSettingOption.objects.create(
  276. user_id=user.id,
  277. scope_type="user",
  278. scope_identifier=user.id,
  279. value="never",
  280. type="workflow",
  281. )
  282. result = serialize(group, user, serializer=GroupSerializerSnuba())
  283. assert not result["isSubscribed"]
  284. assert result["subscriptionDetails"] == {"disabled": True}
  285. def test_project_no_conversations_overrides_group_subscription(self):
  286. user = self.create_user()
  287. group = self.create_group()
  288. GroupSubscription.objects.create(
  289. user_id=user.id, group=group, project=group.project, is_active=True
  290. )
  291. with assume_test_silo_mode(SiloMode.CONTROL):
  292. NotificationSettingOption.objects.create(
  293. user_id=user.id,
  294. scope_type="project",
  295. scope_identifier=group.project.id,
  296. value="never",
  297. type="workflow",
  298. )
  299. result = serialize(group, user, serializer=GroupSerializerSnuba())
  300. assert not result["isSubscribed"]
  301. assert result["subscriptionDetails"] == {"disabled": True}
  302. def test_no_user_unsubscribed(self):
  303. group = self.create_group()
  304. result = serialize(group, serializer=GroupSerializerSnuba())
  305. assert not result["isSubscribed"]
  306. def test_seen_stats(self):
  307. environment = self.create_environment(project=self.project)
  308. environment2 = self.create_environment(project=self.project)
  309. events = []
  310. for event_id, env, user_id, timestamp in [
  311. ("a" * 32, environment, 1, iso_format(self.min_ago)),
  312. ("b" * 32, environment, 2, iso_format(self.min_ago)),
  313. ("c" * 32, environment2, 3, iso_format(self.week_ago)),
  314. ]:
  315. events.append(
  316. self.store_event(
  317. data={
  318. "event_id": event_id,
  319. "fingerprint": ["put-me-in-group1"],
  320. "timestamp": timestamp,
  321. "environment": env.name,
  322. "user": {"id": user_id},
  323. },
  324. project_id=self.project.id,
  325. )
  326. )
  327. # Assert all events are in the same group
  328. (group_id,) = {e.group.id for e in events}
  329. group = Group.objects.get(id=group_id)
  330. group.times_seen = 3
  331. group.first_seen = self.week_ago - timedelta(days=5)
  332. group.last_seen = self.week_ago
  333. group.save()
  334. # should use group columns when no environments arg passed
  335. result = serialize(group, serializer=GroupSerializerSnuba(environment_ids=[]))
  336. assert result["count"] == "3"
  337. assert iso_format(result["lastSeen"]) == iso_format(self.min_ago)
  338. assert result["firstSeen"] == group.first_seen
  339. # update this to something different to make sure it's being used
  340. group_env = GroupEnvironment.objects.get(group_id=group_id, environment_id=environment.id)
  341. group_env.first_seen = self.day_ago - timedelta(days=3)
  342. group_env.save()
  343. group_env2 = GroupEnvironment.objects.get(group_id=group_id, environment_id=environment2.id)
  344. result = serialize(
  345. group,
  346. serializer=GroupSerializerSnuba(environment_ids=[environment.id, environment2.id]),
  347. )
  348. assert result["count"] == "3"
  349. # result is rounded down to nearest second
  350. assert iso_format(result["lastSeen"]) == iso_format(self.min_ago)
  351. assert iso_format(result["firstSeen"]) == iso_format(group_env.first_seen)
  352. assert group_env2.first_seen is not None
  353. assert group_env2.first_seen > group_env.first_seen
  354. assert result["userCount"] == 3
  355. result = serialize(
  356. group,
  357. serializer=GroupSerializerSnuba(
  358. environment_ids=[environment.id, environment2.id],
  359. start=self.week_ago - timedelta(hours=1),
  360. end=self.week_ago + timedelta(hours=1),
  361. ),
  362. )
  363. assert result["userCount"] == 1
  364. assert iso_format(result["lastSeen"]) == iso_format(self.week_ago)
  365. assert iso_format(result["firstSeen"]) == iso_format(self.week_ago)
  366. assert result["count"] == "1"
  367. def test_get_start_from_seen_stats(self):
  368. for days, expected in [(None, 30), (0, 14), (1000, 90)]:
  369. last_seen = None if days is None else before_now(days=days)
  370. start = GroupSerializerSnuba._get_start_from_seen_stats(
  371. {
  372. mock.sentinel.group: {
  373. "last_seen": last_seen,
  374. "first_seen": None,
  375. "times_seen": 0,
  376. "user_count": 0,
  377. }
  378. }
  379. )
  380. assert iso_format(start) == iso_format(before_now(days=expected))
  381. def test_skipped_date_timestamp_filters(self):
  382. group = self.create_group()
  383. serializer = GroupSerializerSnuba(
  384. search_filters=[
  385. SearchFilter(
  386. SearchKey("timestamp"),
  387. ">",
  388. SearchValue(before_now(hours=1)),
  389. ),
  390. SearchFilter(
  391. SearchKey("timestamp"),
  392. "<",
  393. SearchValue(before_now(seconds=1)),
  394. ),
  395. SearchFilter(
  396. SearchKey("date"),
  397. ">",
  398. SearchValue(before_now(hours=1)),
  399. ),
  400. SearchFilter(
  401. SearchKey("date"),
  402. "<",
  403. SearchValue(before_now(seconds=1)),
  404. ),
  405. ]
  406. )
  407. assert not serializer.conditions
  408. result = serialize(group, self.user, serializer=serializer)
  409. assert result["id"] == str(group.id)
  410. class PerformanceGroupSerializerSnubaTest(
  411. APITestCase,
  412. SnubaTestCase,
  413. PerformanceIssueTestCase,
  414. ):
  415. def test_perf_seen_stats(self):
  416. proj = self.create_project()
  417. first_group_fingerprint = f"{PerformanceNPlusOneGroupType.type_id}-group1"
  418. timestamp = timezone.now() - timedelta(days=5)
  419. times = 5
  420. for _ in range(0, times):
  421. event_data = load_data(
  422. "transaction-n-plus-one",
  423. timestamp=timestamp + timedelta(minutes=1),
  424. start_timestamp=timestamp + timedelta(minutes=1),
  425. )
  426. event_data["user"] = {"email": "test1@example.com"}
  427. self.create_performance_issue(
  428. event_data=event_data, fingerprint=first_group_fingerprint, project_id=proj.id
  429. )
  430. event_data = load_data(
  431. "transaction-n-plus-one",
  432. timestamp=timestamp + timedelta(minutes=2),
  433. start_timestamp=timestamp + timedelta(minutes=2),
  434. )
  435. event_data["user"] = {"email": "test2@example.com"}
  436. event = self.create_performance_issue(
  437. event_data=event_data, fingerprint=first_group_fingerprint, project_id=proj.id
  438. )
  439. first_group = event.group
  440. result = serialize(
  441. first_group,
  442. serializer=GroupSerializerSnuba(
  443. start=timezone.now() - timedelta(days=60),
  444. end=timezone.now() + timedelta(days=10),
  445. ),
  446. )
  447. assert result["userCount"] == 2
  448. assert iso_format(result["lastSeen"]) == iso_format(timestamp + timedelta(minutes=2))
  449. assert iso_format(result["firstSeen"]) == iso_format(timestamp + timedelta(minutes=1))
  450. assert result["count"] == str(times + 1)
  451. class ProfilingGroupSerializerSnubaTest(
  452. APITestCase,
  453. SnubaTestCase,
  454. SearchIssueTestMixin,
  455. ):
  456. def test_profiling_seen_stats(self):
  457. proj = self.create_project()
  458. environment = self.create_environment(project=proj)
  459. first_group_fingerprint = f"{ProfileFileIOGroupType.type_id}-group1"
  460. timestamp = (timezone.now() - timedelta(days=5)).replace(hour=0, minute=0, second=0)
  461. times = 5
  462. for incr in range(0, times):
  463. # for user_0 - user_4, first_group
  464. self.store_search_issue(
  465. proj.id,
  466. incr,
  467. [first_group_fingerprint],
  468. environment.name,
  469. timestamp + timedelta(minutes=incr),
  470. )
  471. # user_5, another_group
  472. event, issue_occurrence, group_info = self.store_search_issue(
  473. proj.id,
  474. 5,
  475. [first_group_fingerprint],
  476. environment.name,
  477. timestamp + timedelta(minutes=5),
  478. )
  479. assert group_info is not None
  480. first_group = group_info.group
  481. result = serialize(
  482. first_group,
  483. serializer=GroupSerializerSnuba(
  484. environment_ids=[environment.id],
  485. start=timestamp - timedelta(days=1),
  486. end=timestamp + timedelta(days=1),
  487. ),
  488. )
  489. assert result["userCount"] == 6
  490. assert iso_format(result["lastSeen"]) == iso_format(timestamp + timedelta(minutes=5))
  491. assert iso_format(result["firstSeen"]) == iso_format(timestamp)
  492. assert result["count"] == str(times + 1)