test_group.py 22 KB

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