test_group.py 22 KB

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