test_group.py 22 KB

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