test_group.py 22 KB

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