test_group.py 21 KB

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